CodeWithYou

Validating Request Parameters and Body in Amazon API Gateway with AWS CDK

Published on
Authors
Validating Request Parameters and Body in Amazon API Gateway with AWS CDK
Photo by AI

Note: The code for this post is available on GitHub

Amazon API Gateway provides a powerful way to create REST APIs that can be integrated with other AWS services. However, it's important to validate incoming requests to ensure that they are in the correct format and contain the necessary parameters. This can help to prevent errors and security vulnerabilities.

What is Request Validation?

Request validation is the process of checking that a request contains all the necessary parameters and that they are in the correct format. This can help to prevent errors and security vulnerabilities. For example, if you have an API endpoint that accepts a JSON body with a username and password, you might want to validate that the username is a valid email address and that the password is at least 8 characters long.

How to Validate Request Parameters

Amazon API Gateway allows you to validate request path and query parameters using request validation rules. Request validation helps ensure that incoming requests to your API conform to the expected format, reducing the risk of errors and vulnerabilities.

To validate request path and query parameters in Amazon API Gateway using AWS CDK:

Advertisement
  1. Create a new REST API using the RestApi construct.
const restApi = new apigateway.RestApi(this, 'MyApi', {
  restApiName: 'My API',
  description: 'My sample API',
})
  1. Define a resource and method for your API using the addResource and addMethod methods. Specify a Lambda integration for the method using the LambdaIntegration class.
const getResource = restApi.root.addResource('resource')
const getMethod = getResource.addMethod('GET', new apigateway.LambdaIntegration(myLambdaFunction))
  1. Define the request parameters you want to validate using the requestParameters property. For example, to require a path parameter called id and a query parameter called name, set the requestParameters property like this:
getMethod.addMethod('GET', new apigateway.LambdaIntegration(myLambdaFunction), {
  requestParameters: {
    'method.request.path.id': true,
    'method.request.querystring.name': true,
  },
})
  1. Enable request validation for the method by setting the requestValidatorOptions.validateRequestParameters property to true.
getMethod.addMethod('GET', new apigateway.LambdaIntegration(myLambdaFunction), {
  requestParameters: {
    'method.request.path.id': true,
    'method.request.querystring.name': true,
  },
  requestValidatorOptions: {
    validateRequestParameters: true,
  },
})

If you call the API with a request that contains an invalid path parameter, API Gateway returns a 400 Bad Request response with an error message that describes the validation errors.

{
  "message": "Missing required request parameters: [name, id]"
}

That's it! With these steps, you can validate request path and query parameters in Amazon API Gateway using AWS CDK. By validating requests, you can ensure that your API only receives requests that conform to the expected format, reducing the risk of errors and vulnerabilities.

Validating Request Parameters and Body in Amazon API Gateway with AWS CDK

How to Validate Request Body

To validate the request body in Amazon API Gateway, you can use a JSON schema. A JSON schema is a JSON document that defines the structure of a JSON object. You can use JSON schemas to validate the structure of a JSON object, and to validate the values of the object's properties.

To validate the request body in Amazon API Gateway using AWS CDK:

  1. Create a new REST API using the RestApi construct.
const restApi = new apigateway.RestApi(this, 'MyApi', {
  restApiName: 'My API',
  description: 'My sample API',
})
  1. Define a resource and method for your API using the addResource and addMethod methods. Specify a Lambda integration for the method using the LambdaIntegration class.
const getResource = restApi.root.addResource('resource')
const postMethod = getResource.addMethod('POST', new apigateway.LambdaIntegration(myLambdaFunction))
  1. Define the request body schema using the requestModels property. For example, to require a JSON request body with a name field, set the requestModels property like this:
const requestBodySchema = new apigateway.Model(this, 'RequestBodySchema', {
  restApi: restApi,
  contentType: 'application/json',
  schema: {
    type: apigateway.JsonSchemaType.OBJECT,
    properties: {
      name: { type: apigateway.JsonSchemaType.STRING },
    },
    required: ['name'],
  },
})

postMethod.addMethod('POST', new apigateway.LambdaIntegration(myLambdaFunction), {
  requestModels: {
    'application/json': requestBodySchema,
  },
})
  1. Enable request validation for the method by setting the requestValidatorOptions.validateRequestBody and requestValidatorOptions.validateRequestParameters properties to true.
postMethod.addMethod('POST', new apigateway.LambdaIntegration(myLambdaFunction), {
  requestParameters: {
    'method.request.path.id': true,
    'method.request.querystring.name': true,
  },
  requestModels: {
    'application/json': requestBodySchema,
  },
  requestValidatorOptions: {
    validateRequestBody: true,
    validateRequestParameters: true,
  },
})

If you call the API with a request that contains an invalid request body, API Gateway returns a 400 Bad Request response with an error message that describes the validation errors.

{
  "message": "Invalid request body"
}

That's it! With these steps, you can validate request path and query parameters, as well as the request body, in Amazon API Gateway using AWS CDK. By validating requests, you can ensure that your API only receives requests that conform to the expected format, reducing the risk of errors and vulnerabilities.

Troubleshooting

How to Fix "There is already a Construct with name 'validator' in RestApi"

If you get the following error when trying to add a request validator to an API Gateway resource:

There is already a Construct with name 'validator' in RestApi

If you get this error, it means that you already have a request validator defined for the resource. You can only have one request validator per resource, so you need create specify a different name for the request validator.

To fix this error, specify a different name for the request validator. For example:

const bodyValidator = new apigateway.RequestValidator(this, 'BodyValidator', {
  restApi: restApi,
  requestValidatorName: 'BodyValidator',
  validateRequestBody: true,
  validateRequestParameters: false,
})
resource.addMethod('POST', new apigateway.LambdaIntegration(myLambdaFunction), {
  requestValidator: bodyValidator,
  requestModels: {
    'application/json': requestBodySchema,
  },
})

Conclusion

In conclusion, validating incoming requests is an important part of creating a secure and reliable API. Amazon API Gateway provides several options for validating request parameters and request body. By using AWS CDK to define your API infrastructure, you can automate the process of creating and managing your API, including the request validation process.

In this blog post, we explored how to define request parameters and request body schema in Amazon API Gateway using AWS CDK. We also demonstrated how to enable request validation for a method using the requestValidatorOptions property. By following these steps, you can create a more secure and reliable API that is less prone to errors and vulnerabilities.

Overall, using AWS CDK to define your API infrastructure provides a powerful and flexible way to manage your API. By incorporating request validation into your API design, you can ensure that your API only receives valid requests, which can improve the reliability and security of your application.

References

Thanks for reading! If you have any questions or comments, please send me a note on Twitter. I'd love to hear from you!

Advertisement