All jobs

Add API Gateway Access Logs to an AWS CDK REST API

Yes. An agent adds structured access logging to your CDK REST API, with a log group, retention and the account role API Gateway needs, plus an assertion test.

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 before it adds logging. In a project like the api-cors-lambda-crud-dynamodb example in aws-samples/aws-cdk-examples, index.ts defines ApiLambdaCrudDynamoDBStack: a DynamoDB Table named items with partition key itemId and RemovalPolicy.DESTROY, five NodejsFunctions (getOneItemFunction, getAllItemsFunction, createItemFunction, updateItemFunction, deleteItemFunction) on Runtime.NODEJS_24_X with @aws-sdk/* as external modules and PRIMARY_KEY and TABLE_NAME in the environment, and a RestApi called itemsApi with restApiName: 'Items Service' and no deployOptions. The /items resource takes GET and POST, /items/{id} takes GET, PATCH and DELETE, and addCorsOptions adds a MockIntegration OPTIONS method to each.

Two files decide how logging has to be added. cdk.json sets the context flag @aws-cdk/aws-apigateway:disableCloudWatchRole to true, so the RestApi construct no longer creates the account-level IAM role API Gateway uses to write to CloudWatch Logs, and without that role the stage cannot deliver access logs. package.json pins aws-cdk-lib 2.262.1 and aws-cdk 2.1133.0, builds with tsc, and has jest 30 with @swc/jest and a jest.config.js whose setupFilesAfterEnv loads aws-cdk-lib/testhelpers/jest-autoclean, but there is no test file yet. The repository's SNAPSHOT_TESTING.md and typescript/test-utils/normalize-template.ts show how its examples are expected to test templates.

The agent adds a LogGroup from aws-cdk-lib/aws-logs named after the API with retention: RetentionDays.ONE_MONTH and removalPolicy: RemovalPolicy.DESTROY to match the table, and gives the RestApi deployOptions with accessLogDestination: new LogGroupLogDestination(logGroup) and accessLogFormat: AccessLogFormat.jsonWithStandardFields({caller: false, httpMethod: true, ip: true, protocol: true, requestTime: true, resourcePath: true, responseLength: true, status: true, user: false}), one JSON object per request. Because of the context flag, it also sets cloudWatchRole: true on this RestApi, which creates the AWS::ApiGateway::Account resource and its role for this API only, and it explains in a comment why the prop is there. It changes nothing about the methods, the CORS options or the functions.

It writes index.test.ts with Template.fromStack: the template has one AWS::Logs::LogGroup with RetentionInDays: 30, the AWS::ApiGateway::Stage has an AccessLogSetting whose DestinationArn references that group and whose Format contains requestId, and an AWS::ApiGateway::Account exists with a CloudWatchRoleArn. Then it runs npm install (which also installs the lambdas dependencies through postinstall), npm run build, npx jest and npx cdk synth, which needs no AWS credentials for this environment-agnostic stack, and diffs the synthesized template against main to show the pull request adds exactly the log group, the account, the role and the stage setting.

Start it with one API call

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

{
  "agent": "claude",
  "input": "Add access logging to the API Gateway REST API in this CDK app. Read the stack, cdk.json and package.json first. Create a CloudWatch log group with a retention period, enable access logs on the API's stage with the standard JSON fields, and make sure the account-level CloudWatch role API Gateway requires exists, taking the project's cdk.json feature flags into account. Do not change any method, integration or Lambda function. Add an assertion test with the aws-cdk-lib assertions module that checks the log group, the stage's access log setting and the account role. Run the build, the tests and cdk synth, and open a pull request that shows the template diff.",
  "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 (the log group, deployOptions, cloudWatchRole), adds index.test.ts, and updates README.md with a line on where the logs land. The description shows the cdk synth diff, the added log group, account and role and the changed stage, quotes the jest output from the sandbox, and explains the disableCloudWatchRole flag and why the stack now sets the role per API.

The run's record keeps every command with its output, including npm install, the TypeScript build, the test run and the synth, so a reviewer can see the template compiles with the pinned aws-cdk-lib version rather than trusting the description.

Before merging, a reviewer decides the retention period that matches their log policy, checks whether the account role already exists in the target account from another stack (two stacks setting AWS::ApiGateway::Account in one account and region overwrite each other's role, which is harmless when both roles have the same managed policy), and confirms the field list against what their log queries need.

Run it on every Linear issue labelled agent

In the console, an automation in the Project that has the repository, with a linear trigger on linear.issue.labeled and config.labels set to agent, starts one run per issue, with the issue text added after the prompt. An observability ticket that names the APIs, the retention or extra fields such as integrationLatency reaches the agent as part of that text, and the pull request links the issue.

From your own server, the same work is one POST /o/{org}/sessions with this body and the repository in resources; a webhook on the API key reports run.completed with the session_url to read the pull request link.

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

Why run it on Rush?

Access logging on API Gateway has one trap that only shows up after deployment: the stage setting is accepted but no log line ever arrives, because the account has no CloudWatch role. The agent reads cdk.json and finds the feature flag that disables the role before it writes a line, so the pull request includes the fix for the problem a reader would otherwise find in production.

The sandbox has Node and the pinned CDK toolkit, so the build, the assertion test and cdk synth run for real and the template diff in the pull request is the one the sandbox produced. Several APIs or several stacks can be done at once, each in its own sandbox.

Frequently asked questions

Why does the stack also create an API Gateway account resource?

API Gateway writes access logs through one account-level IAM role per region. This project disables the CDK default that creates it, so the agent sets cloudWatchRole: true on this API, which adds the AWS::ApiGateway::Account and its role. Without it the stage setting deploys but no log is written.

What fields are logged?

The jsonWithStandardFields set: request id, source IP, HTTP method, protocol, request time, resource path, status and response length, as one JSON object per request. The agent leaves out caller and user, which are empty without IAM authorization, and you can add fields such as integrationLatency in the prompt.

Does it need AWS credentials?

No. The stack is environment-agnostic, so cdk synth and the assertion tests run with no account configured. Deploying is yours to do; the pull request shows the template diff so you know what the deploy will create.

Will it change my API's methods or Lambdas?

No. The change is confined to the RestApi props and a new log group. The assertion test and the synth diff show the method, integration and function resources are byte-for-byte the same as before.

More AWS CDK jobs

More jobs like this: Turn a Linear label into a PR

Keep reading