Integrating API Gateway with Lambda and AWS services
How to connect Amazon API Gateway to AWS Lambda and other AWS services, the request/response flow, permission setup, mapping templates, proxy vs non-proxy integrations, and common exam-style examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use API Gateway to expose HTTP(S) endpoints to clients (web, mobile, IoT) and connect those endpoints to compute or AWS services. Integrating Amazon API Gateway with AWS Lambda and other AWS services provides a scalable, serverless way to host REST/HTTP APIs without managing servers.
Key ideas
Integration types — exact options API Gateway REST API supports for connecting a method to a backend: HTTP (call an external HTTP endpoint), HTTP_PROXY (simple proxy to HTTP backend), AWS (direct AWS service action using request templates and SigV4), AWS_PROXY (Lambda proxy integration), and MOCK (returns static responses). There is no separate integration type named LAMBDA or LAMBDA_PROXY; Lambda non-proxy uses type AWS with a Lambda invocation URI, and Lambda proxy uses type AWS_PROXY. Each integration type changes what API Gateway sends to the backend and what you must configure.
Lambda proxy integration — API Gateway forwards the full HTTP request to Lambda as a single event object. The Lambda is responsible for returning a properly formed HTTP response object (statusCode, headers, body). This is the simplest and most common pattern.
Exact Lambda proxy event fields to expect (REST API v1): resource, path, httpMethod, headers, multiValueHeaders, queryStringParameters, multiValueQueryStringParameters, pathParameters, stageVariables, requestContext, body, isBase64Encoded. Draw these as keys in a JSON box labelled "Lambda event" when drawing a diagram. Note: HTTP API (v2) uses a different event shape with keys like
version,routeKey,rawPath,rawQueryString,cookies, andrequestContext.http.method.Non-proxy (custom) integration — API Gateway applies mapping templates (Velocity Template Language, VTL) to transform incoming request data into a different format for the backend (for example to call a DynamoDB PutItem or to pass a smaller JSON to Lambda). You must also map backend responses into method responses.
Mapping templates and VTL — VTL (Velocity Template Language) is the template language used in API Gateway to transform request and response payloads. Important built-ins:
$input,$context,$util. Examples:$input.json('$')returns the whole JSON body;$context.identity.sourceIpreturns client IP.IAM and resource-based permissions — when API Gateway invokes an AWS service it either assumes an IAM role (for AWS integrations) or you must add a resource-based policy to the Lambda function allowing the principal
apigateway.amazonaws.comto calllambda:InvokeFunction. For Lambda proxy integration, you normally runaws lambda add-permissionwith a--source-arnthat restricts which API and stage can invoke the function.Execution flow (draw this diagram in exams) — Draw three boxes left-to-right: Client -> API Gateway -> Backend (Lambda or AWS service). Label arrows: 1) HTTP request (method, path, headers, query, body) from Client to API Gateway. 2) API Gateway (authorizer, request mapping, integration request) to Backend: if Lambda proxy, arrow labeled "JSON event"; if non-proxy, arrow labeled "mapped payload / AWS action". 3) Backend response to API Gateway (integration response; map via response mapping templates). 4) API Gateway returns HTTP response to Client (method response, CORS headers, status code, body).
Stages and deployments — An API must be deployed to a Stage (for example dev, test, prod) to get an invoke URL. Remember to redeploy after changes.
CORS (Cross-Origin Resource Sharing) — to let browsers call APIs from other origins, set
Access-Control-Allow-Originand other CORS headers in method responses or in Lambda response; common exam point: remember OPTIONS method + Access-Control headers.Error mapping — map backend error patterns to HTTP status codes using integration response with regex on the backend response or status code mapping.
Assumptions: the student has basic knowledge of AWS identity (IAM) and Lambda function packaging. Refer to other topics (e.g., IAM and VPC with Python, AWS Lambda functions) for deep details.
Formulas
For this programming topic, memorize these exact syntaxes and key fields.
API Gateway Lambda proxy event keys to remember (REST API v1):
resource,path,httpMethod,headers,multiValueHeaders,queryStringParameters,multiValueQueryStringParameters,pathParameters,stageVariables,requestContext,body,isBase64Encoded.aws CLI for adding Lambda permission (exact syntax to remember):
aws lambda add-permission --function-name FUNCTION_NAME --statement-id STATEMENT_ID --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn arn:aws:execute-api:REGION:ACCOUNT_ID:API_ID/STAGE/HTTP_VERB/RESOURCE_PATHWhere
API_IDis the API Gateway identifier,STAGEis the deployment stage (or*),HTTP_VERBis e.g. GET or*,RESOURCE_PATHis resource path or*.Example Lambda response format (proxy integration) to return HTTP 200 with JSON body:
{ "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": "<stringified JSON>", "isBase64Encoded": false }VTL examples to remember:
$input.json('$')— whole JSON body.$input.path('$.userId')— JSONPath into body.$util.escapeJavaScript($input.body)— escape a string for JSON embedding.$context.identity.sourceIp— caller IP.ARN pattern for API Gateway execute-api:
arn:aws:execute-api:REGION:ACCOUNT_ID:API_ID/STAGE/METHOD/RESOURCE_PATH.
Worked examples
Example 1 — Lambda proxy integration (trace):
Given: API method GET /users/{id} triggers Lambda function GetUser. Client calls GET https://abcde.execute-api.region.amazonaws.com/prod/users/42?verbose=true with header Accept: application/json.
Steps:
- API Gateway receives HTTP request. It constructs the proxy event JSON. Key fields include
path=/users/42,httpMethod=GET,pathParameters={ "id": "42" },queryStringParameters={ "verbose": "true" },headersincludesAccept: application/json. - API Gateway invokes Lambda
GetUser. The function must have a resource-based policy allowing the principalapigateway.amazonaws.comwith an appropriateSourceArnfor this API/stage. The Lambda handler signature receiveseventandcontext. - Example minimal Node.js Lambda handler reads
event.pathParameters.idandevent.queryStringParameters.verbose, queries a database, and returns:{ "statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": JSON.stringify({"id":"42","name":"Ravi"}), "isBase64Encoded": false }. - API Gateway forwards response to client with HTTP 200 and the JSON body.
Example 2 — Non-proxy integration using VTL to call Lambda with a clean payload:
Goal: map POST /orders body to a small JSON { "userId": <from header>, "items": <from body>.items } to send to Lambda.
Request: headers include x-user-id: 123; body is { "items": [{"sku":"A1","qty":2}], "promo":"X" }.
Mapping template (VTL) used in Integration Request (exact text to remember):
{ "userId": "$input.params('header','x-user-id')", "items": $input.json('$.items') }
Steps:
- API Gateway applies mapping template and sends
{ "userId": "123", "items": [{"sku":"A1","qty":2}] }as body to Lambda. - Lambda expects this small payload and returns business result. API Gateway maps Lambda response into HTTP response via Integration Response mapping.
Example 3 — Adding permission (exact command):
Command to allow API Gateway to invoke MyFunction for any method on API ID abc123 in region ap-south-1:
aws lambda add-permission --function-name MyFunction --statement-id apigw-invoke --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn arn:aws:execute-api:ap-south-1:123456789012:abc123/*/*/*
Check: After running, aws lambda get-policy --function-name MyFunction shows a statement with Principal = apigateway.amazonaws.com and Condition on ArnLike for AWS:SourceArn.
Common mistakes
- Confusing Lambda proxy vs non-proxy payloads: Lambda proxy receives full HTTP details; non-proxy receives only what mapping templates send.
- Incorrect VTL syntax: forgetting to escape input when embedding into JSON, causing broken JSON sent to backend.
- CORS issues: not adding OPTIONS method or not returning
Access-Control-Allow-Originheaders. - Wrong response mapping: backend returns a string but API expects an object; mismatch leads to 502 or mapping errors.
- Relying on Console defaults without checking
isBase64Encodedfor binary content; binary payloads need special handling.
For your exam
Kinds of questions:
- Definitions: define API Gateway, Lambda proxy integration, VTL mapping template, resource-based policy.
- Short notes: explain Lambda proxy vs non-proxy, describe CORS configuration in API Gateway.
- Diagram question: draw request flow showing API Gateway stages, integration request/response, mapping templates, and Lambda execution.
- Small program/trace: given a proxy event, show how a Lambda handler extracts parameters; or given a VTL template, produce the mapped payload.
- Commands: write the aws CLI command to add permission for API Gateway to invoke Lambda, and format an API invoke ARN.
What a full-marks answer includes:
- Exact definitions with bolded terms.
- Correct request flow diagram labels and a clear description of each step.
- For command questions: exact CLI syntax or JSON of resource policy with correct principal and action.
- For transformation questions: the exact mapping template and the resulting payload after transformation, with correct escaping.
Quick check
- Name two differences between Lambda proxy and Lambda non-proxy integrations.
- What principal must appear in a Lambda resource policy to allow API Gateway invocation?
- Which VTL variable returns the client's IP address?
Answers: 1) Proxy forwards the whole HTTP request as an event; Lambda must return statusCode+body. Non-proxy uses VTL mapping templates to control payloads and response mapping. 2) apigateway.amazonaws.com. 3) $context.identity.sourceIp.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?