Back to Blog
Lesson 20 of the AWS: AWS Core Services for Developers course
Cloud NativeJuly 27, 20264 min read

Request Validation in API Gateway: A Practical Guide

Learn how to implement Request Validation in API Gateway using JSON Schema. Stop malformed requests early and protect your backend from invalid data.

AWSAPI GatewayServerlessJSON SchemaCloud Native
Wooden blocks aligned to spell 'CHECK' with a checkmark symbol on a neutral background.

Previously in this course, we explored API Gateway Routing and Integration, where we mapped URL paths to our serverless backend. Now that our routes are live, we need to address a critical security and operational concern: the data our clients send us.

If you don't validate incoming requests, your Lambda function becomes responsible for checking every field, type, and required property. This leads to "defensive coding" bloat and wastes compute time on requests that were doomed from the start.

Why Use Request Validation?

Request validation is your first line of defense. By enforcing a contract at the API Gateway level, you ensure that only well-formed data reaches your business logic. This provides three immediate benefits:

  1. Reduced Cost: You don't pay for Lambda execution time if the request is invalid.
  2. Simplified Code: Your handler can assume the payload is correct, reducing the need for heavy if/else checks.
  3. Security: You prevent injection attacks or malformed payloads from reaching your database, which is vital for preventing mass assignment vulnerabilities.

Defining a JSON Schema

Programming code on a computer screen in a dark room, showcasing technology and IT expertise.

To validate requests, we use JSON Schema, a declarative language that describes the structure of your JSON data. Think of it as a contract for your API.

Suppose our application expects a POST request to create a user with a username (string) and an age (number). Our schema looks like this:

JSON
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "UserCreationSchema",
  "type": "object",
  "properties": {
    "username": { "type": "string" },
    "age": { "type": "integer", "minimum": 18 }
  },
  "required": ["username", "age"]
}

This schema tells API Gateway: "If the incoming body isn't an object, doesn't have these exact keys, or if age is less than 18, reject the request immediately with a 400 Bad Request."

Enabling Validation in API Gateway

In the AWS Console, follow these steps to attach this validation to your existing resource:

  1. Navigate to your API in the API Gateway console.
  2. Select Models from the left-hand menu and click Create.
  3. Name it UserRequestModel, set the Content-Type to application/json, and paste your JSON schema above.
  4. Go to your Resources tab and select the POST method.
  5. Click Method Request.
  6. Under Request Validator, select "Validate body".
  7. Under Request Models, add application/json and select the UserRequestModel you just created.
  8. Deploy your API (Actions -> Deploy API) for these changes to take effect.

Testing with Invalid Payloads

Once deployed, use curl or a tool like Postman to test the enforcement.

Test 1: Missing Required Field

Bash
curl -X POST https://your-api-id.execute-api.region.amazonaws.com/prod/users \
     -H "Content-Type: application/json" \
     -d '{"username": "dev_user"}'

Expected Result: 400 Bad Request with a message indicating the missing age field.

Test 2: Out of Bounds Value

Bash
curl -X POST https://your-api-id.execute-api.region.amazonaws.com/prod/users \
     -H "Content-Type: application/json" \
     -d '{"username": "young_user", "age": 10}'

Expected Result: 400 Bad Request because the age is below the minimum of 18 defined in your schema.

Common Pitfalls

Close-up of a rusty sewer manhole cover in a grassy Boston park.

  • Forgetting to Deploy: After updating Method Request settings, you must redeploy your API to the stage (e.g., prod). Changes won't show up otherwise.
  • Case Sensitivity: JSON schema keys are case-sensitive. If your client sends UserName but your schema expects username, validation will fail.
  • Content-Type Mismatch: API Gateway only validates the body if the Content-Type header matches what you defined in the model. If a client sends text/plain, the validator is often bypassed.

Frequently Asked Questions

Does this replace backend validation? No. While it catches structural issues, always perform business-logic validation (e.g., "does this username already exist in DynamoDB?") inside your Lambda function.

Can I validate headers or query parameters? Yes. In the "Method Request" settings, you can toggle validation for "Query String Parameters" and "Headers" in addition to the request body.

Recap

Wooden Scrabble tiles spelling 'RECAP' on a brown textured background. Text concept image.

By using Request Validation in API Gateway, you delegate the burden of input checking to the AWS infrastructure. Using a JSON Schema, you guarantee that your Lambda functions only process clean, valid data, improving the reliability and security of your serverless architecture.

Up next: Configuring CORS for Web Apps to allow your browser-based frontend to communicate with your validated API.

Similar Posts