by

Generic Amazon API Gateway Java Client (SDK)

I’ve recently released apigateway-generic-java-sdk, a simple generic Java client for Amazon API Gateway endpoints for those that don’t necessarily want to generate a strongly-typed SDK. This is particularly useful when the API definition is changing rapidly or when you don’t want to go through the effort of generating and bundling an SDK, such as when prototyping or scripting.

It is optimized to run from a Lambda function and does not require any extra dependencies beyond the AWS SDK, which is already bundled in the Lambda runtime.

Features

  • AWS SigV4 request signing. Supports APIs authenticated with IAM auth using standard AWSCredentialsProvider interface
  • API Keys
  • Custom headers
  • Throws exceptions for non-2xx response codes
  • Compatibility with existing AWS SDK client configuration (connections, retry policies, etc)
  • Runs in AWS Lambda functions with no additional dependencies

Example

GenericApiGatewayClient client = new GenericApiGatewayClientBuilder()
        .withClientConfiguration(new ClientConfiguration())
        .withCredentials(new EnvironmentVariableCredentialsProvider())
        .withEndpoint("https://XXXXXX.execute-api.us-east-1.amazonaws.com")
        .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
        .withApiKey("XXXXXXXXXXXXXXX")
        .build();

Map headers = new HashMap<>();
headers.put("Content-Type", "application/json");

try {
    GenericApiGatewayResponse response = client.execute(
            new GenericApiGatewayRequestBuilder()
                    .withBody(new ByteArrayInputStream("foo".getBytes()))
                    .withHttpMethod(HttpMethodName.POST)
                    .withHeaders(headers)
                    .withResourcePath("/stage/path").build());
    
    System.out.println("Response: " + response.getBody());
    System.out.println("Status: " + response.getHttpResponse.getStatusCode());
    
} catch (GenericApiGatewayException e) {   // exception thrown for any non-2xx response
    System.out.println(String.format("Client threw exception with message %s and status code %s", 
            e.getMessage(), e.getStatusCode()));
}

To get the code and for more examples, see the GitHub repo.

Write a Comment

Comment