Request Validators with API Gateway REST API

Validating your request body in API gateway

Posted on September 15, 2020

API gateway allows us to add basic validation to our requests, allowing us to validate the request body, query string parameters and headers before the request gets to, and invokes, the Lambda function.

This has the benefits of:

  • If validation fails, API Gateway will immediately fail the request, return a 400 error response, and publishes the validation results in CloudWatch Logs.
  • Adding an additional layer of validation between your front end and the API.
  • Better error responses e.g. “Invalid Request Body” rather than “Internal Server Error”.
  • Reduces unnecessary calls to the backend.
  • Allows developers to focus on app-specific deep validation in the backend.
  • Improving performance – Albeit very small.
  • Cost reduction by reducing the number of times your Lambda function is invoked – again, tiny, but it’s still there.

For this article I’m just going to focus on validating the request body for a POST event. I’ll be assuming that you already have a Lambda function created and API Gateway setup with a POST method.

Creating a Model

The model defines what the request body should look like.

To create a model:

  • Navigate to your API Gateway in the AWS console.
  • Select ‘Models’ in the left navigation and then ‘Create’.
  • Give the model name, in this case, Test.
  • Add a content type of application/json.
  • Copy and paste the following schema into the Model schema* box.
{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "Test Schema",
  "type" : "object",
  "properties" : {
    "title" : { "type" : "string" },
    "content" : { "type" : "string" }
  },
  "required": ["title", "content"]
}

The schema should be fairly self explanatory, but we’re basically defining the shape of the data that will be sent in the POST request.

In this case, the POST body data should be an object with two properties of title and content, with both of these values being required and being a string.

Enable the Validation and Deploy

Next we need to add this to our APIs POST method and enable the validation:

  • Navigate back to your API gateway and click on the POST method.
  • Select Method Response and change the Request Validator setting to ‘Validate Body‘.
  • Open the Request Body area and add a model of Content Type = application/json and Model Name = Test.
  • Now deploy your API using Actions > Deploy API.

Now if you make a POST request to this endpoint and the body doesn’t match our model schema then API gateway will respond with an error of “Invalid request body” instead of invoking the lambda function and then returning an error of “Internal Server Error”.

In a lot of cases, using API Gateway’s request validation will be enough serverside validation for your application, which means less code for you to write and a more robust codebase.