

# HTTP client examples for the AWS AppConfig extension in AWS Systems Manager Cloud Extensions

The following examples call the HTTP interface of the extension directly, in Python and in Java.

A request has the following parts:
+ The method `POST` and the URL `http://localhost:5333/appconfig/`.
+ The header `X-Amz-Target: AppConfig.<Operation>`, where the operation is `GetConfiguration` or `GetFlag`.
+ The header `Content-Type: application/x-amz-json-1.1`.
+ The parameters as a JSON body.

A response has the following parts:
+ For a success, the status `200` and a JSON body.
+ For an error, a 4xx or 5xx status and a JSON body with `__type`, `message`, and, for most errors, `reason`. A `ValidationException` with the reason `FIELD_VALIDATION_FAILED` also has `errors`.

The examples send no credentials. These examples work only when the authentication of the profile is `none`. To sign requests, see [Authentication](cloud-extensions-security.md#cloud-extensions-security-authentication).

The examples use the resources from the [Examples with curl for the AWS AppConfig extension in AWS Systems Manager Cloud Extensions](cloud-extensions-ext-appconfig-curl-examples.md): the application `test-demo-app`, the environment `demo`, and the configuration profiles `service-settings` (freeform JSON) and `checkout-flags` (feature flags).

**Topics**
+ [Python examples](#cloud-extensions-ext-appconfig-http-examples-python-examples)
+ [Java examples](#cloud-extensions-ext-appconfig-http-examples-java-examples)

## Python examples
<a name="cloud-extensions-ext-appconfig-http-examples-python-examples"></a>

The Python examples use only the Python standard library, a Python version that the AWS SDK for Python (Boto3) supports.

### Helper
<a name="cloud-extensions-ext-appconfig-http-examples-helper"></a>

`appconfig_extension.py` sends one request and returns the parsed response. On an error response, it raises `ExtensionError`.

```python
import json
import urllib.error
import urllib.request
ENDPOINT = "http://localhost:5333/appconfig/"
class ExtensionError(Exception):
    def __init__(self, status, body):
        self.status = status
        self.type = body.get("__type")
        self.reason = body.get("reason")
        self.errors = body.get("errors", [])
        super().__init__(body.get("message"))
def call(operation, params):
    request = urllib.request.Request(
        ENDPOINT,
        data=json.dumps(params).encode(),
        method="POST",
        headers={
            "X-Amz-Target": "AppConfig." + operation,
            "Content-Type": "application/x-amz-json-1.1",
        },
    )
    try:
        with urllib.request.urlopen(request) as response:
            return json.loads(response.read())
    except urllib.error.HTTPError as e:
        raise ExtensionError(e.code, json.loads(e.read())) from None
```

### GetConfiguration
<a name="cloud-extensions-ext-appconfig-http-examples-getconfiguration"></a>

`get_configuration.py`:

```python
import base64
from appconfig_extension import call
out = call("GetConfiguration", {
    "application": "test-demo-app",
    "environment": "demo",
    "configuration": "service-settings",
})
print("contentType: ", out["contentType"])
print("revision:    ", out["revision"])
print("versionLabel:", out.get("versionLabel"))
print("content:     ", base64.b64decode(out["content"]).decode().strip())
```

```
contentType:  application/json
revision:     0sU6FR2TSJI
versionLabel: baseline
content:      {"greeting":"hello from v1","maxItems":10,"features":["search"]}
```

### GetFlag, without and with context
<a name="cloud-extensions-ext-appconfig-http-examples-getflag-without-and-with-context"></a>

`get_flag.py`:

```python
from appconfig_extension import call
def show(out):
    print(f"enabled={out['enabled']} variant={out.get('variant')}")
    for key, value in out.get("attributes", {}).items():
        (kind, v), = value.items()  # each value has one member that names its type
        print(f"  {key} ({kind}) = {v}")
flag = {
    "application": "test-demo-app",
    "environment": "demo",
    "configuration": "checkout-flags",
    "flag": "quick-pay",
}
# Without context: the flag's default variant.
show(call("GetFlag", flag))
# With context: the first variant whose rule matches.
show(call("GetFlag", {**flag, "context": {"country": "UK", "tier": "gold"}}))
```

```
enabled=False variant=off
enabled=True variant=ukPremium
  currency (string) = GBP
  express (boolean) = True
  maxAmount (number) = 500
  methods (stringList) = ['card', 'wallet']
  tiers (numberList) = [1, 2.5]
```

### Errors
<a name="cloud-extensions-ext-appconfig-http-examples-errors"></a>

`errors.py`:

```python
from appconfig_extension import ExtensionError, call
base = {"application": "test-demo-app", "environment": "demo"}
for label, operation, params in [
    ("configuration profile that doesn't exist", "GetConfiguration",
     {**base, "configuration": "no-such-profile"}),
    ("flag that doesn't exist", "GetFlag",
     {**base, "configuration": "checkout-flags", "flag": "no-such-flag"}),
    ("flag key that isn't valid", "GetFlag",
     {**base, "configuration": "checkout-flags", "flag": "Quick Pay"}),
]:
    try:
        call(operation, params)
        print(f"{label}: no error")
    except ExtensionError as e:
        print(f"{label}: {e.status} {e.type} {e.reason}: {e}")
        for detail in e.errors:
            (kind, v), = detail.items()  # fieldConstraint or semanticError
            print(f"  {kind}: {v}")
```

```
configuration profile that doesn't exist: 400 ValidationException FIELD_VALIDATION_FAILED: ConfigurationProfile not found
  semanticError: {'problem': 'RESOURCE_NOT_FOUND', 'item': 'ConfigurationProfile'}
flag that doesn't exist: 400 ValidationException FIELD_VALIDATION_FAILED: flag 'no-such-flag' not found in configuration 'checkout-flags'
  semanticError: {'problem': 'FLAG_NOT_FOUND', 'item': 'flag', 'value': 'no-such-flag'}
flag key that isn't valid: 400 ValidationException FIELD_VALIDATION_FAILED: 1 validation error: flag must match ^[a-z][a-zA-Z\d_-]{0,63}$
  fieldConstraint: {'constraint': {'pattern': {'pattern': '^[a-z][a-zA-Z\\d_-]{0,63}$'}}, 'field': 'flag', 'value': 'Quick Pay'}
```

## Java examples
<a name="cloud-extensions-ext-appconfig-http-examples-java-examples"></a>

The Java examples use Java 11 or later, the JDK's `java.net.http.HttpClient`, and [Jackson](https://github.com/FasterXML/jackson-databind) to read and write JSON. Add Jackson to your build, for example with Maven:

```
{{dependency}}
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  {{version}}2.17.2</version>
</dependency>
```

### Helper
<a name="cloud-extensions-ext-appconfig-http-examples-helper-2"></a>

`AppConfigExtension.java` sends one request and returns the parsed response. On an error response, it throws `ExtensionException`.

```java
package example;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
/** Calls the AWS AppConfig extension's operations over HTTP, without a signature. */
public final class AppConfigExtension {
    private static final URI ENDPOINT = URI.create("http://localhost:5333/appconfig/");
    private static final HttpClient HTTP = HttpClient.newHttpClient();
    private static final ObjectMapper JSON = new ObjectMapper();
    /** An error response from the extension. */
    public static final class ExtensionException extends RuntimeException {
        public final int status;
        public final JsonNode body;
        ExtensionException(int status, JsonNode body) {
            super(body.path("message").asText());
            this.status = status;
            this.body = body;
        }
        public String type() { return body.path("__type").asText(); }
        public String reason() { return body.path("reason").asText(null); }
        public JsonNode errors() { return body.path("errors"); }
    }
    public static JsonNode call(String operation, Map<String, Object> params)
            throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder(ENDPOINT)
                .header("X-Amz-Target", "AppConfig." + operation)
                .header("Content-Type", "application/x-amz-json-1.1")
                .POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(params)))
                .build();
        HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        JsonNode body = JSON.readTree(response.body());
        if (response.statusCode() != 200) {
            throw new ExtensionException(response.statusCode(), body);
        }
        return body;
    }
    private AppConfigExtension() {}
}
```

### GetConfiguration
<a name="cloud-extensions-ext-appconfig-http-examples-getconfiguration-2"></a>

```java
package example;
import com.fasterxml.jackson.databind.JsonNode;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
public class GetConfigurationExample {
    public static void main(String[] args) throws Exception {
        JsonNode out = AppConfigExtension.call("GetConfiguration", Map.of(
                "application", "test-demo-app",
                "environment", "demo",
                "configuration", "service-settings"));
        byte[] content = Base64.getDecoder().decode(out.path("content").asText());
        System.out.println("contentType:  " + out.path("contentType").asText());
        System.out.println("revision:     " + out.path("revision").asText());
        System.out.println("versionLabel: " + out.path("versionLabel").asText(null));
        System.out.println("content:      " + new String(content, StandardCharsets.UTF_8).strip());
    }
}
```

```
contentType:  application/json
revision:     0sU6FR2TSJI
versionLabel: baseline
content:      {"greeting":"hello from v1","maxItems":10,"features":["search"]}
```

### GetFlag, without and with context
<a name="cloud-extensions-ext-appconfig-http-examples-getflag-without-and-with-context-2"></a>

```java
package example;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class GetFlagExample {
    static void print(JsonNode out) {
        System.out.println("enabled=" + out.path("enabled").asBoolean()
                + " variant=" + out.path("variant").asText(null));
        Iterator<Map.Entry<String, JsonNode>> attributes = out.path("attributes").fields();
        while (attributes.hasNext()) {
            Map.Entry<String, JsonNode> attribute = attributes.next();
            // Each value has one member that names its type, such as {"string":"GBP"}.
            Map.Entry<String, JsonNode> value = attribute.getValue().fields().next();
            System.out.println("  " + attribute.getKey() + " (" + value.getKey() + ") = " + value.getValue());
        }
    }
    public static void main(String[] args) throws Exception {
        Map<String, Object> flag = new HashMap<>(Map.of(
                "application", "test-demo-app",
                "environment", "demo",
                "configuration", "checkout-flags",
                "flag", "quick-pay"));
        // Without context: the flag's default variant.
        print(AppConfigExtension.call("GetFlag", flag));
        // With context: the first variant whose rule matches.
        flag.put("context", Map.of("country", "UK", "tier", "gold"));
        print(AppConfigExtension.call("GetFlag", flag));
    }
}
```

```
enabled=false variant=off
enabled=true variant=ukPremium
  currency (string) = "GBP"
  express (boolean) = true
  maxAmount (number) = 500
  methods (stringList) = ["card","wallet"]
  tiers (numberList) = [1,2.5]
```

### Errors
<a name="cloud-extensions-ext-appconfig-http-examples-errors-2"></a>

```java
package example;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Map;
public class ErrorsExample {
    static void call(String label, String operation, Map<String, Object> params) throws Exception {
        try {
            AppConfigExtension.call(operation, params);
            System.out.println(label + ": no error");
        } catch (AppConfigExtension.ExtensionException e) {
            System.out.println(label + ": " + e.status + " " + e.type() + " " + e.reason() + ": " + e.getMessage());
            for (JsonNode detail : e.errors()) {
                // Each entry has one member: fieldConstraint or semanticError.
                Map.Entry<String, JsonNode> problem = detail.fields().next();
                System.out.println("  " + problem.getKey() + ": " + problem.getValue());
            }
        }
    }
    public static void main(String[] args) throws Exception {
        call("configuration profile that doesn't exist", "GetConfiguration", Map.of(
                "application", "test-demo-app", "environment", "demo", "configuration", "no-such-profile"));
        call("flag that doesn't exist", "GetFlag", Map.of(
                "application", "test-demo-app", "environment", "demo", "configuration", "checkout-flags",
                "flag", "no-such-flag"));
        call("flag key that isn't valid", "GetFlag", Map.of(
                "application", "test-demo-app", "environment", "demo", "configuration", "checkout-flags",
                "flag", "Quick Pay"));
    }
}
```

```
configuration profile that doesn't exist: 400 ValidationException FIELD_VALIDATION_FAILED: ConfigurationProfile not found
  semanticError: {"problem":"RESOURCE_NOT_FOUND","item":"ConfigurationProfile"}
flag that doesn't exist: 400 ValidationException FIELD_VALIDATION_FAILED: flag 'no-such-flag' not found in configuration 'checkout-flags'
  semanticError: {"problem":"FLAG_NOT_FOUND","item":"flag","value":"no-such-flag"}
flag key that isn't valid: 400 ValidationException FIELD_VALIDATION_FAILED: 1 validation error: flag must match ^[a-z][a-zA-Z\d_-]{0,63}$
  fieldConstraint: {"constraint":{"pattern":{"pattern":"^[a-z][a-zA-Z\\d_-]{0,63}$"}},"field":"flag","value":"Quick Pay"}
```