Skip to main content

Cloud and deployment · Intermediate · 24 min

Put an HTTP API in front of a Lambda function with API Gateway

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4 · Lambda runtime nodejs26.x

You will have a small notes API on API Gateway, with GET and POST routes calling one Lambda function, CORS for a single origin, per-route throttling, JSON access logs and a JWT authorizer guarding writes.

On this page

A Lambda function on its own has no web address. To call it from a browser or a phone app you need something in front that speaks HTTP, checks who is calling and turns each request into an event. On AWS that is API Gateway.

API Gateway has two products for this. REST APIs are the older, larger one: API keys and usage plans, per-client rate limits, response caching, request validation, AWS WAF and private endpoints. HTTP APIs do less and cost less: Lambda and HTTP back ends, JWT authorizers, CORS, access logs, throttling per route, and a stage that deploys itself whenever you change a route. Pick a REST API when you need one of the features only it has, such as handing API keys to paying customers (see /tutorials/protect-an-api-with-api-keys for that pattern in your own code). For an app's own back end, an HTTP API is usually enough, and that is what you build here.

You will put a small notes service on the internet: GET /notes lists notes and POST /notes adds one. One Lambda function handles both routes. Around it you add a $default stage with automatic deployment, a throttle on writes, JSON access logs in CloudWatch Logs, CORS for one front-end origin, and finally a JWT authorizer so only signed-in users can post.

Cost. The API Gateway pricing page (checked 26 November 2026) lists one million HTTP API calls a month free for the first 12 months for customers on the older free tier; accounts created from 15 July 2025 get Free Tier credits instead. The few requests here are a rounding error either way. CloudWatch Logs storage is billed separately, so both log groups get a short retention period, and the last step deletes everything.

Run every command in one terminal: later steps reuse shell variables such as API_ID from earlier ones. Files live in ~/notes-api-demo and AWS names start with notes-api-demo.

Step 1 · Deploy the notes function

The function reads one field to decide what to do: routeKey. With payload format 2.0, which you choose in the next step, API Gateway sends every request as an event like this (trimmed):

JSON
{
  "version": "2.0",
  "routeKey": "POST /notes",
  "rawPath": "/notes",
  "rawQueryString": "",
  "headers": { "content-type": "application/json", "origin": "https://notes.example.com" },
  "requestContext": {
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "http": { "method": "POST", "path": "/notes", "sourceIp": "192.0.2.1" },
    "authorizer": { "jwt": { "claims": { "sub": "..." }, "scopes": ["notes/write"] } }
  },
  "body": "{\"text\":\"Buy airtime\"}",
  "isBase64Encoded": false
}

routeKey is the route that matched, exactly as you will name it in API Gateway. Header names are always lower case. body is a string, so the function parses it, and it arrives base64-encoded when isBase64Encoded is true. authorizer appears only on routes with an authorizer.

Make the working folder and write the handler:

Bash
mkdir -p ~/notes-api-demo
cd ~/notes-api-demo
cat > index.mjs <<'JS'
const notes = [];

const reply = (statusCode, data) => ({
  statusCode,
  headers: { 'content-type': 'application/json; charset=utf-8' },
  body: JSON.stringify(data),
});

const readJson = (event) => {
  const raw = event.isBase64Encoded
    ? Buffer.from(event.body ?? '', 'base64').toString('utf8')
    : event.body ?? '';
  return JSON.parse(raw);
};

export const handler = async (event) => {
  console.log(JSON.stringify({ route: event.routeKey, requestId: event.requestContext?.requestId }));

  if (event.routeKey === 'GET /notes') {
    return reply(200, { notes });
  }

  if (event.routeKey === 'POST /notes') {
    let input;
    try {
      input = readJson(event);
    } catch {
      return reply(400, { error: 'The body must be JSON, for example {"text":"Buy airtime"}' });
    }
    const text = typeof input?.text === 'string' ? input.text.trim() : '';
    const length = [...text].length;
    if (length === 0 || length > 280) {
      return reply(400, { error: 'text must be 1 to 280 characters' });
    }
    const note = {
      id: crypto.randomUUID(),
      text,
      author: event.requestContext?.authorizer?.jwt?.claims?.sub ?? null,
      createdAt: new Date().toISOString(),
    };
    notes.push(note);
    return reply(201, note);
  }

  return reply(404, { error: `No handler for ${event.routeKey}` });
};
JS
  • Returning statusCode, headers and body gives you full control of the response. With format 2.0 you may also return a plain object; API Gateway then sends it as JSON with status 200, which is handy but hides mistakes such as a missing 201.
  • [...text].length counts characters, not UTF-16 units, so a note in Yoruba, Amharic or with emoji gets the same 280-character limit as one in English. The charset=utf-8 header keeps older Android browsers from guessing the encoding.
  • notes lives in memory. Each copy of the function that Lambda starts has its own empty list, and Lambda can start a new copy at any time, so notes vanish. That is fine for learning the API side; a real service stores them in a database such as DynamoDB.

Now the function's log group, execution role and the function itself. The role may write only to this function's log group, which you create first with 14-day retention:

Bash
cd ~/notes-api-demo
aws logs create-log-group --log-group-name /aws/lambda/notes-api-demo
aws logs put-retention-policy --log-group-name /aws/lambda/notes-api-demo --retention-in-days 14
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
cat > trust.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }
  ]
}
JSON
ROLE_ARN=$(aws iam create-role --role-name notes-api-demo-role \
  --assume-role-policy-document file://trust.json \
  --query Role.Arn --output text)
cat > logs-only.json <<JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "arn:aws:logs:*:${ACCOUNT_ID}:log-group:/aws/lambda/notes-api-demo:*"
    }
  ]
}
JSON
aws iam put-role-policy --role-name notes-api-demo-role \
  --policy-name logs-only --policy-document file://logs-only.json

Package and deploy. IAM takes a few seconds to make a new role usable everywhere; if create-function fails with The role defined for the function cannot be assumed by Lambda, wait ten seconds and run it again:

Bash
cd ~/notes-api-demo
zip -q function.zip index.mjs
FUNCTION_ARN=$(aws lambda create-function --function-name notes-api-demo \
  --runtime nodejs26.x --handler index.handler \
  --role "$ROLE_ARN" --zip-file fileb://function.zip \
  --memory-size 256 --timeout 10 \
  --query FunctionArn --output text)
REGION=$(echo "$FUNCTION_ARN" | cut -d: -f4)
echo "$FUNCTION_ARN"
echo "$REGION"

REGION is cut from the function's ARN, so it is always the Region your CLI used, whatever your profile says.

Check it worked

The first echo prints an ARN such as arn:aws:lambda:eu-west-2:123456789012:function:notes-api-demo and the second your Region. This shows the runtime, handler and memory:

Bash
aws lambda get-function-configuration --function-name notes-api-demo \
  --query '[Runtime,Handler,MemorySize]' --output text

It prints nodejs26.x, index.handler and 256.

Step 2 · Create the HTTP API and its Lambda integration

An HTTP API is built from three parts: integrations (where requests go), routes (which requests go there) and stages (a deployed, callable copy of the API). Create the API, then an integration that points at the function:

Bash
API_ID=$(aws apigatewayv2 create-api --name notes-api-demo --protocol-type HTTP \
  --query ApiId --output text)
API_URL=$(aws apigatewayv2 get-api --api-id "$API_ID" --query ApiEndpoint --output text)
INTEGRATION_ID=$(aws apigatewayv2 create-integration --api-id "$API_ID" \
  --integration-type AWS_PROXY \
  --integration-uri "$FUNCTION_ARN" \
  --payload-format-version 2.0 \
  --query IntegrationId --output text)
echo "$API_URL"
  • --protocol-type HTTP makes an HTTP API; the same apigatewayv2 commands also build WebSocket APIs.
  • AWS_PROXY is a Lambda proxy integration: API Gateway passes the whole request to the function and sends back whatever it returns, with no mapping templates in between.
  • --payload-format-version 2.0 is required from the CLI. Version 1.0 is the older REST-API-shaped event with httpMethod and multiValueHeaders; choose 2.0 for new functions unless you share one handler with a REST API.

create-api also accepts --target with a function ARN, a quick-create shortcut that adds a catch-all route and stage for you. Building the parts one by one shows you what that shortcut hides, and gives you named routes you can throttle and protect separately.

Check it worked

echo prints an address such as https://a1b2c3d4e5.execute-api.eu-west-2.amazonaws.com. Nothing answers there yet: there are no routes and no stage. Confirm the integration:

Bash
aws apigatewayv2 get-integration --api-id "$API_ID" --integration-id "$INTEGRATION_ID" \
  --query '[IntegrationType,PayloadFormatVersion]' --output text

It prints AWS_PROXY and 2.0.

Step 3 · Add the GET and POST routes

A route key is a method and a path. Both routes target the same integration:

Bash
GET_ROUTE_ID=$(aws apigatewayv2 create-route --api-id "$API_ID" \
  --route-key 'GET /notes' --target "integrations/$INTEGRATION_ID" \
  --query RouteId --output text)
POST_ROUTE_ID=$(aws apigatewayv2 create-route --api-id "$API_ID" \
  --route-key 'POST /notes' --target "integrations/$INTEGRATION_ID" \
  --query RouteId --output text)

Requests that match neither route, such as DELETE /notes or GET /, get a 404 from API Gateway and never reach the function. That is one reason to name routes rather than send everything to a catch-all $default route: you pay for and log fewer junk requests.

API Gateway also needs permission to invoke the function. Lambda keeps that in the function's own resource-based policy. Limit it to this API's /notes path, in any stage and with any method:

Bash
aws lambda add-permission --function-name notes-api-demo \
  --statement-id notes-api-demo-invoke \
  --action lambda:InvokeFunction \
  --principal apigateway.amazonaws.com \
  --source-arn "arn:aws:execute-api:${REGION}:${ACCOUNT_ID}:${API_ID}/*/*/notes" \
  --query Statement --output text

The source ARN reads api-id/stage/method/path. Without --source-arn, any API Gateway API in any account could call your function if it knew the ARN. Without the permission at all, every request fails with a 500 and the access log in a later step shows an integration error.

Check it worked

Bash
aws apigatewayv2 get-routes --api-id "$API_ID" --query 'Items[].RouteKey' --output text

It prints GET /notes and POST /notes. aws lambda get-policy --function-name notes-api-demo prints a policy whose SourceArn condition ends in /*/*/notes.

Step 4 · Create the $default stage with access logs and throttling

A stage named $default is served at the root of the invoke URL, with no /prod or /v1 in front of the path. With auto-deploy on, every change to a route or integration goes live without a separate deployment step. That suits a small API; for a team API with a review step, use named stages and deploy on purpose.

Give the stage two more jobs while you create it:

  • Access logs: one JSON line per request in a log group of its own, so you can see status codes, latency and integration errors without opening the function's logs.
  • Throttling: a default limit for every route and a tighter one for POST /notes. Without your own limits, the routes share the account's limit for the Region, by default 10,000 requests a second with a burst of 5,000 across every API you have there, or 2,500 with a burst of 1,250 in some Regions such as Africa (Cape Town). One noisy client could use it all up.

Create the access log group first:

Bash
aws logs create-log-group --log-group-name /aws/apigateway/notes-api-demo
aws logs put-retention-policy --log-group-name /aws/apigateway/notes-api-demo --retention-in-days 14

Then write the whole stage as one input file. The heredoc is unquoted so the shell fills in your API ID, Region and account; every $ that API Gateway itself must see, such as $default and the $context variables, is written \$ so the shell leaves it alone:

Bash
cd ~/notes-api-demo
cat > stage.json <<JSON
{
  "ApiId": "${API_ID}",
  "StageName": "\$default",
  "AutoDeploy": true,
  "AccessLogSettings": {
    "DestinationArn": "arn:aws:logs:${REGION}:${ACCOUNT_ID}:log-group:/aws/apigateway/notes-api-demo",
    "Format": "{\"requestId\":\"\$context.requestId\",\"ip\":\"\$context.identity.sourceIp\",\"time\":\"\$context.requestTime\",\"route\":\"\$context.routeKey\",\"status\":\"\$context.status\",\"latencyMs\":\"\$context.responseLatency\",\"integrationError\":\"\$context.integrationErrorMessage\",\"authError\":\"\$context.authorizer.error\"}"
  },
  "DefaultRouteSettings": {
    "ThrottlingBurstLimit": 50,
    "ThrottlingRateLimit": 20
  },
  "RouteSettings": {
    "POST /notes": {
      "ThrottlingBurstLimit": 5,
      "ThrottlingRateLimit": 2
    }
  }
}
JSON
aws apigatewayv2 create-stage --cli-input-json file://stage.json \
  --query '[StageName,AutoDeploy]' --output text

How the limits work: API Gateway keeps a bucket of tokens for each route. ThrottlingRateLimit is how many tokens it adds each second and ThrottlingBurstLimit is the bucket's size. Here POST /notes takes a quick burst of 5 posts, then about 2 a second; GET /notes takes 50, then about 20 a second. Requests over the limit get 429 Too Many Requests and never reach the function. AWS treats these numbers as targets, not hard ceilings, so do not rely on them for billing or security.

To change limits or the log format later, use aws apigatewayv2 update-stage --api-id "$API_ID" --stage-name '$default' with --route-settings, --default-route-settings or --access-log-settings.

Check it worked

create-stage prints $default and True. Read the settings back:

Bash
aws apigatewayv2 get-stage --api-id "$API_ID" --stage-name '$default' \
  --query '[RouteSettings."POST /notes".ThrottlingRateLimit, DefaultRouteSettings.ThrottlingRateLimit, AccessLogSettings.DestinationArn]' \
  --output text

It prints 2.0, 20.0 and the ARN of /aws/apigateway/notes-api-demo. If the log format shows empty values where $context should be, a \$ was lost: rewrite stage.json and update the stage.

Step 5 · Allow one browser origin with CORS

A web page on https://notes.example.com that calls your API with fetch is cross-origin, so the browser first asks the API whether that origin is allowed. API Gateway can answer for you: set a CORS configuration on the API and it replies to every preflight OPTIONS request itself and adds the CORS headers to your function's responses. You need no OPTIONS route, and any CORS headers the function sets are ignored.

Set the origin of your front end (replace this with yours, scheme included and no trailing slash), then write the configuration:

Bash
cd ~/notes-api-demo
FRONTEND_ORIGIN=https://notes.example.com
cat > cors.json <<JSON
{
  "AllowOrigins": ["${FRONTEND_ORIGIN}"],
  "AllowMethods": ["GET", "POST"],
  "AllowHeaders": ["authorization", "content-type"],
  "MaxAge": 600
}
JSON
aws apigatewayv2 update-api --api-id "$API_ID" --cors-configuration file://cors.json \
  --query 'CorsConfiguration.AllowOrigins' --output text
  • List exact origins. * lets any site call the API from its visitors' browsers, and it cannot be combined with AllowCredentials.
  • authorization is allowed because the JWT step sends a bearer token in that header.
  • MaxAge lets browsers reuse a preflight answer for 10 minutes. On a slow mobile connection, every skipped preflight is one fewer round trip before the real request.

CORS is a browser rule, not access control. curl, scripts and other servers ignore it, so it does nothing to stop someone posting notes. The JWT step does that.

Check it worked

update-api prints https://notes.example.com (or your origin). aws apigatewayv2 get-api --api-id "$API_ID" --query CorsConfiguration shows both methods, both headers and a MaxAge of 600.

Step 6 · Call the API with curl

The API is live. List the notes, add one, then send a bad body:

Bash
curl -s "$API_URL/notes"
curl -s -i -X POST "$API_URL/notes" \
  -H 'content-type: application/json' \
  -d '{"text":"Buy airtime before Friday"}'
curl -s -i -X POST "$API_URL/notes" -H 'content-type: application/json' -d 'hello'
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE "$API_URL/notes"

Then ask the API what a browser on your front end would ask:

Bash
curl -s -i -X OPTIONS "$API_URL/notes" \
  -H "Origin: $FRONTEND_ORIGIN" \
  -H 'Access-Control-Request-Method: POST' \
  -H 'Access-Control-Request-Headers: content-type'

Finally, read the access log. Entries can take a minute or so to arrive:

Bash
aws logs tail /aws/apigateway/notes-api-demo --since 10m

Check it worked

  • The first call prints {"notes":[]}.
  • The POST returns HTTP/2 201 and a note with an id, your text, "author":null and a createdAt time. A GET straight after usually lists it; if it does not, Lambda served the request from a fresh copy of the function with its own empty list, as described in the first step.
  • The bad body returns 400 with the The body must be JSON message, and DELETE prints 404 because no route matches.
  • The preflight answers with a 2xx status and headers including access-control-allow-origin: https://notes.example.com and access-control-allow-methods naming GET and POST. Send it with -H 'Origin: https://evil.example' instead and that header is missing, so a browser would block the page.
  • The log shows one JSON line per request, with route set to GET /notes or POST /notes, status matching what curl saw, and - for the DELETE route. A 500 with an integrationError mentioning permissions means the add-permission call in the routes step is missing or its source ARN does not match.

Step 7 · Require a JWT to post notes

Anyone can post right now. A JWT authorizer makes API Gateway check a signed token before the request reaches Lambda. You do not write the check yourself: you name your identity provider's issuer URL and the audience your app's tokens carry, and API Gateway fetches the provider's public keys and validates each token's signature, issuer, audience or client_id, expiry and scopes. Failed requests stop at the gateway and cost you no Lambda time.

You need an identity provider that issues JWT access tokens: Amazon Cognito, Auth0, Okta, Keycloak, Microsoft Entra ID or any OpenID Connect provider with RSA-signed tokens. From it, note the issuer URL (for a Cognito user pool, https://cognito-idp.<region>.amazonaws.com/<user-pool-id>) and the audience (for Cognito access tokens, the app client ID, which they carry as client_id). Set both, replacing the example values with yours:

Bash
export JWT_ISSUER="https://cognito-idp.eu-west-2.amazonaws.com/eu-west-2_AbCdEf123"
export JWT_AUDIENCE="your-app-client-id"

Create the authorizer, then attach it to the POST route only, so reading stays public:

Bash
AUTHORIZER_ID=$(aws apigatewayv2 create-authorizer --api-id "$API_ID" \
  --name notes-api-demo-jwt \
  --authorizer-type JWT \
  --identity-source '$request.header.Authorization' \
  --jwt-configuration "Audience=${JWT_AUDIENCE},Issuer=${JWT_ISSUER}" \
  --query AuthorizerId --output text)
aws apigatewayv2 update-route --api-id "$API_ID" --route-id "$POST_ROUTE_ID" \
  --authorization-type JWT \
  --authorizer-id "$AUTHORIZER_ID" \
  --authorization-scopes notes/write \
  --query '[RouteKey,AuthorizationType]' --output text
  • --identity-source tells API Gateway where to find the token. Clients send Authorization: Bearer <token>; the `Bearer ` prefix is optional.
  • --authorization-scopes notes/write requires the token to carry that scope. Use a scope your provider actually issues (in Cognito, a custom scope on a resource server). Requiring a scope also stops someone using an ID token, which looks like an access token to API Gateway.
  • Because auto-deploy is on, the change is live as soon as update-route returns. Preflight OPTIONS requests are still answered by the CORS configuration, without a token.

Inside the function, the token's claims arrive in event.requestContext.authorizer.jwt.claims. The handler already stores claims.sub as the note's author, so each note records who posted it.

Try it without a token, then with one. How you get a token depends on your provider; to try it, sign in through your app or the provider's test tools and copy the access token into a variable with read -rs TOKEN, so it stays out of your shell history:

Bash
curl -s -i -X POST "$API_URL/notes" -H 'content-type: application/json' -d '{"text":"No token"}'
read -rs TOKEN
curl -s -i -X POST "$API_URL/notes" \
  -H "Authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -d '{"text":"Signed in"}'
curl -s "$API_URL/notes"

Check it worked

update-route prints POST /notes and JWT. On the live API, the call without a token returns 401 with a body like {"message":"Unauthorized"}; the call with a valid token returns 201 and a note whose author is your user's sub; and GET /notes still works with no token. A token that is valid but lacks the notes/write scope is refused too, and the access log's authError field says why.

Bash
aws apigatewayv2 get-route --api-id "$API_ID" --route-id "$POST_ROUTE_ID" \
  --query '[AuthorizationType,AuthorizationScopes[0]]' --output text
aws apigatewayv2 get-route --api-id "$API_ID" --route-id "$GET_ROUTE_ID" \
  --query AuthorizationType --output text

The first command prints JWT and notes/write; the second prints NONE (or None) for the public GET route.

Step 8 · Clean up

Deleting the API removes its routes, integration, stage, CORS settings and authorizer in one go. Then remove the function, its role and both log groups. Every name below is this tutorial's own; check that before you run it:

Bash
aws apigatewayv2 delete-api --api-id "$API_ID"
aws lambda delete-function --function-name notes-api-demo
aws iam delete-role-policy --role-name notes-api-demo-role --policy-name logs-only
aws iam delete-role --role-name notes-api-demo-role
aws logs delete-log-group --log-group-name /aws/apigateway/notes-api-demo
aws logs delete-log-group --log-group-name /aws/lambda/notes-api-demo
cd ~
rm -rf ~/notes-api-demo

If you created a user pool or app client only for the JWT step, delete it in your identity provider too.

Check it worked

aws apigatewayv2 get-apis --query "Items[?Name=='notes-api-demo']" prints an empty list, aws lambda get-function --function-name notes-api-demo fails with ResourceNotFoundException, aws iam get-role --role-name notes-api-demo-role fails with NoSuchEntity, and ~/notes-api-demo is gone. Calling $API_URL/notes now fails to resolve the host.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.