Implementing request parameters validation in Amazon API Gateway REST API with Cloud Development Kit (CDK)

3 minute read
Content level: Advanced
0

The purpose of this blog is to showcase how you can configure Amazon API Gateway’s native capability of request parameter validation using AWS Cloud Development Kit (CDK). We will go over how you can configure required URL query string parameters by configuring a sample application.

Introduction

AWS Cloud Development Kit (CDK) is a powerful tool to model and provision your cloud application resources through AWS CloudFormation using familiar programming languages such as TypeScript, Python, Java, .NET, and Go (in Developer Preview).

Amazon API Gateway is a fully managed service that allows developers to create, publish, maintain, monitor and secure APIs at any scale. It certainly acts as a front door to seamlessly integrate with various AWS Services such as AWS Lambda functions, Amazon DynamoDB allowing you to build serverless applications.

Request validation in API Gateway and why is it important?

Request validation is a native API Gateway feature which allows you to ensure that the required request parameters specific to your application are valid and non-null in the incoming requests before they reach to your backend integration. This not only helps you improve error handling in your applications but also offloads unnecessary processing required on the backend. If the validation fails, API Gateway can provide informative error responses to the client to help them understand what went wrong and how to correct their requests which we will see in the following example.

Configuring request parameter validation in API Gateway with a sample application

For the purpose of simplifying the understanding of request parameter validation and the process to configure it with AWS CDK, we will configure a sample application and the request flow looks like this:

  • Users make POST calls to API Gateway with query string parameters.
  • API Gateway validates the request to ensure that the required parameters like “firstname”, “lastname” and “email” are present.
  • Lambda function checks if the record is available in the Amazon DynamoDB database and if the data does not exist, it will generate a unique id for the record and stores the data.

Sample Application Architecture and Request Flow

We are going to configure this sample application step-by-step with AWS CDK and then add the required parameter validations to the API Gateway.

Step 1: Create DynamoDB Table:

dynamodb=_dynamodb.Table(self,"DynamoDbExampleTable",
                         partition_key=_dynamodb.Attribute(name="first_name",type=_dynamodb.AttributeType.STRING),
                         sort_key=_dynamodb.Attribute(name="email_address",type=_dynamodb.AttributeType.STRING),
                         )

Step 2: Create Lambda Function:

lambda_function=_lambda.Function(self,"PutNameExampleFunction",
                                 runtime=_lambda.Runtime.PYTHON_3_11,
                                 code=_lambda.Code.from_asset(os.path.join(os.path.dirname(__file__),"LambdaFunctions")),
                                 handler='lambda_put_name.lambda_handler'
                                 )

Step 3: Grant Lambda function permissions to DynamoDB:

dynamodb.grant_read_write_data(lambda_function)

Step 4: Create API Gateway REST API:

api_gateway=_apigateway.RestApi(self,"ApigatewayExample")

Step 5: Create API Gateway REST API resource:

api_put_name_resource=api_gateway.root.add_resource("put-name")

Step 6: Create POST method for the resource and add the required parameters validator:

api_put_name_method=api_put_name_resource.add_method(http_method="POST",
                                                             integration=_apigateway.LambdaIntegration(lambda_function),
                                                             request_parameters={'method.request.querystring.firstname':True,
                                                                                'method.request.querystring.lastname':True,
                                                                                'method.request.querystring.email':True},
                                                            request_validator=_apigateway.RequestValidator(self,"PutNameRequestValidator",
                                                                                                           rest_api=api_gateway,
                                                                                                           validate_request_parameters=True)
                                                            )

On the Amazon API Gateway method, you will see the required URL query string parameters as below:

URL Query String Parameter Example

Validation

If the required parameters for the referenced sample application [“firstname”,“lastname”,“emailaddress”] are not present in the request to the API Gateway, API Gateway sends the following response to the client with a 400 Bad request:

Validation Failure

Conclusion

In this blog, we configured a sample application with AWS CDK which does request parameter validations on the Amazon API Gateway before passing the requests to the backend integration. Please check the links below to learn more.

References