Accept Array As Query Parameter In API Gateway

The guide demonstrates how to accept the array as the query parameter in API Gateway proxy and non-proxy Lambda integrations

Friday, June 11, 2021

Lambda Non-Proxy Integration

In the non-proxy lambda integration, it is required to map the query parameter in the request mapping template to the lambda handler model property. Suppose our DTO has form of

The request mapping template will then look like (CDK script)

The #if directive is present to protect against empty query string value for the array, which would create invalid JSON.

This is all that is required to accept the array as the query parameter in non-proxy lambda integration. Additionally, let us show how to send the array to the API, as it might be a little counter-intuitive. Suppose our API URL is https://example.com. The request URL with query parameters would then look like

https://example.com?MyQueryStringValue=value&MyQuerystringArray=["item1","item2"] // non uri-encoded
https://example.com?MyQueryStringValue=value&MyQuerystringArray=%5B%22item1%22%2C%22item2%22%5D // uri-encoded
                    

The value for the array type query parameter is the JSON representation of the array so that the lambda runtime can deserialize it properly for the handler. Notice we must URI encode the value so that it can be transmitted over the network.

Lambda Proxy Integration

In the proxy lambda integration, we need to work with the standardized payload format coming into our proxy lambda. The important part is

Therefore, to get our MyQuerystringArray array values, handler code (in C#) can look like

Lastly, let us look how request URL with query string payload to the lambda proxy API will look like

https://example.com?MyQueryStringValue=value&MyQuerystringArray=item1&MyQuerystringArray=item2
                    

For lambda proxy integration, array items are sent by duplicating the query keys equalling the value of the array parameter name, i.e. MyQuerystringArray=item1&MyQuerystringArray=item2.

Further Reading

API Gateway request mapping template - https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#input-variable-reference
Lambda proxy integration input format - https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format