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:

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:

  "$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:

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.