Validating and Transforming Requests and Responses
This lesson explains how API Gateway checks, reshapes and remaps requests and responses, so the backend receives clean input and clients receive consistent output.
Learning outcomes
After completing this lesson, you will be able to:
- Explain how request validators and JSON Schema models reject invalid requests before the backend is called.
- Distinguish parameter mapping from mapping templates.
- Describe how integration responses, gateway responses and mock integrations shape what clients receive.
Request validation
REST APIs support request validators. They check that required headers and query strings are present and validate the body against a JSON Schema model. Invalid requests are rejected with 400 Bad Request before the backend is called, so they never invoke, or incur charges in, the backend.
Example. With this model attached and body validation enabled, a request without id or with a quantity below 1 is rejected.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": ["id", "quantity"],
"properties": {
"id": {"type": "string"},
"quantity": {"type": "integer", "minimum": 1}
}
}Models also document the API and can generate client SDKs. Importing an OpenAPI file creates or updates a REST API, which suits an API-first way of working.
Parameter mapping and mapping templates
API Gateway can transform requests and responses between the client and the backend. The following list describes the two available mechanisms.
- Parameter mapping passes headers, path parameters and query strings to the backend without code, for example sending a path parameter on as a header.
- Mapping templates, written in Velocity Template Language (VTL), transform whole request and response bodies in non-proxy integrations.
Example. This template reshapes the client's JSON and adds the caller's IP address from the request context.
#set($body = $input.path('$'))
{
"orderId": "$body.id",
"customerName": "$body.customer.name",
"itemCount": $body.items.size(),
"sourceIp": "$context.identity.sourceIp"
}Validate and transform without code
Shaping responses
API Gateway can change what clients receive in three situations: when the backend answers, when API Gateway itself rejects a request, and when there is no backend at all.
Integration responses apply to non-proxy integrations. They map the backend's result to a method response, choosing the status code by matching the backend's status or error message against a pattern, and can transform the body with a mapping template. For example, a Lambda error whose message starts with "NotFound" can be returned as a 404 rather than a 200 containing an error. With proxy integrations this step does not exist, because the function sets the status code itself.
Gateway responses control errors generated by API Gateway before the backend is called, such as a missing authentication token, an authorizer denial, a throttled request or a failed request validation. A common use is adding CORS headers to the DEFAULT_4XX and DEFAULT_5XX responses, because without them a browser reports a CORS error instead of the real error. A mock integration returns a response defined entirely in API Gateway, which is useful for prototypes, for testing clients before the backend exists, and for answering CORS preflight OPTIONS requests.
The following table summarises the three features.
| Feature | Use it to |
|---|---|
| Integration responses | Map backend results to method responses, for example return 404 when the backend's error message matches a pattern |
| Gateway responses | Customise errors that API Gateway itself produces, such as adding CORS headers to 4xx and 5xx responses |
| Mock integration | Return a fixed response with no backend, useful for testing and prototypes |
Which feature does the job?
Rejecting bad requests before they cost money
A function receives thousands of malformed order requests a day from a buggy client, each invoking Lambda and logging an error. Moving validation into API Gateway stops them earlier:
| Without validation | With a request validator and JSON schema model |
|---|---|
| Every request invokes Lambda | Malformed requests receive 400 from API Gateway |
| Lambda cost and error logs for bad input | No Lambda invocation for bad input |
| Validation code duplicated in each function | One schema in the API definition |
For a legacy backend expecting XML, a mapping template on a non-proxy integration converts the client's JSON into the shape the backend needs, so neither side has to change.
Why does a request validator reduce cost when clients often send invalid JSON bodies?
Show answer
API Gateway rejects an invalid request with a 400 error before it reaches the integration, so no Lambda invocation or backend call is made for it.
Exam Tips
Remember for the exam
- To reject invalid bodies without invoking Lambda, add a request validator with a model.
- To change status codes or the payload shape without changing the backend, use integration responses and mapping templates.
- If CORS headers are missing from error responses, configure gateway responses.
- To define a REST API from an OpenAPI file, import the OpenAPI definition.