Bird
Raised Fist0
AWScloud~5 mins

Request and response mapping in AWS - Commands & Configuration

Choose your learning style10 modes available
Introduction
When you create an API with AWS API Gateway, you often need to change the shape of the data that comes in or goes out. Request and response mapping lets you change the data format so your backend and frontend can talk smoothly, even if they expect different formats.
When your frontend sends data in a format your backend does not understand.
When your backend returns data that needs to be simplified or changed before sending to the user.
When you want to add or remove fields from the data without changing your backend code.
When you want to convert data formats, like from JSON to XML or vice versa.
When you want to log or audit the data passing through your API.
Config File - api-gateway-mapping-template.vtl
api-gateway-mapping-template.vtl
# Request mapping template example
{
  "userId": "$input.path('$.user.id')",
  "action": "$input.path('$.action')"
}

# Response mapping template example
{
  "status": "$input.path('$.status')",
  "message": "$input.path('$.message')"
}

This file contains two Velocity Template Language (VTL) templates used by AWS API Gateway.

The first part is the request mapping template. It extracts the user ID and action from the incoming JSON and creates a new JSON with just those fields to send to the backend.

The second part is the response mapping template. It takes the backend response and extracts the status and message fields to send back to the client.

Commands
Create a new REST API named 'example-api' in AWS API Gateway.
Terminal
aws apigateway create-rest-api --name example-api
Expected OutputExpected
{ "id": "a1b2c3d4e5", "name": "example-api", "createdDate": "2024-06-01T12:00:00Z", "endpointConfiguration": { "types": ["REGIONAL"] } }
→
--name - Sets the name of the new API
Set up the integration between the API Gateway POST method and a Lambda function, using the request mapping template to transform incoming data.
Terminal
aws apigateway put-integration --rest-api-id a1b2c3d4e5 --resource-id r1a2b3c4 --http-method POST --type AWS_PROXY --integration-http-method POST --uri arn:aws:lambda:us-east-1:123456789012:function:my-function --request-templates file://api-gateway-mapping-template.vtl
Expected OutputExpected
{ "type": "AWS_PROXY", "httpMethod": "POST", "uri": "arn:aws:lambda:us-east-1:123456789012:function:my-function", "requestTemplates": { "application/json": "# Request mapping template example\n{\n \"userId\": \"$input.path('$.user.id')\",\n \"action\": \"$input.path('$.action')\"\n}\n" } }
→
--rest-api-id - Specifies the API to configure
→
--resource-id - Specifies the resource within the API
→
--request-templates - Points to the file with the request mapping template
Define the method response for HTTP 200 status with an empty model, preparing for response mapping.
Terminal
aws apigateway put-method-response --rest-api-id a1b2c3d4e5 --resource-id r1a2b3c4 --http-method POST --status-code 200 --response-models application/json=Empty
Expected OutputExpected
{}
→
--status-code - Sets the HTTP status code for the response
Set the response mapping template to transform the backend response before sending it to the client.
Terminal
aws apigateway put-integration-response --rest-api-id a1b2c3d4e5 --resource-id r1a2b3c4 --http-method POST --status-code 200 --response-templates application/json=file://api-gateway-mapping-template.vtl
Expected OutputExpected
{}
→
--response-templates - Points to the file with the response mapping template
Test the API method with a sample request body to see how the request and response mapping works.
Terminal
aws apigateway test-invoke-method --rest-api-id a1b2c3d4e5 --resource-id r1a2b3c4 --http-method POST --body '{"user":{"id":"123"},"action":"login"}'
Expected OutputExpected
{ "status": 200, "body": "{\"status\":\"success\",\"message\":\"User logged in\"}" }
Key Concept

If you remember nothing else from this pattern, remember: request and response mapping lets you change data formats between your API and backend without changing backend code.

Common Mistakes
Not specifying the correct content type in the mapping templates.
API Gateway won't apply the mapping templates if the content type doesn't match, causing data to pass through unchanged or errors.
Always use the correct content type like 'application/json' in your request and response mapping configurations.
Using incorrect JSON path expressions in the mapping templates.
Wrong paths cause missing or wrong data to be sent to the backend or returned to the client.
Test your JSON paths carefully and use tools or logs to verify they extract the right data.
Forgetting to deploy the API after changes.
Changes to mapping templates won't take effect until the API is deployed, so you won't see your updates.
Always deploy your API after making changes to mapping templates.
Summary
Create an API Gateway REST API and define resources and methods.
Use request mapping templates to change incoming data before it reaches your backend.
Use response mapping templates to change backend responses before sending to clients.
Test your API to ensure mappings work as expected.

Practice

(1/5)
1. What is the main purpose of request and response mapping in AWS API Gateway?
easy
A. To encrypt data during transmission
B. To change data formats between client and backend
C. To monitor user activity on the website
D. To store data permanently in the cloud

Solution

  1. Step 1: Understand the role of mapping templates

    Mapping templates in API Gateway transform data formats between client requests and backend responses.
  2. Step 2: Identify the main purpose

    This transformation allows different systems to communicate smoothly by renaming, adding, or removing fields.
  3. Final Answer:

    To change data formats between client and backend -> Option B
  4. Quick Check:

    Mapping templates = data format change [OK]
Hint: Mapping templates transform data formats between client and backend [OK]
Common Mistakes:
  • Confusing mapping with data storage
  • Thinking mapping encrypts data
  • Assuming mapping monitors activity
2. Which of the following is the correct syntax to access a JSON field named userId in a request mapping template?
easy
A. $input.path('$.userId')
B. $input.json('userId')
C. $input.get('userId')
D. $input.body('userId')

Solution

  1. Step 1: Recall JSON path syntax in mapping templates

    The correct way to access a JSON field is using $input.path('$.fieldName').
  2. Step 2: Match the syntax to the field userId

    Using $input.path('$.userId') correctly accesses the userId field.
  3. Final Answer:

    $input.path('$.userId') -> Option A
  4. Quick Check:

    JSON field access = $input.path('$.field') [OK]
Hint: Use $input.path('$.fieldName') to access JSON fields [OK]
Common Mistakes:
  • Using incorrect method names like json or get
  • Missing the '$.' prefix in JSON path
  • Confusing body access with path access
3. Given this request mapping template:
{
  "user": "$input.path('$.username')",
  "id": "$input.path('$.userId')"
}

What will be the transformed request if the client sends:
{"username": "alice", "userId": "123"}
medium
A. {"user": "$.username", "id": "$.userId"}
B. {"username": "alice", "userId": "123"}
C. {"user": "alice", "id": "123"}
D. {"user": null, "id": null}

Solution

  1. Step 1: Understand the mapping template fields

    The template maps user to $.username and id to $.userId.
  2. Step 2: Apply the client JSON values

    Client sends username as "alice" and userId as "123", so these replace the template placeholders.
  3. Final Answer:

    {"user": "alice", "id": "123"} -> Option C
  4. Quick Check:

    Template fields replaced by client values [OK]
Hint: Mapping replaces template fields with client JSON values [OK]
Common Mistakes:
  • Confusing template keys with client keys
  • Leaving placeholders as literal strings
  • Assuming null values when fields exist
4. You have this response mapping template:
{
  "message": "$input.path('$.msg')",
  "status": "$input.path('$.code')"
}

But the backend returns:
{"message": "Success", "code": 200}

What is the main issue causing the mapping to fail?
medium
A. The template uses wrong JSON paths not matching backend keys
B. The backend response is not valid JSON
C. The template syntax is missing quotes around keys
D. The backend response keys are case-insensitive

Solution

  1. Step 1: Compare template paths with backend keys

    The template expects msg and code, but backend returns message and code.
  2. Step 2: Identify mismatch causing failure

    Since msg does not exist in backend response, mapping fails for that field.
  3. Final Answer:

    The template uses wrong JSON paths not matching backend keys -> Option A
  4. Quick Check:

    Template paths must match backend keys exactly [OK]
Hint: Ensure template JSON paths match backend response keys exactly [OK]
Common Mistakes:
  • Assuming backend keys are case-insensitive
  • Thinking syntax errors cause this issue
  • Ignoring key name mismatches
5. You want to add a new field requestTime with the current timestamp to every request sent to your backend using request mapping. Which mapping template snippet correctly adds this field?
hard
A. { "user": "$input.path('$.user')", "requestTime": "$context.stage" }
B. { "user": "$input.path('$.user')", "requestTime": "$input.requestTime" }
C. { "user": "$input.path('$.user')", "requestTime": "$stageVariables.requestTime" }
D. { "user": "$input.path('$.user')", "requestTime": "$context.requestTime" }

Solution

  1. Step 1: Identify how to get current request time

    In API Gateway mapping templates, $context.requestTime provides the current request timestamp.
  2. Step 2: Check each option for correct usage

    { "user": "$input.path('$.user')", "requestTime": "$context.requestTime" } uses $context.requestTime correctly; others use invalid or unrelated variables.
  3. Final Answer:

    { "user": "$input.path('$.user')", "requestTime": "$context.requestTime" } -> Option D
  4. Quick Check:

    Use $context.requestTime for current timestamp [OK]
Hint: Use $context.requestTime to add current timestamp in mapping [OK]
Common Mistakes:
  • Using $input.requestTime which doesn't exist
  • Confusing stage variables with request time
  • Using unrelated context variables
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard