API Gateway: Transformations, Validation and Custom Domains
Overview
Beyond simply proxying to Lambda, a REST API in API Gateway can reshape requests and responses, validate payloads, return mock responses and override HTTP status codes without any backend code. You do this with integration request/response mappings written in Velocity Template Language (VTL), models (JSON Schema) and gateway responses.
Think of API Gateway as an airport check-in desk: it can check your documents (validation), stamp them in another format (transformation), and turn you away with a standard form (gateway response) before you reach the plane (the backend).
You must also know how to expose the API under your own domain with a custom domain name, map it to stages, and use stage variables and canary release settings for safe deployments.
Key Concepts
- Proxy integration (Lambda proxy) passes the whole request and requires the function to return
statusCode,headersandbody; non-proxy integration lets API Gateway map data. - Mapping templates (VTL) transform request and response bodies, for example mapping a query string to a DynamoDB request.
- Models use JSON Schema; a request validator returns 400 before invoking the backend.
- Integration response mappings select a status code by regex on the backend result, so you can override status codes.
- Gateway responses customise errors generated by API Gateway itself (4XX, 5XX, throttling, authorizer failures).
- Mock integrations return a response without a backend and help front-end teams test early.
- Custom domain names need an ACM certificate (in the same Region for Regional endpoints, us-east-1 for edge-optimised) and base path mappings to stages.
- Stage variables and canary settings support environment config and gradual rollouts.
Detailed Notes
Proxy versus non-proxy integrations
| Aspect | Lambda proxy | Non-proxy (custom) |
|---|---|---|
| Request to backend | Entire request as an event | Shaped by your mapping template |
| Response handling | Function must return the proxy format | Mapped by integration response |
| Status code control | In the function | In API Gateway method/integration responses |
| Best for | Most Lambda APIs | Direct AWS service integrations, legacy shaping |
A direct service integration lets API Gateway call DynamoDB, SQS or Step Functions with no Lambda, using a mapping template and an IAM role for the integration.
Request mapping example
This template turns an HTTP POST into an SQS SendMessage call:
Action=SendMessage&MessageBody=$util.urlEncode($input.body)
and this template converts a path parameter into a DynamoDB GetItem request:
{
"TableName": "orders",
"Key": { "pk": { "S": "$input.params('orderId')" } }
}
A response template can then flatten the typed DynamoDB result:
#set($i = $input.path('$.Item'))
{ "orderId": "$i.pk.S", "total": $i.total.N }
Validation with models
OrderModel:
Type: AWS::ApiGateway::Model
Properties:
RestApiId: !Ref Api
ContentType: application/json
Schema:
type: object
required: [customerId, items]
properties:
customerId: { type: string }
items: { type: array, minItems: 1 }
Validator:
Type: AWS::ApiGateway::RequestValidator
Properties:
RestApiId: !Ref Api
ValidateRequestBody: true
ValidateRequestParameters: true
Attach the model to the method's request body and the validator to the method. Invalid calls are rejected with 400 and never reach the backend, saving cost and protecting the service.
Status codes and gateway responses
For non-proxy integrations, method responses declare which codes exist and integration responses pick one using a selection pattern, for example a Lambda error message matching .*NotFound.* maps to 404. Gateway responses change the body or headers of default errors, such as adding CORS headers to a DEFAULT_4XX response so browsers can read the error.
Custom domains
- Request or import a certificate in ACM.
- Create the custom domain name (Regional or edge-optimised) and attach the certificate.
- Add a base path mapping such as
/v1to APIorders-apistageprod. - Create a Route 53 alias record to the domain's target.
aws apigateway create-domain-name --domain-name api.example.com \
--regional-certificate-arn arn:aws:acm:eu-west-1:111122223333:certificate/abc \
--endpoint-configuration types=REGIONAL --security-policy TLS_1_2
aws apigateway create-base-path-mapping --domain-name api.example.com \
--rest-api-id a1b2c3 --stage prod --base-path v1
Optionally enable mutual TLS with a truststore in S3 for client certificate authentication.
Stages, stage variables and canaries
Each deployment publishes to a stage (dev, test, prod) with its own throttling, logging and caching. Stage variables parameterise integrations, for example my-fn:${stageVariables.alias} so prod calls the prod alias. A canary release on a stage sends a configurable percentage of traffic to a new deployment and can be promoted or rolled back.
aws apigateway create-deployment --rest-api-id a1b2c3 --stage-name prod \
--canary-settings percentTraffic=10
Documentation and testing
Export the API as OpenAPI 3 for contract tests and SDK generation. Use the console Test feature or aws apigateway test-invoke-method to try a method without deploying, and use mock integrations so consumers can build against agreed responses before the backend exists.
Real World Example
An order API let customers post arbitrary JSON, causing Lambda errors from malformed bodies. The team added a JSON Schema model and request validator, which turned bad payloads into immediate 400 responses and cut Lambda error alarms by 80 percent. They exposed the API at api.example.com/v1 through a custom domain, used stage variables to bind each stage to a Lambda alias, and shipped a risky change with a 10 percent canary that they rolled back after a latency alarm fired.
Architecture Diagram
Validation and mapping happen before and after the backend.
- 1The client calls the custom domain and the base path picks the stage.
- 2The request validator checks the body against the model.
- 3A mapping template shapes the call to the backend.
- 4The integration response maps the result to the final status and body.
Best Practices
- ✓Validate at the edge with models and request validators to reject bad requests cheaply.
- ✓Use proxy integration for simplicity and non-proxy only where mapping adds value.
- ✓Add CORS headers to gateway responses so error bodies are visible to browsers.
- ✓Use stage variables and aliases to separate environments without redeploying code.
- ✓Roll out risky changes with canary settings tied to CloudWatch alarms.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Override a status code or transform data without code means non-proxy integration with mapping templates.
- Invalid payload rejected before Lambda is invoked means a request validator.
- Edge-optimised custom domains need an ACM certificate in us-east-1.
- Per-stage Lambda alias selection is done with stage variables.
Finished this lesson?
0 of 46 lessons done · 0% of the course

