Menu
Amazon API Gateway
Developer Guide

Map Response Payload

In this walkthrough, you will learn how to use models and mapping templates in API Gateway to transform the output of an API call from one data schema to another. This walkthrough builds on the instructions and concepts in the Build an API to Expose a Lambda Function and the Map Request Parameters. If you have not yet completed those walkthroughs, we suggest you do them first.

This walkthrough will use API Gateway to get example data from a publicly-accessible HTTP endpoint and from an AWS Lambda function you will create. Both the HTTP endpoint and the Lambda function return the same example data:

Copy
[ { "id": 1, "type": "dog", "price": 249.99 }, { "id": 2, "type": "cat", "price": 124.99 }, { "id": 3, "type": "fish", "price": 0.99 } ]

You will use models and mapping templates to transform this data to one or more output formats. In API Gateway, a model defines the format, also known as the schema or shape, of some data. In API Gateway, a mapping template is used to transform some data from one format to another. For more information, see Create Models and Mapping Templates for Request and Response Payloads.

The first model and mapping template is used to rename id to number, type to class, and price to salesPrice, as follows:

Copy
[ { "number": 1, "class": "dog", "salesPrice": 249.99 }, { "number": 2, "class": "cat", "salesPrice": 124.99 }, { "number": 3, "class": "fish", "salesPrice": 0.99 } ]

The second model and mapping template is used to combine id and type into description, and to rename price to askingPrice, as follows:

Copy
[ { "description": "Item 1 is a dog.", "askingPrice": 249.99 }, { "description": "Item 2 is a cat.", "askingPrice": 124.99 }, { "description": "Item 3 is a fish.", "askingPrice": 0.99 } ]

The third model and mapping template is used to combine id, type, and price into a set of listings, as follows:

Copy
{ "listings": [ "Item 1 is a dog. The asking price is 249.99.", "Item 2 is a cat. The asking price is 124.99.", "Item 3 is a fish. The asking price is 0.99." ] }

Prerequisites

Before you begin this walkthrough, you should have already done the following:

  1. Complete the steps in Get Ready to Use API Gateway, including assigning API Gateway access permission to an IAM user.

  2. Open the API Gateway console and create a new API named MyDemoAPI. For more information, see Build an API Gateway API to Expose an HTTP Endpoint.

  3. Create two resources: petstorewalkthrough and pets. For more information, see Create Resources in the Map Request Parameters.

  4. To use the Lambda portions of this walkthrough, make sure the IAM user has full access to work with Lambda. You can use the IAM console to attach the AWSLambdaFullAccess AWS managed policy to the IAM user.

  5. Make sure the IAM user has access to create policies and roles in IAM. If you have not done so already, create a Lambda execution role named APIGatewayLambdaExecRole in IAM. For more information, see Create Lambda Functions in the Build an API to Expose a Lambda Function.

Step 1: Create Models

In this step, you will create four models. The first three models represent the data output formats for use with the HTTP endpoint and the Lambda function. The last model represents the data input schema for use with the Lambda function.

To create the first output model

  1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway.

  2. If MyDemoAPI is displayed, choose Models.

  3. Choose Create.

  4. For Model name, type PetsModelNoFlatten.

  5. For Content type, type application/json.

  6. For Model description, type Changes id to number, type to class, and price to salesPrice.

  7. For Model schema, type the following JSON Schema-compatible definition:

    Copy
    { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PetsModelNoFlatten", "type": "array", "items": { "type": "object", "properties": { "number": { "type": "integer" }, "class": { "type": "string" }, "salesPrice": { "type": "number" } } } }
  8. Choose Create model.

To create the second output model

  1. Choose Create.

  2. For Model name, type PetsModelFlattenSome.

  3. For Content type, type application/json.

  4. For Model description, type Combines id and type into description, and changes price to askingPrice.

  5. For Model schema, type the following:

    Copy
    { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PetsModelFlattenSome", "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "askingPrice": { "type": "number" } } } }
  6. Choose Create model.

To create the third output model

  1. Choose Create.

  2. For Model name, type PetsModelFlattenAll.

  3. For Content type, type application/json.

  4. For Model description, type Combines id, type, and price into a set of listings.

  5. For Model schema, type the following:

    Copy
    { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PetsModelFlattenAll", "type": "object", "properties": { "listings": { "type": "array", "items": { "type": "string" } } } }
  6. Choose Create model.

To create the input model

  1. Choose Create.

  2. For Model name, type PetsLambdaModel.

  3. For Content type, type application/json.

  4. For Model description, type GetPetsInfo model.

  5. For Model schema, type the following:

    Copy
    { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PetsLambdaModel", "type": "array", "items": { "type": "object", "properties": { "id": { "type": "integer" }, "type": { "type": "string" }, "price": { "type": "number" } } } }
  6. Choose Create model.

Step 2: Create Resources

In this step, you will create four resources. The first three resources will enable you to get the example data from the HTTP endpoint in the three output formats. The last resource will enable you to get the example data from the Lambda function in the output schema that combines id and type into description and renames price to askingPrice.

To create the first resource

  1. In the links list, choose Resources.

  2. In the Resources pane, choose /petstorewalkthrough, and then choose Create Resource.

  3. For Resource Name, type NoFlatten.

  4. For Resource Path, accept the default of /petstorewalkthrough/noflatten, and then choose Create Resource.

To create the second resource

  1. In the Resources pane, choose /petstorewalkthrough again, and then choose Create Resource.

  2. For Resource Name, type FlattenSome.

  3. For Resource Path, accept the default of /petstorewalkthrough/flattensome, and then choose Create Resource.

To create the third resource

  1. In the Resources pane, choose /petstorewalkthrough again, and then choose Create Resource.

  2. For Resource Name, type FlattenAll.

  3. For Resource Path, accept the default of /petstorewalkthrough/flattenall, and then choose Create Resource.

To create the fourth resource

  1. In the Resources pane, choose /petstorewalkthrough again, and then choose Create Resource.

  2. For Resource Name, type LambdaFlattenSome.

  3. For Resource Path, accept the default of /petstorewalkthrough/lambdaflattensome, and then choose Create Resource.

Step 3: Create GET Methods

In this step, you will create a GET method for each of the resources you created in the previous step.

To create the first GET method

  1. In the Resources list, choose /petstorewalkthrough/flattenall, and then choose Create Method.

  2. From the drop-down list, choose GET, and then choose the checkmark icon to save your choice.

  3. In the Setup pane, choose HTTP for the Integration type and GET for HTTP method, type http://petstore-demo-endpoint.execute-api.com/petstore/pets in Endpoint URL, and choose Save.

To create the second GET method

  1. In the Resources list, choose /petstorewalkthrough/lambdaflattensome, and then choose Create Method.

  2. From the drop-down list, choose GET, and then choose the checkmark to save your choice.

  3. In the Setup pane, choose Lambda Function for the Integration type, choose the region where you have created the GetPetsInfo Lambda function from the Lambda Region drop-down list, choose GetPetsInfo for Lambda Function, and choose Save. Choose OK when prompted to add permission to the Lambda function.

To create the third GET method

  1. In the Resources list, choose /petstorewalkthrough/flattensome, and then choose Create Method.

  2. From the drop-down list, choose GET, and then choose the checkmark icon to save your choice.

  3. In the Setup pane, choose HTTP for the Integration type and GET for HTTP method, type http://petstore-demo-endpoint.execute-api.com/petstore/pets in Endpoint URL, and then choose Save.

To create the fourth GET method

  1. In the Resources list, choose /petstorewalkthrough/noflatten, and then choose Actions, Create Method.

  2. From the drop-down list, choose GET, and then choose the checkmark icon to save your choice.

  3. In the Setup pane, choose HTTP for the Integration type and GET for HTTP method, type http://petstore-demo-endpoint.execute-api.com/petstore/pets in Endpoint URL, and then choose Save.

Step 4: Create a Lambda Function

In this step, you will create a Lambda function that returns the sample data.

To create the Lambda function

  1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/.

  2. Do one of the following:

    • If a welcome page appears, choose Get Started Now.

    • If the Lambda: Function list page appears, choose Create a Lambda function.

  3. For Name, type GetPetsInfo.

  4. For Description, type Gets information about pets.

  5. For Code template, choose None.

  6. Type the following code:

    Copy
    console.log('Loading event'); exports.handler = function(event, context, callback) { callback(null, [{"id": 1, "type": "dog", "price": 249.99}, {"id": 2, "type": "cat", "price": 124.99}, {"id": 3, "type": "fish", "price": 0.99}]); // SUCCESS with message };

    Tip

    In the preceding code, written in Node.js, console.log writes information to an Amazon CloudWatch log. event contains the input to the Lambda function. context contains calling context. callback returns the result (for node.js 4.3 and later). For more information about how to write Lambda function code, see the "Programming Model" section in AWS Lambda: How it Works and the sample walkthroughs in the AWS Lambda Developer Guide.

  7. For Handler name, leave the default of index.handler.

  8. For Role, choose the Lambda execution role, APIGatewayLambdaExecRole, you created in the Build an API to Expose a Lambda Function.

  9. Choose Create Lambda function.

  10. In the list of functions, choose GetPetsInfo to show the function's details.

  11. Make a note of the AWS region where you created this function. You will need it later.

  12. In the pop-up list, choose Edit or test function.

  13. For Sample event, replace any code that appears with the following:

    Copy
    { }

    Tip

    The empty curly braces mean there are no input values for this Lambda function. This function simply returns the JSON object containing the pets information, so those key/value pairs are not required here.

  14. Choose Invoke. Execution result shows [{"id":1,"type":"dog","price":249.99},{"id":2,"type":"cat","price":124.99},{"id":3,"type":"fish","price":0.99}], which is also written to the CloudWatch logs.

  15. Choose Go to function list.

Step 5: Set Up and Test the Methods

In this step, you will configure the method responses, integration requests and integration responses to specify the input and output data schemas (or models) for the GET methods associated with the HTTP endpoint and the Lambda function. You will also learn to test calling these methods using the API Gateway console.

To set up the integration for the first GET method and then test it

  1. From the API's Resources tree, choose GET under the /petstorewalkthrough/flattenall node.

  2. In the Method Execution pane, choose Method Response, and then choose the arrow next to 200.

  3. In the Response Models for 200 area, for application/json, choose the pencil icon to start setting up the model for the method output. For Models, choose PetsModelFlattenAll, and then choose the checkmark icon to save the setting.

  4. Choose Method Execution, choose Integration Response, and then choose the arrow next to 200.

  5. Expand the Body Mapping Templates section, choose application/json under Content-Type.

  6. For Generate template from model, choose PetsModelFlattenAll to display a mapping template after the PetsModelFlattenAll model as a starting point.

  7. Modify the mapping template code as follows:

    Copy
    #set($inputRoot = $input.path('$')) { "listings" : [ #foreach($elem in $inputRoot) "Item number $elem.id is a $elem.type. The asking price is $elem.price."#if($foreach.hasNext),#end #end ] }
  8. Choose Save.

  9. Choose Method Execution, and in the Client box, choose TEST, and then choose Test. If successful, Response Body will display the following:

    Copy
    { "listings" : [ "Item number 1 is a dog. The asking price is 249.99.", "Item number 2 is a cat. The asking price is 124.99.", "Item number 3 is a fish. The asking price is 0.99." ] }

To set up integration for the second GET method and then test it

  1. From the API's Resources tree, choose GET under the /petstorewalkthrough/lambdaflattensome node.

  2. In Method Execution, choose Method Response. And then choose the arrow next to 200 to expand the section.

  3. In the Response Models for 200 area, choose the pencil icon on the row for the content type of application/json. Choose PetsModelFlattenSome for Models, and then choose the check mark icon to save the choice.

  4. Go back to Method Execution. Choose Integration Response, and then choose the arrow next to 200.

  5. In the Body Mapping Templates section, choose application/json under Content-Type.

  6. For Generate template, choose PetsModelFlattenSome to display the mapping script template for the output of this method.

  7. Modify the code as follows, and then choose Save:

    Copy
    #set($inputRoot = $input.path('$')) [ #foreach($elem in $inputRoot) { "description" : "Item $elem.id is a $elem.type.", "askingPrice" : $elem.price }#if($foreach.hasNext),#end #end ]
  8. Choose Method Execution, and in the Client box, choose TEST, and then choose Test. If successful, Response Body will display the following:

    Copy
    [ { "description" : "Item 1 is a dog.", "askingPrice" : 249.99 }, { "description" : "Item 2 is a cat.", "askingPrice" : 124.99 }, { "description" : "Item 3 is a fish.", "askingPrice" : 0.99 } ]

To set up integration for the third GET method and then test it

  1. From the API's Resources tree, choose GET under the /petstorewalkthrough/flattensome node.

  2. In the Method Execution pane, choose Method Response.

  3. Choose the arrow next to 200.

  4. In the Response Models for 200 area, for application/json, choose the pencil icon. For Models, choose PetsModelFlattenSome, and then choose the check-mark icon to save the choice.

  5. Go back to Method Execution and choose Integration Response.

  6. Choose the arrow next to 200 to expand the section.

  7. Expand the Body Mapping Templates area. Choose application/json for Content-Type. For Generate template, choose PetsModelFlattenSome to display a mapping script template for the output of this method.

  8. Modify the code as follows:

    Copy
    #set($inputRoot = $input.path('$')) [ #foreach($elem in $inputRoot) { "description": "Item $elem.id is a $elem.type.", "askingPrice": $elem.price }#if($foreach.hasNext),#end #end ]
  9. Choose Save.

  10. Go back to Method Execution and choose TEST in the Client box. And then choose Test. If successful, Response Body will display the following:

    Copy
    [ { "description": "Item 1 is a dog.", "askingPrice": 249.99 }, { "description": "Item 2 is a cat.", "askingPrice": 124.99 }, { "description": "Item 3 is a fish.", "askingPrice": 0.99 } ]

To set up integration for the fourth GET method and then test it

  1. From the API's Resources tree, choose GET under the /petstorewalkthrough/noflatten node.

  2. In the Method Execution pane, choose Method Response, and then expand the 200 section.

  3. In the Response Models for 200 area, for application/json, choose the pencil icon to update the response model for this method.

  4. Choose PetsModelNoFlatten as the model for the content type of application/json, and then choose the check-mark icon to save the choice.

  5. Choose Method Execution, choose Integration Response, and then choose the arrow next to 200 to expand the section.

  6. Expand the Mapping Mapping Templates section. Choose application/json for Content-Type. For Generate templates, choose PetsModelNoFlatten to display a mapping script template for the output of this method.

  7. Modify the code as follows:

    Copy
    #set($inputRoot = $input.path('$')) [ #foreach($elem in $inputRoot) { "number": $elem.id, "class": "$elem.type", "salesPrice": $elem.price }#if($foreach.hasNext),#end #end ]
  8. Choose Save.

  9. Go back to Method Execution, and in the Client box, choose TEST, and then choose Test. If successful, Response Body will display the following:

    Copy
    [ { "number": 1, "class": "dog", "salesPrice": 249.99 }, { "number": 2, "class": "cat", "salesPrice": 124.99 }, { "number": 3, "class": "fish", "salesPrice": 0.99 } ]

Step 6: Deploy the API

In this step, you will deploy the API so that you can begin calling it outside of the API Gateway console.

To deploy the API

  1. In the Resources pane, choose Deploy API.

  2. For Deployment stage, choose test.

  3. For Deployment description, type Using models and mapping templates walkthrough.

  4. Choose Deploy.

Step 7: Test the API

In this step, you will go outside of the API Gateway console to interact with both the HTTP endpoint and the Lambda function.

  1. In the Stage Editor pane, next to Invoke URL, copy the URL to the clipboard. It should look something like this:

    Copy
    https://my-api-id.execute-api.region-id.amazonaws.com/test
  2. Paste this URL in the address box of a new browser tab.

  3. Append /petstorewalkthrough/noflatten so that it looks like this:

    Copy
    https://my-api-id.execute-api.region-id.amazonaws.com/test/petstorewalkthrough/noflatten

    Browse to the URL. The following information should be displayed:

    Copy
    [ { "number": 1, "class": "dog", "salesPrice": 249.99 }, { "number": 2, "class": "cat", "salesPrice": 124.99 }, { "number": 3, "class": "fish", "salesPrice": 0.99 } ]
  4. After petstorewalkthrough/, replace noflatten with flattensome.

  5. Browse to the URL. The following information should be displayed:

    Copy
    [ { "description": "Item 1 is a dog.", "askingPrice": 249.99 }, { "description": "Item 2 is a cat.", "askingPrice": 124.99 }, { "description": "Item 3 is a fish.", "askingPrice": 0.99 } ]
  6. After petstorewalkthrough/, replace flattensome with flattenall.

  7. Browse to the URL. The following information should be displayed:

    Copy
    { "listings" : [ "Item number 1 is a dog. The asking price is 249.99.", "Item number 2 is a cat. The asking price is 124.99.", "Item number 3 is a fish. The asking price is 0.99." ] }
  8. After petstorewalkthrough/, replace flattenall with lambdaflattensome.

  9. Browse to the URL. The following information should be displayed:

    Copy
    [ { "description" : "Item 1 is a dog.", "askingPrice" : 249.99 }, { "description" : "Item 2 is a cat.", "askingPrice" : 124.99 }, { "description" : "Item 3 is a fish.", "askingPrice" : 0.99 } ]

Step 8: Clean Up

If you no longer need the Lambda function you created for this walkthrough, you can delete it now. You can also delete the accompanying IAM resources.

Warning

If you delete a Lambda function your APIs rely on, those APIs will no longer work. Deleting a Lambda function cannot be undone. If you want to use the Lambda function again, you must re-create the function.

If you delete an IAM resource a Lambda function relies on, the Lambda function and any APIs that rely on it will no longer work. Deleting an IAM resource cannot be undone. If you want to use the IAM resource again, you must re-create the resource. If you plan to continue experimenting with the resources you created for this and the other walkthroughs, do not delete the Lambda invocation role or the Lambda execution role.

API Gateway does not currently support the deactivation or deletion of APIs that no longer work.

To delete the Lambda function

  1. Sign in to the AWS Management Console and open the AWS Lambda console at https://console.aws.amazon.com/lambda/.

  2. On the Lambda: Function list page, in the list of functions, choose the button next to GetPetsInfo, and then choose Actions, Delete. When prompted, choose Delete again.

To delete the associated IAM resources

  1. Open the IAM console at https://console.aws.amazon.com/iam/.

  2. In the Details area, choose Roles.

  3. Select APIGatewayLambdaExecRole, and then choose Role Actions, Delete Role. When prompted, choose Yes, Delete.

  4. In the Details area, choose Policies.

  5. Select APIGatewayLambdaExecPolicy, and then choose Policy Actions, Delete. When prompted, choose Delete.

You have now reached the end of this walkthrough.

Next Steps

You may want to begin the next walkthrough, which shows you how to create an API Gateway API to access an AWS service. See Create an AWS Service Proxy.