All jobs

Add Request Validation to an API Gateway in AWS CDK

Yes. An agent adds API Gateway request validators, JSON schema models and CORS-aware 400 responses to your CDK REST API, tests the template and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent clones the repository into its own cloud sandbox and reads the stack and the handlers behind it before it adds a validator. In a stack like typescript/api-cors-lambda-crud-dynamodb in aws-samples/aws-cdk-examples, index.ts builds a RestApi named Items Service with an items resource for GET and POST, an {id} child for GET, PATCH and DELETE, and an addCorsOptions helper that answers OPTIONS from a MockIntegration. Five NodejsFunctions on NODEJS_24_X share a DynamoDB table whose partition key is itemId. lambdas/create.ts answers 400 only when event.body is missing and otherwise stores whatever JSON arrived, and lambdas/update-one.ts turns every key in the body into an UpdateExpression, which is why it carries a 500 message about reserved keywords: an attribute named name or status reaches DynamoDB as a reserved word. package.json is on aws-cdk-lib 2.262.1 with Jest 30 through @swc/jest, jest.config.js matches **/*.test.ts and loads aws-cdk-lib/testhelpers/jest-autoclean, but no test exists, and cdk.json already sets the @aws-cdk/aws-apigateway:requestValidatorUniqueId flag.

It defines two models on the API with api.addModel: an item model whose schema is DRAFT4 with the properties the prompt names, required for the ones a new item must have and additionalProperties: false, and a patch model with the same properties, none required, minProperties: 1 and the same closed shape, which is what removes the reserved-keyword path from update-one.ts, since only known attribute names can now reach the expression. One RequestValidator with validateRequestBody and validateRequestParameters both on is attached to each method through its MethodOptions: POST /items and PATCH /items/{id} get requestModels for application/json, and the three {id} methods get requestParameters marking method.request.path.id required.

A validation failure answers from the gateway before any function runs, and the default body is a bare message with no CORS headers, which a browser reports as a network error instead of a 400. The agent adds two GatewayResponses, BAD_REQUEST_BODY and BAD_REQUEST_PARAMETERS, with Access-Control-Allow-Origin set the same way the existing OPTIONS mock sets it and a JSON template that carries $context.error.validationErrorString, so a client sees which property failed. The handlers' own checks stay, because the gateway validates the shape and the functions still own what a valid item means.

It writes test/api.test.ts with Template.fromStack from aws-cdk-lib/assertions: one AWS::ApiGateway::RequestValidator with both flags true, two AWS::ApiGateway::Model resources with the schemas, RequestModels on the POST and PATCH methods, RequestParameters on the {id} methods, and the two gateway responses with their headers. In the sandbox it runs npm install, whose postinstall installs the lambdas/ dependencies, npm run build for the type check, npx cdk synth to render the template without an AWS account, and npx jest.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add request validation to the API Gateway in this CDK app. Read index.ts, every file under lambdas/, jest.config.js and cdk.json first. Define a JSON schema model for an item with name as a required string, description as an optional string and price as an optional number, with no additional properties, and a patch model with the same properties where at least one must be present. Add one request validator that checks bodies and parameters, attach the models to the create and update methods and mark the id path parameter required on the single-item methods. Add gateway responses for bad request body and parameters that carry the CORS origin header and the validation error string. Write a Jest test with aws-cdk-lib assertions covering the validator, models, method options and gateway responses, run the build, cdk synth and the tests, and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

What comes back is a pull request on its own branch that changes index.ts and adds test/api.test.ts. The description shows the two schemas, lists which method got which model or parameter rule, explains why the gateway responses carry the CORS header, and pastes the tsc, cdk synth and Jest output from the sandbox, including the resource counts from the synthesised template.

The run's record keeps the synthesised cdk.out template alongside the commands, so a reviewer can read the exact AWS::ApiGateway::Model schema CloudFormation will create rather than reconstruct it from the TypeScript.

Before merging, a reviewer checks the item schema against what real clients send, since a closed schema rejects any extra property, decides whether price should have a minimum, and deploys to a non-production stage, because the sandbox proves the template and the tests but cannot call a deployed endpoint.

Run it on every Linear issue labelled api-hardening

In the console, an automation in the Project that has the repository, with a linear trigger on linear.issue.labeled and labels set to api-hardening, starts one run per issue with the issue as its context after the prompt; the saved prompt is the whole instruction, and the trigger fills in no placeholder. A later issue that adds a field to the item, tightens a type, or asks for a query-string parameter to be required is one run that changes the model, the method options and the test together.

From your own tracker, a handler sends one POST /o/{org}/sessions with this body, the repository in resources and a request_id that is a UUID v5 of the issue id, so a repeated delivery returns the run already started. With a webhook_url on the key, Rush posts run.completed with the session_url when the pull request is up.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

Request validation in CDK is spread across models, validators, method options and gateway responses, and the usual mistakes are a validator that is created but attached to nothing, a schema that validates on synth and rejects every real client, or a 400 that browsers cannot read because the CORS header is missing from the gateway response. The agent reads the handlers to see what they currently accept, closes the schema deliberately, and proves the template with assertions in its own sandbox before the pull request exists.

The sandbox installs both package trees, synthesises the template and keeps every command's output in the run's record, so the reviewer reads the real schema and the real test result. Several APIs can be hardened at once in separate sandboxes, each ending in its own pull request.

Frequently asked questions

Will existing clients break?

Any client that sends a property outside the schema gets a 400 from the gateway after this change, which is the point, and the pull request lists the accepted properties so you can compare them with real traffic first. The handlers themselves are unchanged, so a valid request behaves exactly as before.

Why add gateway responses for CORS?

The existing OPTIONS mock only answers preflight. When the validator rejects a body, API Gateway answers on its own without the function, and that default response has no Access-Control-Allow-Origin, so a browser sees a failed request with no status. The added GatewayResponses put the header and a readable error on those answers.

How is it tested without deploying?

Template.fromStack renders the stack to CloudFormation in Jest, and the test asserts on the RequestValidator, Model, Method and GatewayResponse resources and their properties. The repository already has jest.config.js with @swc/jest and the CDK autoclean helper; the agent adds the first test file.

Does the reserved keyword problem in update-one go away?

For the API, yes: the patch model only admits the known property names, so an attribute like status never reaches the UpdateExpression. The handler keeps its 500 branch as a defence, and the pull request notes that a direct invocation of the function bypasses the gateway's check.

More AWS CDK jobs

The same job on other stacks

Keep reading