id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
apigateway-dg-052
apigateway-dg.pdf
52
facilitate generating the mapping template. However, you can generate a mapping template without using any model. In this tutorial, we used two slightly different payload formats to illustrate that an API developer can choose to expose the backend data format to the client or hide it from the client. One format is for the PUT /streams/{stream-name}/records method (above). Another format is used for the PUT /streams/{stream-name}/record method (in the previous procedure). In production environment, you should keep both formats consistent. 15. To test the PUT /streams/{stream-name}/records method, set the stream-name path variable to an existing stream, supply the following payload, and submit the method request. { "records": [ { "data": "some data", "partition-key": "some key" }, { "data": "some other data", "partition-key": "some key" } ] } The successful result is a 200 OK response with a payload similar to the following output: Tutorial: Create a REST API as an Amazon Kinesis proxy 180 Amazon API Gateway Developer Guide { "FailedRecordCount": 0, "Records": [ { "SequenceNumber": "49559409944537880850133345460167468741933742152373764162", "ShardId": "shardId-000000000004" }, { "SequenceNumber": "49559409944537880850133345460168677667753356781548470338", "ShardId": "shardId-000000000004" } ] } To set up and test the GET /streams/{stream-name}/sharditerator method invoke GetShardIterator in Kinesis The GET /streams/{stream-name}/sharditerator method is a helper method to acquire a required shard iterator before calling the GET /streams/{stream-name}/records method. 1. Choose the /sharditerator resource, and then choose Create method. 2. 3. 4. 5. For Method type, select GET. For Integration type, select AWS service. For AWS Region, select the AWS Region where you created your Kinesis stream. For AWS service, select Kinesis. 6. Keep AWS subdomain blank. 7. 8. 9. For HTTP method, choose POST. For Action type, choose Use action name. For Action name, enter GetShardIterator. 10. For Execution role, enter the ARN for your execution role. 11. Keep the default of Passthrough for Content Handling. 12. Choose URL query string parameters. The GetShardIterator action requires an input of a ShardId value. To pass a client-supplied ShardId value, we add a shard-id query parameter to the method request, as shown in the following step. Tutorial: Create a REST API as an Amazon Kinesis proxy 181 Amazon API Gateway 13. Choose Add query string. 14. For Name, enter shard-id. 15. Keep Required and Caching turned off. 16. Choose Create method. Developer Guide 17. In the Integration request section, add the following mapping template to generate the required input (ShardId and StreamName) to the GetShardIterator action from the shard-id and stream-name parameters of the method request. In addition, the mapping template also sets ShardIteratorType to TRIM_HORIZON as a default. { "ShardId": "$input.params('shard-id')", "ShardIteratorType": "TRIM_HORIZON", "StreamName": "$input.params('stream-name')" } 18. Using the Test option in the API Gateway console, enter an existing stream name as the stream-name Path variable value, set the shard-id Query string to an existing ShardId value (e.g., shard-000000000004), and choose Test. The successful response payload is similar to the following output: { "ShardIterator": "AAAAAAAAAAFYVN3VlFy..." } Make note of the ShardIterator value. You need it to get records from a stream. To configure and test the GET /streams/{stream-name}/records method to invoke the GetRecords action in Kinesis 1. Choose the /records resource, and then choose Create method. 2. 3. 4. 5. For Method type, select GET. For Integration type, select AWS service. For AWS Region, select the AWS Region where you created your Kinesis stream. For AWS service, select Kinesis. 6. Keep AWS subdomain blank. Tutorial: Create a REST API as an Amazon Kinesis proxy 182 Amazon API Gateway Developer Guide 7. 8. 9. For HTTP method, choose POST. For Action type, choose Use action name. For Action name, enter GetRecords. 10. For Execution role, enter the ARN for your execution role. 11. Keep the default of Passthrough for Content Handling. 12. Choose HTTP request headers. The GetRecords action requires an input of a ShardIterator value. To pass a client- supplied ShardIterator value, we add a Shard-Iterator header parameter to the method request. 13. Choose Add header. 14. For Name, enter Shard-Iterator. 15. Keep Required and Caching turned off. 16. Choose Create method. 17. In the Integration request section, add the following body mapping template to map the Shard-Iterator header parameter value to the ShardIterator property value of the JSON payload for the GetRecords action in Kinesis. { "ShardIterator": "$input.params('Shard-Iterator')" } 18. Using the Test option in the API Gateway console, enter an existing stream name as the stream-name Path variable value, set the Shard-Iterator Header to the ShardIterator value obtained from the test run of the GET /streams/{stream-name}/sharditerator method (above), and choose Test. The successful response payload is similar to the following output: { "MillisBehindLatest": 0, "NextShardIterator": "AAAAAAAAAAF...", "Records": [ ... ] } Tutorial: Create a REST API as an Amazon Kinesis proxy 183 Amazon API Gateway Developer Guide OpenAPI definitions of a sample API as a Kinesis proxy Following are OpenAPI definitions for the sample API as
apigateway-dg-053
apigateway-dg.pdf
53
"$input.params('Shard-Iterator')" } 18. Using the Test option in the API Gateway console, enter an existing stream name as the stream-name Path variable value, set the Shard-Iterator Header to the ShardIterator value obtained from the test run of the GET /streams/{stream-name}/sharditerator method (above), and choose Test. The successful response payload is similar to the following output: { "MillisBehindLatest": 0, "NextShardIterator": "AAAAAAAAAAF...", "Records": [ ... ] } Tutorial: Create a REST API as an Amazon Kinesis proxy 183 Amazon API Gateway Developer Guide OpenAPI definitions of a sample API as a Kinesis proxy Following are OpenAPI definitions for the sample API as a Kinesis proxy used in this tutorial. OpenAPI 3.0 { "openapi": "3.0.0", "info": { "title": "KinesisProxy", "version": "2016-03-31T18:25:32Z" }, "paths": { "/streams/{stream-name}/sharditerator": { "get": { "parameters": [ { "name": "stream-name", "in": "path", "required": true, "schema": { "type": "string" } }, { "name": "shard-id", "in": "query", "schema": { "type": "string" } } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, Tutorial: Create a REST API as an Amazon Kinesis proxy 184 Amazon API Gateway Developer Guide "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/GetShardIterator", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"ShardId\": \"$input.params('shard- id')\",\n \"ShardIteratorType\": \"TRIM_HORIZON\",\n \"StreamName\": \"$input.params('stream-name')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } } }, "/streams/{stream-name}/records": { "get": { "parameters": [ { "name": "stream-name", "in": "path", "required": true, "schema": { "type": "string" } }, { "name": "Shard-Iterator", "in": "header", "schema": { "type": "string" } } ], "responses": { "200": { Tutorial: Create a REST API as an Amazon Kinesis proxy 185 Amazon API Gateway Developer Guide "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/GetRecords", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"ShardIterator\": \"$input.params('Shard- Iterator')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } }, "put": { "parameters": [ { "name": "Content-Type", "in": "header", "schema": { "type": "string" } }, { "name": "stream-name", "in": "path", "required": true, Tutorial: Create a REST API as an Amazon Kinesis proxy 186 Amazon API Gateway Developer Guide "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/PutRecordsMethodRequestPayload" } }, "application/x-amz-json-1.1": { "schema": { "$ref": "#/components/schemas/PutRecordsMethodRequestPayload" } } }, "required": true }, "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecords", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" Tutorial: Create a REST API as an Amazon Kinesis proxy 187 Amazon API Gateway }, Developer Guide "requestTemplates": { "application/json": "{\n \"StreamName\": \"$input.params('stream- name')\",\n \"Records\": [\n {\n \"Data\": \"$util.base64Encode($elem.data)\",\n \"PartitionKey\": \"$elem.partition-key\"\n }#if($foreach.hasNext),#end\n ]\n}", "application/x-amz-json-1.1": "{\n \"StreamName\": \"$input.params('stream-name')\",\n \"records\" : [\n {\n \"Data \" : \"$elem.data\",\n \"PartitionKey\" : \"$elem.partition-key\"\n }#if($foreach.hasNext),#end\n ]\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } } }, "/streams/{stream-name}": { "get": { "parameters": [ { "name": "stream-name", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/DescribeStream", Tutorial: Create a REST API as an Amazon Kinesis proxy 188 Amazon API Gateway Developer Guide "responses": { "default": { "statusCode": "200" } }, "requestTemplates": { "application/json": "{\n \"StreamName\": \"$input.params('stream- name')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } }, "post": { "parameters": [ { "name": "stream-name", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/CreateStream", "responses": { "default": { "statusCode": "200" } Tutorial: Create a REST API as an Amazon Kinesis proxy 189 Amazon API Gateway }, Developer Guide "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"ShardCount\": 5,\n \"StreamName\": \"$input.params('stream-name')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } }, "delete": { "parameters": [ { "name": "stream-name", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "200 response", "headers": { "Content-Type": { "schema": { "type": "string" } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } }, "400": { "description": "400 response", Tutorial: Create a REST API as an Amazon Kinesis proxy 190 Amazon API Gateway Developer Guide "headers": { "Content-Type": { "schema": { "type": "string" } } }, "content": {} }, "500": { "description": "500 response", "headers": { "Content-Type": { "schema": { "type": "string" } } }, "content": {} } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/DeleteStream", "responses": { "4\\d{2}": { "statusCode": "400", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } },
apigateway-dg-054
apigateway-dg.pdf
54
"200 response", "headers": { "Content-Type": { "schema": { "type": "string" } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } }, "400": { "description": "400 response", Tutorial: Create a REST API as an Amazon Kinesis proxy 190 Amazon API Gateway Developer Guide "headers": { "Content-Type": { "schema": { "type": "string" } } }, "content": {} }, "500": { "description": "500 response", "headers": { "Content-Type": { "schema": { "type": "string" } } }, "content": {} } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/DeleteStream", "responses": { "4\\d{2}": { "statusCode": "400", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } }, "default": { "statusCode": "200", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } }, "5\\d{2}": { "statusCode": "500", "responseParameters": { Tutorial: Create a REST API as an Amazon Kinesis proxy 191 Amazon API Gateway Developer Guide "method.response.header.Content-Type": "integration.response.header.Content-Type" } } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"StreamName\": \"$input.params('stream- name')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } } }, "/streams/{stream-name}/record": { "put": { "parameters": [ { "name": "stream-name", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, "x-amazon-apigateway-integration": { "type": "aws", Tutorial: Create a REST API as an Amazon Kinesis proxy 192 Amazon API Gateway Developer Guide "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecord", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"StreamName\": \"$input.params('stream- name')\",\n \"Data\": \"$util.base64Encode($input.json('$.Data'))\",\n \"PartitionKey\": \"$input.path('$.PartitionKey')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } } }, "/streams": { "get": { "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/ListStreams", "responses": { "default": { "statusCode": "200" } }, Tutorial: Create a REST API as an Amazon Kinesis proxy 193 Amazon API Gateway Developer Guide "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } } } }, "components": { "schemas": { "Empty": { "type": "object" }, "PutRecordsMethodRequestPayload": { "type": "object", "properties": { "records": { "type": "array", "items": { "type": "object", "properties": { "data": { "type": "string" }, "partition-key": { "type": "string" } } } } } } } } } Tutorial: Create a REST API as an Amazon Kinesis proxy 194 Amazon API Gateway OpenAPI 2.0 Developer Guide { "swagger": "2.0", "info": { "version": "2016-03-31T18:25:32Z", "title": "KinesisProxy" }, "basePath": "/test", "schemes": [ "https" ], "paths": { "/streams": { "get": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/ListStreams", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n}" Tutorial: Create a REST API as an Amazon Kinesis proxy 195 Amazon API Gateway }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" Developer Guide } } }, "/streams/{stream-name}": { "get": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "stream-name", "in": "path", "required": true, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/DescribeStream", "responses": { "default": { "statusCode": "200" } }, "requestTemplates": { "application/json": "{\n \"StreamName\": \"$input.params('stream- name')\"\n}" }, "passthroughBehavior": "when_no_match", Tutorial: Create a REST API as an Amazon Kinesis proxy 196 Amazon API Gateway Developer Guide "httpMethod": "POST" } }, "post": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "stream-name", "in": "path", "required": true, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/CreateStream", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"ShardCount\": 5,\n \"StreamName\": \"$input.params('stream-name')\"\n}" }, "passthroughBehavior": "when_no_match", Tutorial: Create a REST API as an Amazon Kinesis proxy 197 Amazon API Gateway Developer Guide "httpMethod": "POST" } }, "delete": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "stream-name", "in": "path", "required": true, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" }, "headers": { "Content-Type": { "type": "string" } } }, "400": { "description": "400 response", "headers": { "Content-Type": { "type": "string" } } }, "500": { "description": "500 response", "headers": { "Content-Type": { "type": "string" } Tutorial: Create a REST API as an Amazon Kinesis proxy 198 Amazon API Gateway } } }, Developer Guide "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/DeleteStream", "responses": { "4\\d{2}": { "statusCode": "400", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } }, "default": { "statusCode": "200", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } }, "5\\d{2}": { "statusCode": "500", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n
apigateway-dg-055
apigateway-dg.pdf
55
"string" } } }, "400": { "description": "400 response", "headers": { "Content-Type": { "type": "string" } } }, "500": { "description": "500 response", "headers": { "Content-Type": { "type": "string" } Tutorial: Create a REST API as an Amazon Kinesis proxy 198 Amazon API Gateway } } }, Developer Guide "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/DeleteStream", "responses": { "4\\d{2}": { "statusCode": "400", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } }, "default": { "statusCode": "200", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } }, "5\\d{2}": { "statusCode": "500", "responseParameters": { "method.response.header.Content-Type": "integration.response.header.Content-Type" } } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"StreamName\": \"$input.params('stream- name')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } } }, "/streams/{stream-name}/record": { Tutorial: Create a REST API as an Amazon Kinesis proxy 199 Amazon API Gateway Developer Guide "put": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "stream-name", "in": "path", "required": true, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecord", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"StreamName\": \"$input.params('stream- name')\",\n \"Data\": \"$util.base64Encode($input.json('$.Data'))\",\n \"PartitionKey\": \"$input.path('$.PartitionKey')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } Tutorial: Create a REST API as an Amazon Kinesis proxy 200 Developer Guide Amazon API Gateway } }, "/streams/{stream-name}/records": { "get": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "stream-name", "in": "path", "required": true, "type": "string" }, { "name": "Shard-Iterator", "in": "header", "required": false, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/GetRecords", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" Tutorial: Create a REST API as an Amazon Kinesis proxy 201 Amazon API Gateway }, Developer Guide "requestTemplates": { "application/json": "{\n \"ShardIterator\": \"$input.params('Shard- Iterator')\"\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } }, "put": { "consumes": [ "application/json", "application/x-amz-json-1.1" ], "produces": [ "application/json" ], "parameters": [ { "name": "Content-Type", "in": "header", "required": false, "type": "string" }, { "name": "stream-name", "in": "path", "required": true, "type": "string" }, { "in": "body", "name": "PutRecordsMethodRequestPayload", "required": true, "schema": { "$ref": "#/definitions/PutRecordsMethodRequestPayload" } }, { "in": "body", "name": "PutRecordsMethodRequestPayload", "required": true, "schema": { "$ref": "#/definitions/PutRecordsMethodRequestPayload" Tutorial: Create a REST API as an Amazon Kinesis proxy 202 Developer Guide Amazon API Gateway } } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/PutRecords", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"StreamName\": \"$input.params('stream- name')\",\n \"Records\": [\n {\n \"Data\": \"$util.base64Encode($elem.data)\",\n \"PartitionKey\": \"$elem.partition-key\"\n }#if($foreach.hasNext),#end\n ]\n}", "application/x-amz-json-1.1": "{\n \"StreamName\": \"$input.params('stream-name')\",\n \"records\" : [\n {\n \"Data \" : \"$elem.data\",\n \"PartitionKey\" : \"$elem.partition-key\"\n }#if($foreach.hasNext),#end\n ]\n}" }, "passthroughBehavior": "when_no_match", "httpMethod": "POST" } } }, "/streams/{stream-name}/sharditerator": { "get": { "consumes": [ "application/json" ], Tutorial: Create a REST API as an Amazon Kinesis proxy 203 Amazon API Gateway Developer Guide "produces": [ "application/json" ], "parameters": [ { "name": "stream-name", "in": "path", "required": true, "type": "string" }, { "name": "shard-id", "in": "query", "required": false, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } }, "x-amazon-apigateway-integration": { "type": "aws", "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "uri": "arn:aws:apigateway:us-east-1:kinesis:action/GetShardIterator", "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.header.Content-Type": "'application/x-amz- json-1.1'" }, "requestTemplates": { "application/json": "{\n \"ShardId\": \"$input.params('shard- id')\",\n \"ShardIteratorType\": \"TRIM_HORIZON\",\n \"StreamName\": \"$input.params('stream-name')\"\n}" }, "passthroughBehavior": "when_no_match", Tutorial: Create a REST API as an Amazon Kinesis proxy 204 Amazon API Gateway Developer Guide "httpMethod": "POST" } } } }, "definitions": { "Empty": { "type": "object" }, "PutRecordsMethodRequestPayload": { "type": "object", "properties": { "records": { "type": "array", "items": { "type": "object", "properties": { "data": { "type": "string" }, "partition-key": { "type": "string" } } } } } } } } Tutorial: Create a REST API using AWS SDKs or the AWS CLI Use the following tutorial to create a PetStore API supporting the GET /pets and GET /pets/ {petId} methods. The methods are integrated with an HTTP endpoint. You can follow this tutorial using the AWS SDK for JavaScript, the SDK for Python (Boto3), or the AWS CLI. You use the following functions or commands to set up your API: JavaScript v3 • CreateRestApiCommand Tutorial: Create a REST API using AWS SDKs or the AWS CLI 205 Amazon API Gateway Developer Guide • CreateResourceCommand • PutMethodCommand • PutMethodResponseCommand • PutIntegrationCommand • PutIntegrationResponseCommand • CreateDeploymentCommand Python • create_rest_api • create_resource • put_method • put_method_response • put_integration • put_integration_response • create_deployment AWS CLI • create-rest-api • create-resource • put-method • put-method-response • put-integration • put-integration-response • create-deployment For more information about the AWS SDK for JavaScript v3, see What's the AWS SDK for JavaScript?. For more information about the SDK for Python
apigateway-dg-056
apigateway-dg.pdf
56
the following functions or commands to set up your API: JavaScript v3 • CreateRestApiCommand Tutorial: Create a REST API using AWS SDKs or the AWS CLI 205 Amazon API Gateway Developer Guide • CreateResourceCommand • PutMethodCommand • PutMethodResponseCommand • PutIntegrationCommand • PutIntegrationResponseCommand • CreateDeploymentCommand Python • create_rest_api • create_resource • put_method • put_method_response • put_integration • put_integration_response • create_deployment AWS CLI • create-rest-api • create-resource • put-method • put-method-response • put-integration • put-integration-response • create-deployment For more information about the AWS SDK for JavaScript v3, see What's the AWS SDK for JavaScript?. For more information about the SDK for Python (Boto3), see AWS SDK for Python (Boto3). For more information about the AWS CLI, see What is the AWS CLI?. Tutorial: Create a REST API using AWS SDKs or the AWS CLI 206 Amazon API Gateway Developer Guide Set up an edge-optimized PetStore API In this tutorial, example commands use placeholder values for value IDs such as API ID and resource ID. As you complete the tutorial, replace these values with your own. To set up an edge-optimized PetStore API using AWS SDKs 1. Use the following example to create a RestApi entity: JavaScript v3 import {APIGatewayClient, CreateRestApiCommand} from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new CreateRestApiCommand({ name: "Simple PetStore (JavaScript v3 SDK)", description: "Demo API created using the AWS SDK for JavaScript v3", version: "0.00.001", binaryMediaTypes: [ '*'] }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.error(Couldn't create API:\n", err) } })(); A successful call returns your API ID and the root resource ID of your API in an output like the following: { id: 'abc1234', name: 'PetStore (JavaScript v3 SDK)', description: 'Demo API created using the AWS SDK for node.js', createdDate: 2017-09-05T19:32:35.000Z, version: '0.00.001', rootResourceId: 'efg567' binaryMediaTypes: [ '*' ] } Tutorial: Create a REST API using AWS SDKs or the AWS CLI 207 Amazon API Gateway Python import botocore import boto3 import logging Developer Guide logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.create_rest_api( name='Simple PetStore (Python SDK)', description='Demo API created using the AWS SDK for Python', version='0.00.001', binaryMediaTypes=[ '*' ] ) except botocore.exceptions.ClientError as error: logger.exception("Couldn't create REST API %s.", error) raise attribute=["id","name","description","createdDate","version","binaryMediaTypes","apiKeySource","endpointConfiguration","disableExecuteApiEndpoint","rootResourceId"] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns your API ID and the root resource ID of your API in an output like the following: {'id': 'abc1234', 'name': 'Simple PetStore (Python SDK)', 'description': 'Demo API created using the AWS SDK for Python', 'createdDate': datetime.datetime(2024, 4, 3, 14, 31, 39, tzinfo=tzlocal()), 'version': '0.00.001', 'binaryMediaTypes': ['*'], 'apiKeySource': 'HEADER', 'endpointConfiguration': {'types': ['EDGE']}, 'disableExecuteApiEndpoint': False, 'rootResourceId': 'efg567'} AWS CLI aws apigateway create-rest-api --name 'Simple PetStore (AWS CLI)' --region us- west-2 The following is the output of this command: Tutorial: Create a REST API using AWS SDKs or the AWS CLI 208 Amazon API Gateway Developer Guide { "id": "abcd1234", "name": "Simple PetStore (AWS CLI)", "createdDate": "2022-12-15T08:07:04-08:00", "apiKeySource": "HEADER", "endpointConfiguration": { "types": [ "EDGE" ] }, "disableExecuteApiEndpoint": false, "rootResourceId": "efg567" } The API you created has an API ID of abcd1234 and a root resource ID of efg567. You use these values in the set up of your API. 2. Next, you append a child resource under the root, you specify the RootResourceId as the parentId property value. Use the following example to create a /pets resource for your API: JavaScript v3 import {APIGatewayClient, CreateResourceCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new CreateResourceCommand({ restApiId: 'abcd1234', parentId: 'efg567', pathPart: 'pets' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The '/pets' resource setup failed:\n", err) } })(); A successful call returns information about your resource in an output like the following: Tutorial: Create a REST API using AWS SDKs or the AWS CLI 209 Amazon API Gateway Developer Guide { "path": "/pets", "pathPart": "pets", "id": "aaa111", "parentId": "efg567'" } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.create_resource( restApiId='abcd1234', parentId='efg567', pathPart='pets' ) except botocore.exceptions.ClientError as error: logger.exception("The '/pets' resource setup failed: %s.", error) raise attribute=["id","parentId", "pathPart", "path",] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns information about your resource in an output like the following: {'id': 'aaa111', 'parentId': 'efg567', 'pathPart': 'pets', 'path': '/pets'} AWS CLI aws apigateway create-resource --rest-api-id abcd1234 \ --region us-west-2 \ --parent-id efg567 \ --path-part pets Tutorial: Create a REST API using AWS SDKs or the AWS CLI 210 Amazon API Gateway Developer Guide The following is the output of this command: { "id": "aaa111", "parentId": "efg567", "pathPart": "pets", "path": "/pets" } The /pets resource you created has a resource ID of aaa111. You use this value in the set up of your API. 3. Next, you append a child resource under the /pets resource. This
apigateway-dg-057
apigateway-dg.pdf
57
in an output like the following: {'id': 'aaa111', 'parentId': 'efg567', 'pathPart': 'pets', 'path': '/pets'} AWS CLI aws apigateway create-resource --rest-api-id abcd1234 \ --region us-west-2 \ --parent-id efg567 \ --path-part pets Tutorial: Create a REST API using AWS SDKs or the AWS CLI 210 Amazon API Gateway Developer Guide The following is the output of this command: { "id": "aaa111", "parentId": "efg567", "pathPart": "pets", "path": "/pets" } The /pets resource you created has a resource ID of aaa111. You use this value in the set up of your API. 3. Next, you append a child resource under the /pets resource. This resource, /{petId} has a path parameter for the {petId}.To make a path part a path parameter, enclose it in a pair of curly brackets, { }. Use the following example to create a /pets/{petId} resource for your API: JavaScript v3 import {APIGatewayClient, CreateResourceCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new CreateResourceCommand({ restApiId: 'abcd1234', parentId: 'aaa111', pathPart: '{petId}' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The '/pets/{petId}' resource setup failed:\n", err) } })(); A successful call returns information about your resource in an output like the following: { "path": "/pets/{petId}", Tutorial: Create a REST API using AWS SDKs or the AWS CLI 211 Amazon API Gateway Developer Guide "pathPart": "{petId}", "id": "bbb222", "parentId": "aaa111'" } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.create_resource( restApiId='abcd1234', parentId='aaa111', pathPart='{petId}' ) except botocore.exceptions.ClientError as error: logger.exception("The '/pets/{petId}' resource setup failed: %s.", error) raise attribute=["id","parentId", "pathPart", "path",] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns information about your resource in an output like the following: {'id': 'bbb222', 'parentId': 'aaa111', 'pathPart': '{petId}', 'path': '/pets/ {petId}'} AWS CLI aws apigateway create-resource --rest-api-id abcd1234 \ --region us-west-2 \ --parent-id aaa111 \ --path-part '{petId}' The following is the output of this command: Tutorial: Create a REST API using AWS SDKs or the AWS CLI 212 Amazon API Gateway Developer Guide { "id": "bbb222", "parentId": "aaa111", "path": "/pets/{petId}", "pathPart": "{petId}" } The /pets/{petId} resource you created has a resource ID of bbb222. You use this value in the set up of your API. 4. In the following two steps, you add HTTP methods to your resources. In this tutorial, you set the methods to have open access by setting the authorization-type to set to NONE. To permit only authenticated users to call the method, you can use IAM roles and policies, a Lambda authorizer (formerly known as a custom authorizer), or an Amazon Cognito user pool. For more information, see the section called “Access control”. Use the following example to add the GET HTTP method on the /pets resource: JavaScript v3 import {APIGatewayClient, PutMethodCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutMethodCommand({ restApiId: 'abcd1234', resourceId: 'aaa111', httpMethod: 'GET', authorizationType: 'NONE' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The 'GET /pets' method setup failed:\n", err) } })(); A successful call returns the following output: Tutorial: Create a REST API using AWS SDKs or the AWS CLI 213 Amazon API Gateway Developer Guide { "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE" } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_method( restApiId='abcd1234', resourceId='aaa111', httpMethod='GET', authorizationType='NONE' ) except botocore.exceptions.ClientError as error: logger.exception("The 'GET /pets' method setup failed: %s", error) raise attribute=["httpMethod","authorizationType","apiKeyRequired"] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns the following output: {'httpMethod': 'GET', 'authorizationType': 'NONE', 'apiKeyRequired': False} AWS CLI aws apigateway put-method --rest-api-id abcd1234 \ --resource-id aaa111 \ --http-method GET \ --authorization-type "NONE" \ --region us-west-2 Tutorial: Create a REST API using AWS SDKs or the AWS CLI 214 Amazon API Gateway Developer Guide The following is the output of this command: { "httpMethod": "GET", "authorizationType": "NONE", "apiKeyRequired": false } 5. Use the following example to add the GET HTTP method on the /pets/{petId} resource and to set the requestParameters property to pass the client-supplied petId value to the backend: JavaScript v3 import {APIGatewayClient, PutMethodCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutMethodCommand({ restApiId: 'abcd1234', resourceId: 'bbb222', httpMethod: 'GET', authorizationType: 'NONE' requestParameters: { "method.request.path.petId" : true } }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The 'GET /pets/{petId}' method setup failed:\n", err) } })(); A successful call returns the following output: { "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE", Tutorial: Create a REST API using AWS SDKs or the AWS CLI 215 Amazon API Gateway Developer Guide "requestParameters": { "method.request.path.petId": true } } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_method( restApiId='abcd1234', resourceId='bbb222', httpMethod='GET', authorizationType='NONE', requestParameters={ "method.request.path.petId": True }
apigateway-dg-058
apigateway-dg.pdf
58
PutMethodCommand({ restApiId: 'abcd1234', resourceId: 'bbb222', httpMethod: 'GET', authorizationType: 'NONE' requestParameters: { "method.request.path.petId" : true } }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The 'GET /pets/{petId}' method setup failed:\n", err) } })(); A successful call returns the following output: { "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE", Tutorial: Create a REST API using AWS SDKs or the AWS CLI 215 Amazon API Gateway Developer Guide "requestParameters": { "method.request.path.petId": true } } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_method( restApiId='abcd1234', resourceId='bbb222', httpMethod='GET', authorizationType='NONE', requestParameters={ "method.request.path.petId": True } ) except botocore.exceptions.ClientError as error: logger.exception("The 'GET /pets/{petId}' method setup failed: %s", error) raise attribute=["httpMethod","authorizationType","apiKeyRequired", "requestParameters" ] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns the following output: {'httpMethod': 'GET', 'authorizationType': 'NONE', 'apiKeyRequired': False, 'requestParameters': {'method.request.path.petId': True}} AWS CLI aws apigateway put-method --rest-api-id abcd1234 \ --resource-id bbb222 --http-method GET \ --authorization-type "NONE" \ Tutorial: Create a REST API using AWS SDKs or the AWS CLI 216 Amazon API Gateway Developer Guide --region us-west-2 \ --request-parameters method.request.path.petId=true The following is the output of this command: { "httpMethod": "GET", "authorizationType": "NONE", "apiKeyRequired": false, "requestParameters": { "method.request.path.petId": true } } 6. Use the following example to add the 200 OK method response for the GET /pets method: JavaScript v3 import {APIGatewayClient, PutMethodResponseCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutMethodResponseCommand({ restApiId: 'abcd1234', resourceId: 'aaa111', httpMethod: 'GET', statusCode: '200' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("Set up the 200 OK response for the 'GET /pets' method failed: \n", err) } })(); A successful call returns the following output: { "statusCode": "200" } Tutorial: Create a REST API using AWS SDKs or the AWS CLI 217 Developer Guide Amazon API Gateway Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_method_response( restApiId='abcd1234', resourceId='aaa111', httpMethod='GET', statusCode='200' ) except botocore.exceptions.ClientError as error: logger.exception("Set up the 200 OK response for the 'GET /pets' method failed %s.", error) raise attribute=["statusCode"] filtered_result ={key:result[key] for key in attribute} logger.info(filtered_result) A successful call returns the following output: {'statusCode': '200'} AWS CLI aws apigateway put-method-response --rest-api-id abcd1234 \ --resource-id aaa111 --http-method GET \ --status-code 200 --region us-west-2 The following is the output of this command: { "statusCode": "200" } Tutorial: Create a REST API using AWS SDKs or the AWS CLI 218 Amazon API Gateway Developer Guide 7. Use the following example to add the 200 OK method response for the GET /pets/{petId} method: JavaScript v3 import {APIGatewayClient, PutMethodResponseCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutMethodResponseCommand({ restApiId: 'abcd1234', resourceId: 'bbb222', httpMethod: 'GET', statusCode: '200' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("Set up the 200 OK response for the 'GET /pets/{petId}' method failed:\n", err) } })(); A successful call returns the following output: { "statusCode": "200" } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_method_response( restApiId='abcd1234', Tutorial: Create a REST API using AWS SDKs or the AWS CLI 219 Amazon API Gateway Developer Guide resourceId='bbb222', httpMethod='GET', statusCode='200' ) except botocore.exceptions.ClientError as error: logger.exception("Set up the 200 OK response for the 'GET /pets/{petId}' method failed %s.", error) raise attribute=["statusCode"] filtered_result ={key:result[key] for key in attribute} logger.info(filtered_result) A successful call returns the following output: {'statusCode': '200'} AWS CLI aws apigateway put-method-response --rest-api-id abcd1234 \ --resource-id bbb222 --http-method GET \ --status-code 200 --region us-west-2 The following is the output of this command: { "statusCode": "200" } 8. Use the following example to configure an integration for the GET /pets method with an HTTP endpoint. The HTTP endpoint is http://petstore-demo-endpoint.execute- api.com/petstore/pets. JavaScript v3 import {APIGatewayClient, PutIntegrationCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutIntegrationCommand({ restApiId: 'abcd1234', resourceId: 'aaa111', Tutorial: Create a REST API using AWS SDKs or the AWS CLI 220 Amazon API Gateway Developer Guide httpMethod: 'GET', type: 'HTTP', integrationHttpMethod: 'GET', uri: 'http://petstore-demo-endpoint.execute-api.com/petstore/pets' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("Set up the integration of the 'GET /pets' method of the API failed:\n", err) } })(); A successful call returns the following output: { "httpMethod": "GET", "passthroughBehavior": "WHEN_NO_MATCH", "cacheKeyParameters": [], "type": "HTTP", "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "cacheNamespace": "ccc333" } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_integration( restApiId='abcd1234', resourceId='aaa111', httpMethod='GET', type='HTTP', integrationHttpMethod='GET', uri='http://petstore-demo-endpoint.execute-api.com/petstore/pets' Tutorial: Create a REST API using AWS SDKs or the AWS CLI 221 Amazon API Gateway ) Developer Guide except botocore.exceptions.ClientError as error: logger.exception("Set up the integration of the 'GET /' method of the API failed %s.", error) raise attribute=["httpMethod","passthroughBehavior","cacheKeyParameters", "type", "uri", "cacheNamespace"] filtered_result ={key:result[key] for key in attribute} print(filtered_result)
apigateway-dg-059
apigateway-dg.pdf
59
the API failed:\n", err) } })(); A successful call returns the following output: { "httpMethod": "GET", "passthroughBehavior": "WHEN_NO_MATCH", "cacheKeyParameters": [], "type": "HTTP", "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "cacheNamespace": "ccc333" } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_integration( restApiId='abcd1234', resourceId='aaa111', httpMethod='GET', type='HTTP', integrationHttpMethod='GET', uri='http://petstore-demo-endpoint.execute-api.com/petstore/pets' Tutorial: Create a REST API using AWS SDKs or the AWS CLI 221 Amazon API Gateway ) Developer Guide except botocore.exceptions.ClientError as error: logger.exception("Set up the integration of the 'GET /' method of the API failed %s.", error) raise attribute=["httpMethod","passthroughBehavior","cacheKeyParameters", "type", "uri", "cacheNamespace"] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns the following output: {'httpMethod': 'GET', 'passthroughBehavior': 'WHEN_NO_MATCH', 'cacheKeyParameters': [], 'type': 'HTTP', 'uri': 'http://petstore-demo- endpoint.execute-api.com/petstore/pets', 'cacheNamespace': 'ccc333'} AWS CLI aws apigateway put-integration --rest-api-id abcd1234 \ --resource-id aaa111 --http-method GET --type HTTP \ --integration-http-method GET \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets' \ --region us-west-2 The following is the output of this command: { "type": "HTTP", "httpMethod": "GET", "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "connectionType": "INTERNET", "passthroughBehavior": "WHEN_NO_MATCH", "timeoutInMillis": 29000, "cacheNamespace": "6sxz2j", "cacheKeyParameters": [] } 9. Use the following example to configure an integration for the GET /pets/{petId} method with an HTTP endpoint. The HTTP endpoint is http://petstore-demo- endpoint.execute-api.com/petstore/pets/{id}. In this step, you map the path parameter petId to the integration endpoint path parameter of id. Tutorial: Create a REST API using AWS SDKs or the AWS CLI 222 Amazon API Gateway JavaScript v3 Developer Guide import {APIGatewayClient, PutIntegrationCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutIntegrationCommand({ restApiId: 'abcd1234', resourceId: 'bbb222', httpMethod: 'GET', type: 'HTTP', integrationHttpMethod: 'GET', uri: 'http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}' requestParameters: { "integration.request.path.id": "method.request.path.petId" } }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("Set up the integration of the 'GET /pets/{petId}' method of the API failed:\n", err) } })(); A successful call returns the following output: { "httpMethod": "GET", "passthroughBehavior": "WHEN_NO_MATCH", "cacheKeyParameters": [], "type": "HTTP", "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}", "cacheNamespace": "ddd444", "requestParameters": { "integration.request.path.id": "method.request.path.petId" } } Tutorial: Create a REST API using AWS SDKs or the AWS CLI 223 Developer Guide Amazon API Gateway Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_integration( restApiId='ieps9b05sf', resourceId='t8zeb4', httpMethod='GET', type='HTTP', integrationHttpMethod='GET', uri='http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}', requestParameters={ "integration.request.path.id": "method.request.path.petId" } ) except botocore.exceptions.ClientError as error: logger.exception("Set up the integration of the 'GET /pets/{petId}' method of the API failed %s.", error) raise attribute=["httpMethod","passthroughBehavior","cacheKeyParameters", "type", "uri", "cacheNamespace", "requestParameters"] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns the following output: {'httpMethod': 'GET', 'passthroughBehavior': 'WHEN_NO_MATCH', 'cacheKeyParameters': [], 'type': 'HTTP', 'uri': 'http://petstore- demo-endpoint.execute-api.com/petstore/pets/{id}', 'cacheNamespace': 'ddd444', 'requestParameters': {'integration.request.path.id': 'method.request.path.petId'}}} AWS CLI aws apigateway put-integration --rest-api-id abcd1234 \ Tutorial: Create a REST API using AWS SDKs or the AWS CLI 224 Amazon API Gateway Developer Guide --resource-id bbb222 --http-method GET --type HTTP \ --integration-http-method GET \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}' \ --request-parameters '{"integration.request.path.id":"method.request.path.petId"}' \ --region us-west-2 The following is the output of this command: { "type": "HTTP", "httpMethod": "GET", "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}", "connectionType": "INTERNET", "requestParameters": { "integration.request.path.id": "method.request.path.petId" }, "passthroughBehavior": "WHEN_NO_MATCH", "timeoutInMillis": 29000, "cacheNamespace": "rjkmth", "cacheKeyParameters": [] } 10. Use the following example to add the integration response for the GET /pets integration: JavaScript v3 import {APIGatewayClient, PutIntegrationResponseCommand } from "@aws-sdk/ client-api-gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutIntegrationResponseCommand({ restApiId: 'abcd1234', resourceId: 'aaa111', httpMethod: 'GET', statusCode: '200', selectionPattern: '' }); try { const results = await apig.send(command) console.log(results) } catch (err) { Tutorial: Create a REST API using AWS SDKs or the AWS CLI 225 Amazon API Gateway Developer Guide console.log("The 'GET /pets' method integration response setup failed:\n", err) } })(); A successful call returns the following output: { "selectionPattern": "", "statusCode": "200" } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_integration_response( restApiId='abcd1234', resourceId='aaa111', httpMethod='GET', statusCode='200', selectionPattern='', ) except botocore.exceptions.ClientError as error: logger.exception("Set up the integration response of the 'GET /pets' method of the API failed: %s", error) raise attribute=["selectionPattern","statusCode"] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns the following output: {'selectionPattern': "", 'statusCode': '200'} Tutorial: Create a REST API using AWS SDKs or the AWS CLI 226 Amazon API Gateway AWS CLI Developer Guide aws apigateway put-integration-response --rest-api-id abcd1234 \ --resource-id aaa111 --http-method GET \ --status-code 200 --selection-pattern "" \ --region us-west-2 The following is the output of this command: { "statusCode": "200", "selectionPattern": "" } 11. Use the following example to add the integration response for the GET /pets/{petId} integration: JavaScript v3 import {APIGatewayClient, PutIntegrationResponseCommand } from "@aws-sdk/ client-api-gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutIntegrationResponseCommand({ restApiId: 'abcd1234', resourceId: 'bbb222', httpMethod: 'GET', statusCode: '200', selectionPattern: '' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The 'GET /pets/{petId}' method integration response setup failed:\n", err) } })(); A successful call returns the following output: Tutorial: Create a REST API using AWS
apigateway-dg-060
apigateway-dg.pdf
60
us-west-2 The following is the output of this command: { "statusCode": "200", "selectionPattern": "" } 11. Use the following example to add the integration response for the GET /pets/{petId} integration: JavaScript v3 import {APIGatewayClient, PutIntegrationResponseCommand } from "@aws-sdk/ client-api-gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutIntegrationResponseCommand({ restApiId: 'abcd1234', resourceId: 'bbb222', httpMethod: 'GET', statusCode: '200', selectionPattern: '' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The 'GET /pets/{petId}' method integration response setup failed:\n", err) } })(); A successful call returns the following output: Tutorial: Create a REST API using AWS SDKs or the AWS CLI 227 Amazon API Gateway Developer Guide { "selectionPattern": "", "statusCode": "200" } Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_integration_response( restApiId='abcd1234', resourceId='bbb222', httpMethod='GET', statusCode='200', selectionPattern='', ) except botocore.exceptions.ClientError as error: logger.exception("Set up the integration response of the 'GET /pets/{petId}' method of the API failed: %s", error) raise attribute=["selectionPattern","statusCode"] filtered_result ={key:result[key] for key in attribute} print(filtered_result) A successful call returns the following output: {'selectionPattern': "", 'statusCode': '200'} AWS CLI aws apigateway put-integration-response --rest-api-id abcd1234 \ --resource-id bbb222 --http-method GET --status-code 200 --selection-pattern "" --region us-west-2 Tutorial: Create a REST API using AWS SDKs or the AWS CLI 228 Amazon API Gateway Developer Guide The following is the output of this command: { "statusCode": "200", "selectionPattern": "" } After you create the integration response, your API can query available pets on the PetStore website and to view an individual pet of a specified identifier. Before your API is callable by your customers, you must deploy it. We recommend that before you deploy your API, you test it. 12. Use the following example to test the GET /pets method: JavaScript v3 import {APIGatewayClient, TestInvokeMethodCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new TestInvokeMethodCommand({ restApiId: 'abcd1234', resourceId: 'aaa111', httpMethod: 'GET', pathWithQueryString: '/', }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The test on 'GET /pets' method failed:\n", err) } })(); Python import botocore import boto3 import logging Tutorial: Create a REST API using AWS SDKs or the AWS CLI 229 Amazon API Gateway Developer Guide logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.test_invoke_method( restApiId='abcd1234', resourceId='aaa111', httpMethod='GET', pathWithQueryString='/', ) except botocore.exceptions.ClientError as error: logger.exception("Test invoke method on 'GET /pets' failed: %s", error) raise print(result) AWS CLI aws apigateway test-invoke-method --rest-api-id abcd1234 / --resource-id aaa111 / --http-method GET / --path-with-query-string '/' 13. Use the following example to test the GET /pets/{petId} method with a petId of 3: JavaScript v3 import {APIGatewayClient, TestInvokeMethodCommand } from "@aws-sdk/client-api- gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new TestInvokeMethodCommand({ restApiId: 'abcd1234', resourceId: 'bbb222', httpMethod: 'GET', pathWithQueryString: '/pets/3', }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The test on 'GET /pets/{petId}' method failed:\n", err) } Tutorial: Create a REST API using AWS SDKs or the AWS CLI 230 Developer Guide Amazon API Gateway })(); Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.test_invoke_method( restApiId='abcd1234', resourceId='bbb222', httpMethod='GET', pathWithQueryString='/pets/3', ) except botocore.exceptions.ClientError as error: logger.exception("Test invoke method on 'GET /pets/{petId}' failed: %s", error) raise print(result) AWS CLI aws apigateway test-invoke-method --rest-api-id abcd1234 / --resource-id bbb222 / --http-method GET / --path-with-query-string '/pets/3' After you successfully test your API, you can deploy it to a stage. 14. Use the following example to deploy your API to a stage named test. When you deploy your API to a stage, API callers can invoke your API. JavaScript v3 import {APIGatewayClient, CreateDeploymentCommand } from "@aws-sdk/client-api- gateway"; (async function (){ Tutorial: Create a REST API using AWS SDKs or the AWS CLI 231 Amazon API Gateway Developer Guide const apig = new APIGatewayClient({region:"us-east-1"}); const command = new CreateDeploymentCommand({ restApiId: 'abcd1234', stageName: 'test', stageDescription: 'test deployment' }); try { const results = await apig.send(command) console.log("Deploying API succeeded\n", results) } catch (err) { console.log("Deploying API failed:\n", err) } })(); Python import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.create_deployment( restApiId='ieps9b05sf', stageName='test', stageDescription='my test stage', ) except botocore.exceptions.ClientError as error: logger.exception("Error deploying stage %s.", error) raise print('Deploying API succeeded') print(result) AWS CLI aws apigateway create-deployment --rest-api-id abcd1234 \ --region us-west-2 \ --stage-name test \ --stage-description 'Test stage' \ --description 'First deployment' Tutorial: Create a REST API using AWS SDKs or the AWS CLI 232 Amazon API Gateway Developer Guide The following is the output of this command: { "id": "ab1c1d", "description": "First deployment", "createdDate": "2022-12-15T08:44:13-08:00" } Your API is now callable by customers. You can test this API by entering the https:// abcd1234.execute-api.us-west-2.amazonaws.com/test/pets URL in a browser, and substituting abcd1234 with the identifier of your API. For more examples of how to create or update an API using AWS
apigateway-dg-061
apigateway-dg.pdf
61
print(result) AWS CLI aws apigateway create-deployment --rest-api-id abcd1234 \ --region us-west-2 \ --stage-name test \ --stage-description 'Test stage' \ --description 'First deployment' Tutorial: Create a REST API using AWS SDKs or the AWS CLI 232 Amazon API Gateway Developer Guide The following is the output of this command: { "id": "ab1c1d", "description": "First deployment", "createdDate": "2022-12-15T08:44:13-08:00" } Your API is now callable by customers. You can test this API by entering the https:// abcd1234.execute-api.us-west-2.amazonaws.com/test/pets URL in a browser, and substituting abcd1234 with the identifier of your API. For more examples of how to create or update an API using AWS SDKs or the AWS CLI, see Actions for API Gateway using AWS SDKs. Automate the setup of your API Instead of creating your API step-by-step, you can automate the creation and cleanup of AWS resources by using OpenAPI, AWS CloudFormation, or Terraform to create your API. OpenAPI 3.0 definition You can import an OpenAPI defintion into API Gateway. For more information, see the section called “OpenAPI”. { "openapi" : "3.0.1", "info" : { "title" : "Simple PetStore (OpenAPI)", "description" : "Demo API created using OpenAPI", "version" : "2024-05-24T20:39:34Z" }, "servers" : [ { "url" : "{basePath}", "variables" : { "basePath" : { "default" : "Prod" } } } ], Tutorial: Create a REST API using AWS SDKs or the AWS CLI 233 Developer Guide Amazon API Gateway "paths" : { "/pets" : { "get" : { "responses" : { "200" : { "description" : "200 response", "content" : { } } }, "x-amazon-apigateway-integration" : { "type" : "http", "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "200" } }, "passthroughBehavior" : "when_no_match", "timeoutInMillis" : 29000 } } }, "/pets/{petId}" : { "get" : { "parameters" : [ { "name" : "petId", "in" : "path", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response", "content" : { } } }, "x-amazon-apigateway-integration" : { "type" : "http", "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}", "responses" : { Tutorial: Create a REST API using AWS SDKs or the AWS CLI 234 Amazon API Gateway Developer Guide "default" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.path.id" : "method.request.path.petId" }, "passthroughBehavior" : "when_no_match", "timeoutInMillis" : 29000 } } } }, "components" : { } } AWS CloudFormation template To deploy your AWS CloudFormation template, see Creating a stack on the AWS CloudFormation console. AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Name: Simple PetStore (AWS CloudFormation) PetsResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'pets' PetIdResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !Ref PetsResource PathPart: '{petId}' PetsMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api Tutorial: Create a REST API using AWS SDKs or the AWS CLI 235 Amazon API Gateway Developer Guide ResourceId: !Ref PetsResource HttpMethod: GET AuthorizationType: NONE Integration: Type: HTTP IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ IntegrationResponses: - StatusCode: '200' MethodResponses: - StatusCode: '200' PetIdMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref PetIdResource HttpMethod: GET AuthorizationType: NONE RequestParameters: method.request.path.petId: true Integration: Type: HTTP IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id} RequestParameters: integration.request.path.id: method.request.path.petId IntegrationResponses: - StatusCode: '200' MethodResponses: - StatusCode: '200' ApiDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: - PetsMethodGet Properties: RestApiId: !Ref Api StageName: Prod Outputs: ApiRootUrl: Description: Root Url of the API Value: !Sub 'https://${Api}.execute-api.${AWS::Region}.amazonaws.com/Prod' Tutorial: Create a REST API using AWS SDKs or the AWS CLI 236 Amazon API Gateway Terraform configuration For more information about Terraform, see Terraform. Developer Guide provider "aws" { region = "us-east-1" # Update with your desired region } resource "aws_api_gateway_rest_api" "Api" { name = "Simple PetStore (Terraform)" description = "Demo API created using Terraform" } resource "aws_api_gateway_resource" "petsResource"{ rest_api_id = aws_api_gateway_rest_api.Api.id parent_id = aws_api_gateway_rest_api.Api.root_resource_id path_part = "pets" } resource "aws_api_gateway_resource" "petIdResource"{ rest_api_id = aws_api_gateway_rest_api.Api.id parent_id = aws_api_gateway_resource.petsResource.id path_part = "{petId}" } resource "aws_api_gateway_method" "petsMethodGet" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petsResource.id http_method = "GET" authorization = "NONE" } resource "aws_api_gateway_method_response" "petsMethodResponseGet" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petsResource.id http_method = aws_api_gateway_method.petsMethodGet.http_method status_code ="200" } resource "aws_api_gateway_integration" "petsIntegration" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petsResource.id http_method = aws_api_gateway_method.petsMethodGet.http_method type = "HTTP" uri = "http://petstore-demo-endpoint.execute-api.com/petstore/ pets" Tutorial: Create a REST API using AWS SDKs or the AWS CLI 237 Amazon API Gateway Developer Guide integration_http_method = "GET" depends_on = [aws_api_gateway_method.petsMethodGet] } resource "aws_api_gateway_integration_response" "petsIntegrationResponse" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petsResource.id http_method = aws_api_gateway_method.petsMethodGet.http_method status_code = aws_api_gateway_method_response.petsMethodResponseGet.status_code } resource "aws_api_gateway_method" "petIdMethodGet" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petIdResource.id http_method = "GET" authorization = "NONE" request_parameters = {"method.request.path.petId" = true} } resource "aws_api_gateway_method_response" "petIdMethodResponseGet" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petIdResource.id http_method = aws_api_gateway_method.petIdMethodGet.http_method status_code ="200" } resource "aws_api_gateway_integration" "petIdIntegration" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petIdResource.id http_method = aws_api_gateway_method.petIdMethodGet.http_method type = "HTTP" uri = "http://petstore-demo-endpoint.execute-api.com/petstore/ pets/{id}" integration_http_method = "GET" request_parameters = {"integration.request.path.id" = "method.request.path.petId"} depends_on = [aws_api_gateway_method.petIdMethodGet] } resource "aws_api_gateway_integration_response"
apigateway-dg-062
apigateway-dg.pdf
62
API Gateway Developer Guide integration_http_method = "GET" depends_on = [aws_api_gateway_method.petsMethodGet] } resource "aws_api_gateway_integration_response" "petsIntegrationResponse" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petsResource.id http_method = aws_api_gateway_method.petsMethodGet.http_method status_code = aws_api_gateway_method_response.petsMethodResponseGet.status_code } resource "aws_api_gateway_method" "petIdMethodGet" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petIdResource.id http_method = "GET" authorization = "NONE" request_parameters = {"method.request.path.petId" = true} } resource "aws_api_gateway_method_response" "petIdMethodResponseGet" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petIdResource.id http_method = aws_api_gateway_method.petIdMethodGet.http_method status_code ="200" } resource "aws_api_gateway_integration" "petIdIntegration" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petIdResource.id http_method = aws_api_gateway_method.petIdMethodGet.http_method type = "HTTP" uri = "http://petstore-demo-endpoint.execute-api.com/petstore/ pets/{id}" integration_http_method = "GET" request_parameters = {"integration.request.path.id" = "method.request.path.petId"} depends_on = [aws_api_gateway_method.petIdMethodGet] } resource "aws_api_gateway_integration_response" "petIdIntegrationResponse" { rest_api_id = aws_api_gateway_rest_api.Api.id resource_id = aws_api_gateway_resource.petIdResource.id http_method = aws_api_gateway_method.petIdMethodGet.http_method status_code = aws_api_gateway_method_response.petIdMethodResponseGet.status_code Tutorial: Create a REST API using AWS SDKs or the AWS CLI 238 Amazon API Gateway } Developer Guide resource "aws_api_gateway_deployment" "Deployment" { rest_api_id = aws_api_gateway_rest_api.Api.id depends_on = [aws_api_gateway_integration.petsIntegration,aws_api_gateway_integration.petIdIntegration ] } resource "aws_api_gateway_stage" "Stage" { stage_name = "Prod" rest_api_id = aws_api_gateway_rest_api.Api.id deployment_id = aws_api_gateway_deployment.Deployment.id } Tutorial: Create a private REST API In this tutorial, you create a private REST API. Clients can access the API only from within your Amazon VPC. The API is isolated from the public internet, which is a common security requirement. This tutorial takes approximately 30 minutes to complete. First, you use an AWS CloudFormation template to create an Amazon VPC, a VPC endpoint, an AWS Lambda function, and launch an Amazon EC2 instance that you'll use to test your API. Next, you use the AWS Management Console to create a private API and attach a resource policy that allows access only from your VPC endpoint. Lastly, you test your API. To complete this tutorial, you need an AWS account and an AWS Identity and Access Management user with console access. For more information, see Prerequisites. In this tutorial, you use the AWS Management Console. For an AWS CloudFormation template that creates this API and all related resources, see template.yaml. Topics Tutorial: Create a private REST API 239 Developer Guide Amazon API Gateway • Step 1: Create dependencies • Step 2: Create a private API • Step 3: Create a method and integration • Step 4: Attach a resource policy • Step 5: Deploy your API • Step 6: Verify that your API isn't publicly accessible • Step 7: Connect to an instance in your VPC and invoke your API • Step 8: Clean up • Next steps: Automate with AWS CloudFormation Step 1: Create dependencies Download and unzip this AWS CloudFormation template. You use the template to create all of the dependencies for your private API, including an Amazon VPC, a VPC endpoint, and a Lambda function that serves as the backend of your API. You create the private API later. To create an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Choose Create stack and then choose With new resources (standard). 3. 4. For Specify template, choose Upload a template file. Select the template that you downloaded. 5. Choose Next. 6. 7. 8. For Stack name, enter private-api-tutorial and then choose Next. For Configure stack options, choose Next. For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account. 9. Choose Submit. AWS CloudFormation provisions the dependencies for your API, which can take a few minutes. When the status of your AWS CloudFormation stack is CREATE_COMPLETE, choose Outputs. Note your VPC endpoint ID. You need it for later steps in this tutorial. Tutorial: Create a private REST API 240 Amazon API Gateway Developer Guide Step 2: Create a private API You create a private API to allow only clients within your VPC to access it. To create a private API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API, and then for REST API, choose Build. 3. 4. 5. For API name, enter private-api-tutorial. For API endpoint type, select Private. For VPC endpoint IDs, enter the VPC endpoint ID from the Outputs of your AWS CloudFormation stack. 6. For IP address type, choose Dualstack. 7. Choose Create API. Step 3: Create a method and integration You create a GET method and Lambda integration to handle GET requests to your API. When a client invokes your API, API Gateway sends the request to the Lambda function that you created in Step 1, and then returns a response to the client. To create a method and integration 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Create method. 4. 5. 6. 7. For Method type select GET. For Integration type, select Lambda function. Turn on Lambda proxy integration. With a Lambda proxy integration, API Gateway sends an event to Lambda with a defined structure, and transforms the response from your Lambda function to an HTTP response. For Lambda function, choose the function that you
apigateway-dg-063
apigateway-dg.pdf
63
the request to the Lambda function that you created in Step 1, and then returns a response to the client. To create a method and integration 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Create method. 4. 5. 6. 7. For Method type select GET. For Integration type, select Lambda function. Turn on Lambda proxy integration. With a Lambda proxy integration, API Gateway sends an event to Lambda with a defined structure, and transforms the response from your Lambda function to an HTTP response. For Lambda function, choose the function that you created with the AWS CloudFormation template in Step 1. The function's name begins with private-api-tutorial. 8. Choose Create method. Tutorial: Create a private REST API 241 Amazon API Gateway Developer Guide Step 4: Attach a resource policy You attach a resource policy to your API that allows clients to invoke your API only through your VPC endpoint. To further restrict access to your API, you can also configure a VPC endpoint policy for your VPC endpoint, but that's not necessary for this tutorial. To attach a resource policy 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Resource policy, and then choose Create policy. 4. Enter the following policy. Replace vpceID with your VPC endpoint ID from the Outputs of your AWS CloudFormation stack. { "Version": "2012-10-17", "Statement": [ { "Effect": "Deny", "Principal": "*", "Action": "execute-api:Invoke", "Resource": "execute-api:/*", "Condition": { "StringNotEquals": { "aws:sourceVpce": "vpceID" } } }, { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": "execute-api:/*" } ] } 5. Choose Save changes. Tutorial: Create a private REST API 242 Amazon API Gateway Step 5: Deploy your API Developer Guide Next, you deploy your API to make it available to clients in your Amazon VPC. To deploy an API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Deploy API. 4. 5. 6. For Stage, select New stage. For Stage name, enter test. (Optional) For Description, enter a description. 7. Choose Deploy. Now you're ready to test your API. Step 6: Verify that your API isn't publicly accessible Use curl to verify that you can't invoke your API from outside of your Amazon VPC. To test your API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. In the main navigation pane, choose Stages, and then choose the test stage. 4. Under Stage details, choose the copy icon to copy your API's invoke URL. The URL looks like https://abcdef123.execute-api.us-west-2.amazonaws.com/test. The VPC endpoint that you created in Step 1 has private DNS enabled, so you can use the provided URL to invoke your API. 5. Use curl to attempt to invoke your API from outside of your VPC. curl https://abcdef123.execute-api.us-west-2.amazonaws.com/test Curl indicates that your API's endpoint can't be resolved. If you get a different response, go back to Step 2, and make sure that you choose Private for your API's endpoint type. Tutorial: Create a private REST API 243 Amazon API Gateway Developer Guide curl: (6) Could not resolve host: abcdef123.execute-api.us-west-2.amazonaws.com/ test Next, you connect to an Amazon EC2 instance in your VPC to invoke your API. Step 7: Connect to an instance in your VPC and invoke your API Next, you test your API from within your Amazon VPC. To access your private API, you connect to an Amazon EC2 instance in your VPC and then use curl to invoke your API. You use Systems Manager Session Manager to connect to your instance in the browser. To test your API 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. Choose Instances. 3. Choose the instance named private-api-tutorial that you created with the AWS CloudFormation template in Step 1. 4. Choose Connect and then choose Session Manager. 5. Choose Connect to launch a browser-based session to your instance. 6. In your Session Manager session, use curl to invoke your API. You can invoke your API because you're using an instance in your Amazon VPC. curl https://abcdef123.execute-api.us-west-2.amazonaws.com/test Verify that you get the response Hello from Lambda!. Tutorial: Create a private REST API 244 Amazon API Gateway Developer Guide You successfully created an API that's accessible only from within your Amazon VPC and then verified that it works. Step 8: Clean up To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following steps delete your REST API and your AWS CloudFormation stack. To delete a REST API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. On the APIs page, select an API. Choose API actions, choose Delete API, and then confirm your choice. To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack.
apigateway-dg-064
apigateway-dg.pdf
64
API that's accessible only from within your Amazon VPC and then verified that it works. Step 8: Clean up To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following steps delete your REST API and your AWS CloudFormation stack. To delete a REST API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. On the APIs page, select an API. Choose API actions, choose Delete API, and then confirm your choice. To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack. 3. Choose Delete and then confirm your choice. Next steps: Automate with AWS CloudFormation You can automate the creation and cleanup of all AWS resources involved in this tutorial. For a full example AWS CloudFormation template, see template.yaml. Amazon API Gateway HTTP API tutorials The following tutorials provide hands-on exercises to help you learn about API Gateway HTTP APIs. Topics • Tutorial: Create a CRUD HTTP API with Lambda and DynamoDB • Tutorial: Create an HTTP API with a private integration to an Amazon ECS service Tutorial: Create a CRUD HTTP API with Lambda and DynamoDB In this tutorial, you create a serverless API that creates, reads, updates, and deletes items from a DynamoDB table. DynamoDB is a fully managed NoSQL database service that provides fast and HTTP API tutorials 245 Amazon API Gateway Developer Guide predictable performance with seamless scalability. This tutorial takes approximately 30 minutes to complete, and you can do it within the AWS Free Tier. First, you create a DynamoDB table using the DynamoDB console. Then you create a Lambda function using the AWS Lambda console. Next, you create an HTTP API using the API Gateway console. Lastly, you test your API. When you invoke your HTTP API, API Gateway routes the request to your Lambda function. The Lambda function interacts with DynamoDB, and returns a response to API Gateway. API Gateway then returns a response to you. To complete this exercise, you need an AWS account and an AWS Identity and Access Management user with console access. For more information, see Prerequisites. In this tutorial, you use the AWS Management Console. For an AWS SAM template that creates this API and all related resources, see template.yaml. Topics • Step 1: Create a DynamoDB table • Step 2: Create a Lambda function • Step 3: Create an HTTP API • Step 4: Create routes • Step 5: Create an integration • Step 6: Attach your integration to routes • Step 7: Test your API • Step 8: Clean up • Next steps: Automate with AWS SAM or AWS CloudFormation Step 1: Create a DynamoDB table You use a DynamoDB table to store data for your API. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 246 Amazon API Gateway Developer Guide Each item has a unique ID, which we use as the partition key for the table. To create a DynamoDB table 1. Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/. 2. Choose Create table. 3. 4. For Table name, enter http-crud-tutorial-items. For Partition key, enter id. 5. Choose Create table. Step 2: Create a Lambda function You create a Lambda function for the backend of your API. This Lambda function creates, reads, updates, and deletes items from DynamoDB. The function uses events from API Gateway to determine how to interact with DynamoDB. For simplicity this tutorial uses a single Lambda function. As a best practice, you should create separate functions for each route. For more information, see The Lambda monolith. To create a Lambda function 1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda. 2. Choose Create function. 3. 4. For Function name, enter http-crud-tutorial-function. For Runtime, choose either the latest supported Node.js or Python runtime. 5. Under Permissions choose Change default execution role. 6. 7. 8. Select Create a new role from AWS policy templates. For Role name, enter http-crud-tutorial-role. For Policy templates, choose Simple microservice permissions. This policy grants the Lambda function permission to interact with DynamoDB. Note This tutorial uses a managed policy for simplicity. As a best practice, you should create your own IAM policy to grant the minimum permissions required. 9. Choose Create function. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 247 Amazon API Gateway Developer Guide 10. Open the Lambda function in the console's code editor, and replace its contents with the following code. Choose Deploy to update your function. Node.js import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, ScanCommand, PutCommand, GetCommand, DeleteCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const dynamo = DynamoDBDocumentClient.from(client); const tableName = "http-crud-tutorial-items"; export const handler = async (event, context) => { let body; let statusCode = 200; const headers = { "Content-Type": "application/json", }; try { switch (event.routeKey) {
apigateway-dg-065
apigateway-dg.pdf
65
Choose Create function. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 247 Amazon API Gateway Developer Guide 10. Open the Lambda function in the console's code editor, and replace its contents with the following code. Choose Deploy to update your function. Node.js import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, ScanCommand, PutCommand, GetCommand, DeleteCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const dynamo = DynamoDBDocumentClient.from(client); const tableName = "http-crud-tutorial-items"; export const handler = async (event, context) => { let body; let statusCode = 200; const headers = { "Content-Type": "application/json", }; try { switch (event.routeKey) { case "DELETE /items/{id}": await dynamo.send( new DeleteCommand({ TableName: tableName, Key: { id: event.pathParameters.id, }, }) ); body = `Deleted item ${event.pathParameters.id}`; break; case "GET /items/{id}": body = await dynamo.send( new GetCommand({ Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 248 Amazon API Gateway Developer Guide TableName: tableName, Key: { id: event.pathParameters.id, }, }) ); body = body.Item; break; case "GET /items": body = await dynamo.send( new ScanCommand({ TableName: tableName }) ); body = body.Items; break; case "PUT /items": let requestJSON = JSON.parse(event.body); await dynamo.send( new PutCommand({ TableName: tableName, Item: { id: requestJSON.id, price: requestJSON.price, name: requestJSON.name, }, }) ); body = `Put item ${requestJSON.id}`; break; default: throw new Error(`Unsupported route: "${event.routeKey}"`); } } catch (err) { statusCode = 400; body = err.message; } finally { body = JSON.stringify(body); } return { statusCode, body, headers, }; Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 249 Amazon API Gateway }; Python Developer Guide import json import boto3 from decimal import Decimal client = boto3.client('dynamodb') dynamodb = boto3.resource("dynamodb") table = dynamodb.Table('http-crud-tutorial-items') tableName = 'http-crud-tutorial-items' def lambda_handler(event, context): print(event) body = {} statusCode = 200 headers = { "Content-Type": "application/json" } try: if event['routeKey'] == "DELETE /items/{id}": table.delete_item( Key={'id': event['pathParameters']['id']}) body = 'Deleted item ' + event['pathParameters']['id'] elif event['routeKey'] == "GET /items/{id}": body = table.get_item( Key={'id': event['pathParameters']['id']}) body = body["Item"] responseBody = [ {'price': float(body['price']), 'id': body['id'], 'name': body['name']}] body = responseBody elif event['routeKey'] == "GET /items": body = table.scan() body = body["Items"] print("ITEMS----") print(body) responseBody = [] for items in body: responseItems = [ Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 250 Amazon API Gateway Developer Guide {'price': float(items['price']), 'id': items['id'], 'name': items['name']}] responseBody.append(responseItems) body = responseBody elif event['routeKey'] == "PUT /items": requestJSON = json.loads(event['body']) table.put_item( Item={ 'id': requestJSON['id'], 'price': Decimal(str(requestJSON['price'])), 'name': requestJSON['name'] }) body = 'Put item ' + requestJSON['id'] except KeyError: statusCode = 400 body = 'Unsupported route: ' + event['routeKey'] body = json.dumps(body) res = { "statusCode": statusCode, "headers": { "Content-Type": "application/json" }, "body": body } return res Step 3: Create an HTTP API The HTTP API provides an HTTP endpoint for your Lambda function. In this step, you create an empty API. In the following steps, you configure routes and integrations to connect your API and your Lambda function. To create an HTTP API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API, and then for HTTP API, choose Build. 3. 4. For API name, enter http-crud-tutorial-api. For IP address type, select IPv4. 5. Choose Next. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 251 Amazon API Gateway Developer Guide 6. For Configure routes, choose Next to skip route creation. You create routes later. 7. Review the stage that API Gateway creates for you, and then choose Next. 8. Choose Create. Step 4: Create routes Routes are a way to send incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource path, for example, GET /items. For this example API, we create four routes: • GET /items/{id} • GET /items • PUT /items • DELETE /items/{id} To create routes 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Routes. 4. Choose Create. 5. 6. For Method, choose GET. For the path, enter /items/{id}. The {id} at the end of the path is a path parameter that API Gateway retrieves from the request path when a client makes a request. 7. Choose Create. 8. Repeat steps 4-7 for GET /items, DELETE /items/{id}, and PUT /items. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 252 Amazon API Gateway Developer Guide Step 5: Create an integration You create an integration to connect a route to backend resources. For this example API, you create one Lambda integration that you use for all routes. To create an integration 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Integrations. 4. Choose Manage integrations and then choose Create. 5. 6. 7. Skip Attach this integration to a route. You complete that in a later step. For Integration type, choose Lambda function. For Lambda function, enter http-crud-tutorial-function. 8. Choose Create.
apigateway-dg-066
apigateway-dg.pdf
66
Lambda and DynamoDB 252 Amazon API Gateway Developer Guide Step 5: Create an integration You create an integration to connect a route to backend resources. For this example API, you create one Lambda integration that you use for all routes. To create an integration 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Integrations. 4. Choose Manage integrations and then choose Create. 5. 6. 7. Skip Attach this integration to a route. You complete that in a later step. For Integration type, choose Lambda function. For Lambda function, enter http-crud-tutorial-function. 8. Choose Create. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 253 Amazon API Gateway Developer Guide Step 6: Attach your integration to routes For this example API, you use the same Lambda integration for all routes. After you attach the integration to all of the API's routes, your Lambda function is invoked when a client calls any of your routes. To attach integrations to routes 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Integrations. 4. Choose a route. 5. Under Choose an existing integration, choose http-crud-tutorial-function. 6. Choose Attach integration. 7. Repeat steps 4-6 for all routes. All routes show that an AWS Lambda integration is attached. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 254 Amazon API Gateway Developer Guide Now that you have an HTTP API with routes and integrations, you can test your API. Step 7: Test your API To make sure that your API is working, you use curl. To get the URL to invoke your API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Note your API's invoke URL. It appears under Invoke URL on the Details page. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 255 Amazon API Gateway Developer Guide 4. Copy your API's invoke URL. The full URL looks like https://abcdef123.execute-api.us-west-2.amazonaws.com. To create or update an item • Use the following command to create or update an item. The command includes a request body with the item's ID, price, and name. curl -X "PUT" -H "Content-Type: application/json" -d "{\"id\": \"123\", \"price\": 12345, \"name\": \"myitem\"}" https://abcdef123.execute-api.us- west-2.amazonaws.com/items To get all items • Use the following command to list all items. curl https://abcdef123.execute-api.us-west-2.amazonaws.com/items To get an item • Use the following command to get an item by its ID. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 256 Amazon API Gateway Developer Guide curl https://abcdef123.execute-api.us-west-2.amazonaws.com/items/123 To delete an item 1. Use the following command to delete an item. curl -X "DELETE" https://abcdef123.execute-api.us-west-2.amazonaws.com/items/123 2. Get all items to verify that the item was deleted. curl https://abcdef123.execute-api.us-west-2.amazonaws.com/items Step 8: Clean up To prevent unnecessary costs, delete the resources that you created as part of this getting started exercise. The following steps delete your HTTP API, your Lambda function, and associated resources. To delete a DynamoDB table 1. Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/. 2. Select your table. 3. Choose Delete table. 4. Confirm your choice, and choose Delete. To delete an HTTP API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. On the APIs page, select an API. Choose Actions, and then choose Delete. 3. Choose Delete. To delete a Lambda function 1. Sign in to the Lambda console at https://console.aws.amazon.com/lambda. 2. On the Functions page, select a function. Choose Actions, and then choose Delete. Tutorial: Build a CRUD HTTP API with Lambda and DynamoDB 257 Amazon API Gateway 3. Choose Delete. To delete a Lambda function's log group Developer Guide 1. In the Amazon CloudWatch console, open the Log groups page. 2. On the Log groups page, select the function's log group (/aws/lambda/http-crud- tutorial-function). Choose Actions, and then choose Delete log group. 3. Choose Delete. To delete a Lambda function's execution role 1. 2. In the AWS Identity and Access Management console, open the Roles page. Select the function's role, for example, http-crud-tutorial-role. 3. Choose Delete role. 4. Choose Yes, delete. Next steps: Automate with AWS SAM or AWS CloudFormation You can automate the creation and cleanup of AWS resources by using AWS CloudFormation or AWS SAM. For an example AWS SAM template for this tutorial, see template.yaml. For example AWS CloudFormation templates, see example AWS CloudFormation templates. Tutorial: Create an HTTP API with a private integration to an Amazon ECS service In this tutorial, you create a serverless API that connects to an Amazon ECS service that runs in an Amazon VPC. Clients outside of your Amazon VPC can use the API to access your Amazon ECS service. This tutorial takes approximately an hour to complete. First, you use an AWS CloudFormation template to create a Amazon VPC and Amazon ECS service. Then you use the API Gateway console to
apigateway-dg-067
apigateway-dg.pdf
67
SAM template for this tutorial, see template.yaml. For example AWS CloudFormation templates, see example AWS CloudFormation templates. Tutorial: Create an HTTP API with a private integration to an Amazon ECS service In this tutorial, you create a serverless API that connects to an Amazon ECS service that runs in an Amazon VPC. Clients outside of your Amazon VPC can use the API to access your Amazon ECS service. This tutorial takes approximately an hour to complete. First, you use an AWS CloudFormation template to create a Amazon VPC and Amazon ECS service. Then you use the API Gateway console to create a VPC link. The VPC link allows API Gateway to access the Amazon ECS service that runs in your Amazon VPC. Next, you create an HTTP API that uses the VPC link to connect to your Amazon ECS service. Lastly, you test your API. Tutorial: Create an HTTP API with a private integration to Amazon ECS 258 Amazon API Gateway Developer Guide When you invoke your HTTP API, API Gateway routes the request to your Amazon ECS service through your VPC link, and then returns the response from the service. To complete this tutorial, you need an AWS account and an AWS Identity and Access Management user with console access. For more information, see Prerequisites. In this tutorial, you use the AWS Management Console. For an AWS CloudFormation template that creates this API and all related resources, see template.yaml. Topics • Step 1: Create an Amazon ECS service • Step 2: Create a VPC link • Step 3: Create an HTTP API • Step 4: Create a route • Step 5: Create an integration • Step 6: Test your API • Step 7: Clean up • Next steps: Automate with AWS CloudFormation Step 1: Create an Amazon ECS service Amazon ECS is a container management service that makes it easy to run, stop, and manage Docker containers on a cluster. In this tutorial, you run your cluster on a serverless infrastructure that's managed by Amazon ECS. Tutorial: Create an HTTP API with a private integration to Amazon ECS 259 Amazon API Gateway Developer Guide Download and unzip this AWS CloudFormation template, which creates all of the dependencies for the service, including an Amazon VPC. You use the template to create an Amazon ECS service that uses an Application Load Balancer. To create an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Choose Create stack and then choose With new resources (standard). 3. 4. For Specify template, choose Upload a template file. Select the template that you downloaded. 5. Choose Next. 6. 7. 8. For Stack name, enter http-api-private-integrations-tutorial and then choose Next. For Configure stack options, choose Next. For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account. 9. Choose Submit. AWS CloudFormation provisions the ECS service, which can take a few minutes. When the status of your AWS CloudFormation stack is CREATE_COMPLETE, you're ready to move on to the next step. Step 2: Create a VPC link A VPC link allows API Gateway to access private resources in an Amazon VPC. You use a VPC link to allow clients to access your Amazon ECS service through your HTTP API. To create a VPC link 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. On the main navigation pane, choose VPC links and then choose Create. 3. 4. 5. You might need to choose the menu icon to open the main navigation pane. For Choose a VPC link version, select VPC link for HTTP APIs. For Name, enter private-integrations-tutorial. For VPC, choose the VPC that you created in step 1. The name should start with PrivateIntegrationsStack. Tutorial: Create an HTTP API with a private integration to Amazon ECS 260 Amazon API Gateway Developer Guide 6. For Subnets, select the two private subnets in your VPC. Their names end with PrivateSubnet. 7. For Security groups, select the Group ID that starts with private-integrations- tutorial and has the description of PrivateIntegrationsStack/ PrivateIntegrationsTutorialService/Service/SecurityGroup. 8. Choose Create. After you create your VPC link, API Gateway provisions Elastic Network Interfaces to access your VPC. The process can take a few minutes. In the meantime, you can create your API. Step 3: Create an HTTP API The HTTP API provides an HTTP endpoint for your Amazon ECS service. In this step, you create an empty API. In Steps 4 and 5, you configure a route and an integration to connect your API and your Amazon ECS service. To create an HTTP API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API, and then for HTTP API, choose Build. 3. 4. For API name, enter http-private-integrations-tutorial. For IP address type, select IPv4. 5. Choose Next. 6. For Configure routes, choose Next to
apigateway-dg-068
apigateway-dg.pdf
68
can create your API. Step 3: Create an HTTP API The HTTP API provides an HTTP endpoint for your Amazon ECS service. In this step, you create an empty API. In Steps 4 and 5, you configure a route and an integration to connect your API and your Amazon ECS service. To create an HTTP API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API, and then for HTTP API, choose Build. 3. 4. For API name, enter http-private-integrations-tutorial. For IP address type, select IPv4. 5. Choose Next. 6. For Configure routes, choose Next to skip route creation. You create routes later. 7. Review the stage that API Gateway creates for you. API Gateway creates a $default stage with automatic deployments enabled, which is the best choice for this tutorial. Choose Next. 8. Choose Create. Step 4: Create a route Routes are a way to send incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource path, for example, GET /items. For this example API, we create one route. Tutorial: Create an HTTP API with a private integration to Amazon ECS 261 Amazon API Gateway To create a route Developer Guide 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Routes. 4. Choose Create. 5. 6. For Method, choose ANY. For the path, enter /{proxy+}. The {proxy+} at the end of the path is a greedy path variable. API Gateway sends all requests to your API to this route. 7. Choose Create. Step 5: Create an integration You create an integration to connect a route to backend resources. To create an integration 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Integrations. 4. Choose Manage integrations and then choose Create. 5. 6. 7. 8. 9. For Attach this integration to a route, select the ANY /{proxy+} route that you created earlier. For Integration type, choose Private resource. For Integration details, choose Select manually. For Target service, choose ALB/NLB. For Load balancer, choose the load balancer that you created with the AWS CloudFormation template in Step 1. It's name should start with http-Priva. 10. For Listener, choose HTTP 80. 11. For VPC link, choose the VPC link that you created in Step 2. It's name should be private- integrations-tutorial. 12. Choose Create. Tutorial: Create an HTTP API with a private integration to Amazon ECS 262 Amazon API Gateway Developer Guide To verify that your route and integration are set up correctly, select Attach integrations to routes. The console shows that you have an ANY /{proxy+} route with an integration to a VPC Load Balancer. Now you're ready to test your API. Step 6: Test your API Next, you test your API to make sure that it's working. For simplicity, use a web browser to invoke your API. To test your API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Note your API's invoke URL. Tutorial: Create an HTTP API with a private integration to Amazon ECS 263 Amazon API Gateway Developer Guide 4. In a web browser, go to your API's invoke URL. The full URL should look like https://abcdef123.execute-api.us- east-2.amazonaws.com. Your browser sends a GET request to the API. 5. Verify that your API's response is a welcome message that tells you that your app is running on Amazon ECS. If you see the welcome message, you successfully created an Amazon ECS service that runs in an Amazon VPC, and you used an API Gateway HTTP API with a VPC link to access the Amazon ECS service. Step 7: Clean up To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following steps delete your VPC link, AWS CloudFormation stack, and HTTP API. To delete an HTTP API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. On the APIs page, select an API. Choose Actions, choose Delete, and then confirm your choice. Tutorial: Create an HTTP API with a private integration to Amazon ECS 264 Amazon API Gateway To delete a VPC link Developer Guide 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose VPC link. 3. Select your VPC link, choose Delete, and then confirm your choice. To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack. 3. Choose Delete and then confirm your choice. Next steps: Automate with AWS CloudFormation You can automate the creation and cleanup of all AWS resources involved in this tutorial. For a full example AWS CloudFormation template, see template.yaml. Amazon API Gateway WebSocket API tutorials The following tutorials provide a hands-on exercise to help you learn about API
apigateway-dg-069
apigateway-dg.pdf
69
to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose VPC link. 3. Select your VPC link, choose Delete, and then confirm your choice. To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack. 3. Choose Delete and then confirm your choice. Next steps: Automate with AWS CloudFormation You can automate the creation and cleanup of all AWS resources involved in this tutorial. For a full example AWS CloudFormation template, see template.yaml. Amazon API Gateway WebSocket API tutorials The following tutorials provide a hands-on exercise to help you learn about API Gateway WebSocket APIs. Topics • Tutorial: Create a WebSocket chat app with a WebSocket API, Lambda and DynamoDB • Tutorial: Create a WebSocket API with an AWS integration Tutorial: Create a WebSocket chat app with a WebSocket API, Lambda and DynamoDB In this tutorial, you'll create a serverless chat application with a WebSocket API. With a WebSocket API, you can support two-way communication between clients. Clients can receive messages without having to poll for updates. This tutorial takes approximately 30 minutes to complete. First, you'll use an AWS CloudFormation template to create Lambda functions that will handle API requests, as well as a DynamoDB table that stores your client IDs. Then, you'll use the API Gateway console to create a WebSocket API that WebSocket API tutorials 265 Amazon API Gateway Developer Guide integrates with your Lambda functions. Lastly, you'll test your API to verify that messages are sent and received. To complete this tutorial, you need an AWS account and an AWS Identity and Access Management user with console access. For more information, see Prerequisites. You also need wscat to connect to your API. For more information, see the section called “Use wscat to connect to a WebSocket API and send messages to it”. Topics • Step 1: Create Lambda functions and a DynamoDB table • Step 2: Create a WebSocket API • Step 3: Test your API • Step 4: Clean up • Next steps: Automate with AWS CloudFormation Step 1: Create Lambda functions and a DynamoDB table Download and unzip the app creation template for AWS CloudFormation. You'll use this template to create a Amazon DynamoDB table to store your app's client IDs. Each connected client has Tutorial: Create a WebSocket chat app 266 Amazon API Gateway Developer Guide a unique ID which we will use as the table's partition key. This template also creates Lambda functions that update your client connections in DynamoDB and handle sending messages to connected clients. To create an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Choose Create stack and then choose With new resources (standard). 3. 4. For Specify template, choose Upload a template file. Select the template that you downloaded. 5. Choose Next. 6. 7. 8. For Stack name, enter websocket-api-chat-app-tutorial and then choose Next. For Configure stack options, choose Next. For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account. 9. Choose Submit. AWS CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. When the status of your AWS CloudFormation stack is CREATE_COMPLETE, you're ready to move on to the next step. Step 2: Create a WebSocket API You'll create a WebSocket API to handle client connections and route requests to the Lambda functions that you created in Step 1. To create a WebSocket API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API. Then for WebSocket API, choose Build. 3. 4. 5. For API name, enter websocket-chat-app-tutorial. For IP address type, select IPv4. For Route selection expression, enter request.body.action. The route selection expression determines the route that API Gateway invokes when a client sends a message. Tutorial: Create a WebSocket chat app 267 Amazon API Gateway 6. Choose Next. Developer Guide 7. 8. For Predefined routes, choose Add $connect, Add $disconnect, and Add $default. The $connect and $disconnect routes are special routes that API Gateway invokes automatically when a client connects to or disconnects from an API. API Gateway invokes the $default route when no other routes match a request. For Custom routes, choose Add custom route. For Route key, enter sendmessage. This custom route handles messages that are sent to connected clients. 9. Choose Next. 10. Under Attach integrations, for each route and Integration type, choose Lambda. For Lambda, choose the corresponding Lambda function that you created with AWS CloudFormation in Step 1. Each function's name matches a route. For example, for the $connect route, choose the function named websocket-chat-app-tutorial- ConnectHandler. 11. Review the stage that API Gateway creates for you. By default, API Gateway creates a stage name production and automatically deploys your API to that stage. Choose Next. 12. Choose Create and deploy.
apigateway-dg-070
apigateway-dg.pdf
70
route. For Route key, enter sendmessage. This custom route handles messages that are sent to connected clients. 9. Choose Next. 10. Under Attach integrations, for each route and Integration type, choose Lambda. For Lambda, choose the corresponding Lambda function that you created with AWS CloudFormation in Step 1. Each function's name matches a route. For example, for the $connect route, choose the function named websocket-chat-app-tutorial- ConnectHandler. 11. Review the stage that API Gateway creates for you. By default, API Gateway creates a stage name production and automatically deploys your API to that stage. Choose Next. 12. Choose Create and deploy. Step 3: Test your API Next, you'll test your API to make sure that it works correctly. Use the wscat command to connect to the API. To to get the invoke URL for your API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose your API. 3. Choose Stages, and then choose production. 4. Note your API's WebSocket URL. The URL should look like wss://abcdef123.execute- api.us-east-2.amazonaws.com/production. To connect to your API 1. Use the following command to connect to your API. When you connect to your API, API Gateway invokes the $connect route. When this route is invoked, it calls a Lambda function that stores your connection ID in DynamoDB. Tutorial: Create a WebSocket chat app 268 Amazon API Gateway Developer Guide wscat -c wss://abcdef123.execute-api.us-west-2.amazonaws.com/production Connected (press CTRL+C to quit) 2. Open a new terminal and run the wscat command again with the following parameters. wscat -c wss://abcdef123.execute-api.us-west-2.amazonaws.com/production Connected (press CTRL+C to quit) This gives you two connected clients that can exchange messages. To send a message • API Gateway determines which route to invoke based on your API's route selection expression. Your API's route selection expression is $request.body.action. As a result, API Gateway invokes the sendmessage route when you send the following message: {"action": "sendmessage", "message": "hello, everyone!"} The Lambda function associated with the invoked route collects the client IDs from DynamoDB. Then, the function calls the API Gateway Management API and sends the message to those clients. All connected clients receive the following message: < hello, everyone! To invoke your API's $default route • API Gateway invokes your API's default route when a client sends a message that doesn't match your defined routes. The Lambda function associated with the $default route uses the API Gateway Management API to send the client information about their connection. test Tutorial: Create a WebSocket chat app 269 Amazon API Gateway Developer Guide Use the sendmessage route to send a message. Your info: {"ConnectedAt":"2022-01-25T18:50:04.673Z","Identity": {"SourceIp":"192.0.2.1","UserAgent":null},"LastActiveAt":"2022-01-25T18:50:07.642Z","connectionID":"Mg_ugfpqPHcCIVA="} To disconnect from your API • Press CTRL+C to disconnect from your API. When a client disconnects from your API, API Gateway invokes your API's $disconnect route. The Lambda integration for your API's $disconnect route removes the connection ID from DynamoDB. Step 4: Clean up To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following steps delete your AWS CloudFormation stack and WebSocket API. To delete a WebSocket API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. On the APIs page, select your websocket-chat-app-tutorial API. Choose Actions, choose Delete, and then confirm your choice. To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack. 3. Choose Delete and then confirm your choice. Next steps: Automate with AWS CloudFormation You can automate the creation and cleanup of all of the AWS resources involved in this tutorial. For an AWS CloudFormation template that creates this API and all related resources, see ws-chat- app.yaml. Tutorial: Create a WebSocket chat app 270 Amazon API Gateway Developer Guide Tutorial: Create a WebSocket API with an AWS integration In this tutorial, you create a serverless broadcast application with a WebSocket API. Clients can receive messages without having to poll for updates. This tutorial shows how to broadcast messages to connected clients and includes an example of a Lambda authorizer, a mock integration, and a non-proxy integration to Step Functions. After you create your resources using a AWS CloudFormation template, you'll use the API Gateway console to create a WebSocket API that integrates with your AWS resources. You'll attach a Lambda authorizer to your API and create an AWS service integration with Step Functions to start a state machine execution. The Step Functions state machine will invoke a Lambda function that sends a message to all connected clients. After you build your API, you'll test your connection to your API and verify that messages are sent and received. This tutorial takes approximately 45 minutes to complete. Topics • Prerequisites • Step 1: Create resources • Step 2: Create a WebSocket API • Step 3: Create a Lambda authorizer Tutorial: Create a WebSocket API with an AWS integration 271 Amazon API Gateway Developer
apigateway-dg-071
apigateway-dg.pdf
71
to your API and create an AWS service integration with Step Functions to start a state machine execution. The Step Functions state machine will invoke a Lambda function that sends a message to all connected clients. After you build your API, you'll test your connection to your API and verify that messages are sent and received. This tutorial takes approximately 45 minutes to complete. Topics • Prerequisites • Step 1: Create resources • Step 2: Create a WebSocket API • Step 3: Create a Lambda authorizer Tutorial: Create a WebSocket API with an AWS integration 271 Amazon API Gateway Developer Guide • Step 4: Create a mock two-way integration • Step 5: Create a non-proxy integration with Step Functions • Step 6: Test your API • Step 7: Clean up • Next steps Prerequisites You need the following prerequisites: • An AWS account and an AWS Identity and Access Management user with console access. For more information, see Prerequisites. • wscat to connect to your API. For more information, see the section called “Use wscat to connect to a WebSocket API and send messages to it”. We recommend that you complete the WebSocket chat app tutorial before you start this tutorial. To complete the WebSocket chat app tutorial, see the section called “Tutorial: Create a WebSocket chat app”. Step 1: Create resources Download and unzip the app creation template for AWS CloudFormation. You'll use this template to create the following: • Lambda functions that handle API requests and authorize access to your API. • A DynamoDB table to store client IDs and the principal user identification returned by the Lambda authorizer. • A Step Functions state machine to send messages to connected clients. To create an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Choose Create stack and then choose With new resources (standard). 3. 4. For Specify template, choose Upload a template file. Select the template that you downloaded. Tutorial: Create a WebSocket API with an AWS integration 272 Amazon API Gateway 5. Choose Next. Developer Guide 6. 7. 8. For Stack name, enter websocket-step-functions-tutorial and then choose Next. For Configure stack options, choose Next. For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account. 9. Choose Submit. AWS CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. Choose the Outputs tab to see your created resources and their ARNs. When the status of your AWS CloudFormation stack is CREATE_COMPLETE, you're ready to move on to the next step. Step 2: Create a WebSocket API You'll create a WebSocket API to handle client connections and route requests to the resources that you created in Step 1. To create a WebSocket API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API. Then for WebSocket API, choose Build. 3. 4. 5. For API name, enter websocket-step-functions-tutorial. For IP address type, select IPv4. For Route selection expression, enter request.body.action. The route selection expression determines the route that API Gateway invokes when a client sends a message. 6. Choose Next. 7. For Predefined routes, choose Add $connect, Add $disconnect, Add $default. The $connect and $disconnect routes are special routes that API Gateway invokes automatically when a client connects to or disconnects from an API. API Gateway invokes the $default route when no other routes match a request. You will create a custom route to connect to Step Functions after you create your API. 8. Choose Next. 9. For Integration for $connect, do the following: Tutorial: Create a WebSocket API with an AWS integration 273 Amazon API Gateway Developer Guide a. b. For Integration type, choose Lambda. For Lambda function, choose the corresponding $connect Lambda function that you created with AWS CloudFormation in Step 1. The Lambda function name should start with websocket-step. 10. For Integration for $disconnect, do the following: a. b. For Integration type, choose Lambda. For Lambda function, choose the corresponding $disconnect Lambda function that you created with AWS CloudFormation in Step 1. The Lambda function name should start with websocket-step. 11. For Integration for $default, choose mock. In a mock integration, API Gateway manages the route response without an integration backend. 12. Choose Next. 13. Review the stage that API Gateway creates for you. By default, API Gateway creates a stage named production and automatically deploys your API to that stage. Choose Next. 14. Choose Create and deploy. Step 3: Create a Lambda authorizer To control access to your WebSocket API, you create a Lambda authorizer. The AWS CloudFormation template created the Lambda authorizer function for you. You can see the Lambda function in the Lambda console. The name should start with websocket-step- functions-tutorial-AuthorizerHandler. This Lambda function denies all calls to the WebSocket API unless the Authorization header
apigateway-dg-072
apigateway-dg.pdf
72
an integration backend. 12. Choose Next. 13. Review the stage that API Gateway creates for you. By default, API Gateway creates a stage named production and automatically deploys your API to that stage. Choose Next. 14. Choose Create and deploy. Step 3: Create a Lambda authorizer To control access to your WebSocket API, you create a Lambda authorizer. The AWS CloudFormation template created the Lambda authorizer function for you. You can see the Lambda function in the Lambda console. The name should start with websocket-step- functions-tutorial-AuthorizerHandler. This Lambda function denies all calls to the WebSocket API unless the Authorization header is Allow. The Lambda function also passes the $context.authorizer.principalId variable to your API, which is later used in the DynamoDB table to identify API callers. In this step, you configure the $connect route to use the Lambda authorizer. To create a Lambda authorizer 1. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. In the main navigation pane, choose Authorizers. 3. Choose Create an authorizer. Tutorial: Create a WebSocket API with an AWS integration 274 Amazon API Gateway Developer Guide 4. 5. For Authorizer name, enter LambdaAuthorizer. For Authorizer ARN, enter the name of the authorizer created by the AWS CloudFormation template. The name should start with websocket-step-functions-tutorial- AuthorizerHandler. Note We recommend that you don't use this example authorizer for your production APIs. 6. For Identity source type, choose Header. For Key, enter Authorization. 7. Choose Create authorizer. After you create your authorizer, you attach it to the $connect route of your API. To attach an authorizer to the $connect route 1. In the main navigation pane, choose Routes. 2. Choose the $connect route. 3. 4. In the Route request settings section, choose Edit. For Authorization, choose the dropdown menu, and then select your request authorizer. 5. Choose Save changes. Step 4: Create a mock two-way integration Next, you create the two-way mock integration for the $default route. A mock integration lets you send a response to the client without using a backend. When you create an integration for the $default route, you can show clients how to interact with your API. You configure the $default route to inform clients to use the sendmessage route. To create a mock integration 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose the $default route, and then choose the Integration request tab. 3. 4. For Request templates, choose Edit. For Template selection expression, enter 200, and then choose Edit. Tutorial: Create a WebSocket API with an AWS integration 275 Amazon API Gateway Developer Guide 5. On the Integration request tab, for Request templates, choose Create template. 6. 7. For Template key, enter 200. For Generate template, enter the following mapping template: {"statusCode": 200} Choose Create template. The result should look like the following: 8. The the $default route pane, choose Enable two-way communication. 9. Choose the Integration response tab, and then choose Create integration response. 10. For Response key, enter $default. 11. For Template selection expression, enter 200. 12. Choose Create response. Tutorial: Create a WebSocket API with an AWS integration 276 Amazon API Gateway Developer Guide 13. Under Response templates, choose Create template. 14. For Template key, enter 200. 15. For Response template, enter the following mapping template: {"Use the sendmessage route to send a message. Connection ID: $context.connectionId"} 16. Choose Create template. The result should look like the following: Tutorial: Create a WebSocket API with an AWS integration 277 Amazon API Gateway Developer Guide Step 5: Create a non-proxy integration with Step Functions Next, you create a sendmessage route. Clients can invoke the sendmessage route to broadcast a message to all connected clients. The sendmessage route has a non-proxy AWS service integration with AWS Step Functions. The integration invokes the StartExecution command for the Step Functions state machine that the AWS CloudFormation template created for you. To create a non-proxy integration 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create route. 3. 4. 5. 6. 7. 8. 9. For Route key, enter sendmessage. For Integration type, choose AWS service. For AWS Region, enter the Region where you deployed your AWS CloudFormation template. For AWS service, choose Step Functions. For HTTP method, choose POST. For Action name, enter StartExecution. For Execution role, enter the execution role created by the AWS CloudFormation template. The name should be WebsocketTutorialApiRole. 10. Choose Create route. Next, you create a mapping template to send request parameters to the Step Functions state machine. To create a mapping template 1. Choose the sendmessage route, and then choose the Integration request tab. 2. 3. In the Request templates section, choose Edit. For Template selection expression, enter \$default. 4. Choose Edit. 5. 6. 7. In the Request templates section, choose Create template. For Template key, enter \$default. For Generate template, enter the following
apigateway-dg-073
apigateway-dg.pdf
73
For Action name, enter StartExecution. For Execution role, enter the execution role created by the AWS CloudFormation template. The name should be WebsocketTutorialApiRole. 10. Choose Create route. Next, you create a mapping template to send request parameters to the Step Functions state machine. To create a mapping template 1. Choose the sendmessage route, and then choose the Integration request tab. 2. 3. In the Request templates section, choose Edit. For Template selection expression, enter \$default. 4. Choose Edit. 5. 6. 7. In the Request templates section, choose Create template. For Template key, enter \$default. For Generate template, enter the following mapping template: #set($domain = "$context.domainName") Tutorial: Create a WebSocket API with an AWS integration 278 Amazon API Gateway Developer Guide #set($stage = "$context.stage") #set($body = $input.json('$')) #set($getMessage = $util.parseJson($body)) #set($mymessage = $getMessage.message) { "input": "{\"domain\": \"$domain\", \"stage\": \"$stage\", \"message\": \"$mymessage\"}", "stateMachineArn": "arn:aws:states:us-east-2:123456789012:stateMachine:WebSocket- Tutorial-StateMachine" } Replace the stateMachineArn with the ARN of the state machine created by AWS CloudFormation. The mapping template does the following: • Creates the variable $domain using the context variable domainName. • Creates the variable $stage using the context variable stage. The $domain and $stage variables are required to build a callback URL. • Takes in the incoming sendmessage JSON message, and extracts the message property. • Creates the input for the state machine. The input is the domain and stage of the WebSocket API and the message from the sendmessage route. 8. Choose Create template. Tutorial: Create a WebSocket API with an AWS integration 279 Amazon API Gateway Developer Guide You can create a non-proxy integration on the $connect or $disconnect routes, to directly add or remove a connection ID from the DynamoDB table, without invoking a Lambda function. Step 6: Test your API Next, you'll deploy and test your API to make sure that it works correctly. You will use the wscat command to connect to the API and then, you will use a slash command to send a ping frame to check the connection to the WebSocket API. To deploy your API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Tutorial: Create a WebSocket API with an AWS integration 280 Amazon API Gateway Developer Guide 2. In the main navigation pane, choose Routes. 3. Choose Deploy API. 4. 5. For Stage, choose production. (Optional) For Deployment description, enter a description. 6. Choose Deploy. After you deploy your API, you can invoke it. Use the invoke URL to call your API. To get the invoke URL for your API 1. Choose your API. 2. Choose Stages, and then choose production. 3. Note your API's WebSocket URL. The URL should look like wss://abcdef123.execute- api.us-east-2.amazonaws.com/production. Now that you have your invoke URL, you can test the connection to your WebSocket API. To test the connection to your API 1. Use the following command to connect to your API. First, you test the connection by invoking the /ping path. wscat -c wss://abcdef123.execute-api.us-east-2.amazonaws.com/production -H "Authorization: Allow" --slash -P Connected (press CTRL+C to quit) 2. Enter the following command to ping the control frame. You can use a control frame for keepalive purposes from the client side. /ping The result should look like the following: < Received pong (data: "") Tutorial: Create a WebSocket API with an AWS integration 281 Amazon API Gateway Developer Guide Now that you have tested the connection, you can test that your API works correctly. In this step, you open a new terminal window so the WebSocket API can send a message to all connected clients. To test your API 1. Open a new terminal and run the wscat command again with the following parameters. wscat -c wss://abcdef123.execute-api.us-east-2.amazonaws.com/production -H "Authorization: Allow" Connected (press CTRL+C to quit) 2. API Gateway determines which route to invoke based on your API's route request selection expression. Your API's route select expression is $request.body.action. As a result, API Gateway invokes the sendmessage route when you send the following message: {"action": "sendmessage", "message": "hello, from Step Functions!"} The Step Functions state machine associated with the route invokes a Lambda function with the message and the callback URL. The Lambda function calls the API Gateway Management API and sends the message to all connected clients. All clients receive the following message: < hello, from Step Functions! Now that you have tested your WebSocket API, you can disconnect from your API. To disconnect from your API • Press CTRL+Cto disconnect from your API. When a client disconnects from your API, API Gateway invokes your API's $disconnect route. The Lambda integration for your API's $disconnect route removes the connection ID from DynamoDB. Tutorial: Create a WebSocket API with an AWS integration 282 Amazon API Gateway Step 7: Clean up Developer Guide To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following steps delete your AWS
apigateway-dg-074
apigateway-dg.pdf
74
message: < hello, from Step Functions! Now that you have tested your WebSocket API, you can disconnect from your API. To disconnect from your API • Press CTRL+Cto disconnect from your API. When a client disconnects from your API, API Gateway invokes your API's $disconnect route. The Lambda integration for your API's $disconnect route removes the connection ID from DynamoDB. Tutorial: Create a WebSocket API with an AWS integration 282 Amazon API Gateway Step 7: Clean up Developer Guide To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following steps delete your AWS CloudFormation stack and WebSocket API. To delete a WebSocket API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. On the APIs page, select your websocket-api. 3. Choose Actions, choose Delete, and then confirm your choice. To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack. 3. Choose Delete and then confirm your choice. Next steps You can automate the creation and cleanup of all the AWS resources involved in this tutorial. For an example of an AWS CloudFormation template that automates these actions for this tutorial, see ws-sfn.zip. Tutorial: Create a WebSocket API with an AWS integration 283 Amazon API Gateway Developer Guide API Gateway REST APIs A REST API in API Gateway is a collection of resources and methods that are integrated with backend HTTP endpoints, Lambda functions, or other AWS services. You can use API Gateway features to help you with all aspects of the API lifecycle, from creation through monitoring your production APIs. API Gateway REST APIs use a request/response model where a client sends a request to a service and the service responds back synchronously. This kind of model is suitable for many different kinds of applications that depend on synchronous communication. Topics • Develop REST APIs in API Gateway • Publish REST APIs for customers to invoke • Optimize performance of REST APIs • Distribute your REST APIs to clients in API Gateway • Protect your REST APIs in API Gateway • Monitor REST APIs in API Gateway Develop REST APIs in API Gateway In Amazon API Gateway, you build a REST API as a collection of programmable entities known as API Gateway resources. For example, you use a RestApi resource to represent an API that can contain a collection of Resource entities. Each Resource entity can have one or more Method resources. A Method is an incoming request submitted by the client and can contain the following request parameters: a path parameter, a header, or a query string parameter. In addition, depending on the HTTP method, the request can contain a body. Your method defines how the client accesses the exposed Resource. To integrate the Method with a backend endpoint, also known as the integration endpoint, you create an Integration resource. This forwards the incoming request to a specified integration endpoint URI. If necessary, you can transform request parameters or the request body to meet the backend requirements, or you can create a proxy integration, where API Gateway sends the entire request in a standardized format to the integration endpoint URI and then directly sends the response to the client. Develop 284 Amazon API Gateway Developer Guide For responses, you can create a MethodResponse resource to represent a response received by the client and you create an IntegrationResponse resource to represent the response that is returned by the backend. Use an integration response to transform the backend response data before returning the data to the client or to pass the backend response as-is to the client. Example resource for a REST API The following diagram shows how API Gateway implements this request/response model for an HTTP proxy and an HTTP non-proxy integration for the GET /pets resource. The client sends the x-version:beta header to API Gateway and API Gateway sends the 204 status code to the client. In the non-proxy integration, API Gateway performs data transformations to meet the backend requirements, by modifying the integration request and integration response. In a non-proxy integration, you can access the body in the method request but you transform it in the integration request. When the integration endpoint returns a response with a body, you access and transform it in the integration response. You can't modify the body in the method response. In the proxy integration, the integration endpoint modifies the request and response. API Gateway doesn't modify the integration request or integration response, and sends the incoming request to the backend as-is. Regardless of the integration type, the client sent a request to API Gateway and API Gateway responded synchronously. Example resource for a REST API 285 Amazon API Gateway Non-proxy integration Developer Guide Proxy integration Example resource for a REST API 286 Amazon
apigateway-dg-075
apigateway-dg.pdf
75
the integration endpoint returns a response with a body, you access and transform it in the integration response. You can't modify the body in the method response. In the proxy integration, the integration endpoint modifies the request and response. API Gateway doesn't modify the integration request or integration response, and sends the incoming request to the backend as-is. Regardless of the integration type, the client sent a request to API Gateway and API Gateway responded synchronously. Example resource for a REST API 285 Amazon API Gateway Non-proxy integration Developer Guide Proxy integration Example resource for a REST API 286 Amazon API Gateway Developer Guide The following example execution logs show what API Gateway would log in the previous example. For clarity, some values and initial logs have been removed: Non-proxy integration Wed Feb 12 23:56:44 UTC 2025 : Starting execution for request: abcd-1234-5678 Wed Feb 12 23:56:44 UTC 2025 : HTTP Method: GET, Resource Path: /pets Wed Feb 12 23:56:44 UTC 2025 : Method request path: {} Wed Feb 12 23:56:44 UTC 2025 : Method request query string: {} Wed Feb 12 23:56:44 UTC 2025 : Method request headers: {x-version=beta} Wed Feb 12 23:56:44 UTC 2025 : Method request body before transformations: Wed Feb 12 23:56:44 UTC 2025 : Endpoint request URI: http://petstore-demo- endpoint.execute-api.com/petstore/pets Wed Feb 12 23:56:44 UTC 2025 : Endpoint request headers: {app-version=beta} Wed Feb 12 23:56:44 UTC 2025 : Endpoint request body after transformations: Wed Feb 12 23:56:44 UTC 2025 : Sending request to http://petstore-demo- endpoint.execute-api.com/petstore/pets Wed Feb 12 23:56:45 UTC 2025 : Received response. Status: 200, Integration latency: 123 ms Wed Feb 12 23:56:45 UTC 2025 : Endpoint response headers: {Date=Wed, 12 Feb 2025 23:56:45 GMT} Wed Feb 12 23:56:45 UTC 2025 : Endpoint response body before transformations: Wed Feb 12 23:56:45 UTC 2025 : Method response body after transformations: (null) Wed Feb 12 23:56:45 UTC 2025 : Method response headers: {X-Amzn-Trace-Id=Root=1- abcd-12345} Wed Feb 12 23:56:45 UTC 2025 : Successfully completed execution Wed Feb 12 23:56:45 UTC 2025 : Method completed with status: 204 Proxy integration Wed Feb 12 23:59:42 UTC 2025 : Starting execution for request: abcd-1234-5678 Wed Feb 12 23:59:42 UTC 2025 : HTTP Method: GET, Resource Path: /pets Wed Feb 12 23:59:42 UTC 2025 : Method request path: {} Wed Feb 12 23:59:42 UTC 2025 : Method request query string: {} Wed Feb 12 23:59:42 UTC 2025 : Method request headers: {x-version=beta} Wed Feb 12 23:59:42 UTC 2025 : Method request body before transformations: Wed Feb 12 23:59:42 UTC 2025 : Endpoint request URI: http://petstore-demo- endpoint.execute-api.com/petstore/pets Wed Feb 12 23:59:42 UTC 2025 : Endpoint request headers: { x-version=beta} Wed Feb 12 23:59:42 UTC 2025 : Endpoint request body after transformations: Wed Feb 12 23:59:42 UTC 2025 : Sending request to http://petstore-demo- endpoint.execute-api.com/petstore/pets Example resource for a REST API 287 Amazon API Gateway Developer Guide Wed Feb 12 23:59:43 UTC 2025 : Received response. Status: 204, Integration latency: 123 ms Wed Feb 12 23:59:43 UTC 2025 : Endpoint response headers: {Date=Wed, 12 Feb 2025 23:59:43 GMT} Wed Feb 12 23:59:43 UTC 2025 : Endpoint response body before transformations: Wed Feb 12 23:59:43 UTC 2025 : Method response body after transformations: Wed Feb 12 23:59:43 UTC 2025 : Method response headers: {Date=Wed, 12 Feb 2025 23:59:43 GMT} Wed Feb 12 23:59:43 UTC 2025 : Successfully completed execution Wed Feb 12 23:59:43 UTC 2025 : Method completed with status: 204 To import a similar API and test it in the AWS Management Console, see the example API. Additional REST API features for development API Gateway supports additional features for the development of your REST API. For example, to help your customers understand your API, you can provide documentation for the API. To enable this, add a DocumentationPart resource for a supported API entity. To control how clients call an API, use IAM permissions, a Lambda authorizer, or an Amazon Cognito user pool. To meter the use of your API, set up usage plans to throttle API requests. You can enable these when creating or updating your API. The following diagram shows the features available for REST API development and where in the request/response model these features are configured. Additional REST API features for development 288 Amazon API Gateway Developer Guide For an introduction on how to create an API, see the section called “Tutorial: Create a REST API with a Lambda proxy integration”. To learn more information about the capabilities of API Gateway that you might use while developing a REST API, see the following topics. These topics contain conceptual information and procedures that you can perform using the API Gateway console, the API Gateway REST API, the AWS CLI, or one of the AWS SDKs. Topics • API endpoint types for REST APIs in API Gateway • IP address types for REST APIs in
apigateway-dg-076
apigateway-dg.pdf
76
Amazon API Gateway Developer Guide For an introduction on how to create an API, see the section called “Tutorial: Create a REST API with a Lambda proxy integration”. To learn more information about the capabilities of API Gateway that you might use while developing a REST API, see the following topics. These topics contain conceptual information and procedures that you can perform using the API Gateway console, the API Gateway REST API, the AWS CLI, or one of the AWS SDKs. Topics • API endpoint types for REST APIs in API Gateway • IP address types for REST APIs in API Gateway • Methods for REST APIs in API Gateway • Control and manage access to REST APIs in API Gateway • Integrations for REST APIs in API Gateway • Request validation for REST APIs in API Gateway • Data transformations for REST APIs in API Gateway • Gateway responses for REST APIs in API Gateway • CORS for REST APIs in API Gateway • Binary media types for REST APIs in API Gateway Additional REST API features for development 289 Amazon API Gateway Developer Guide • Invoke REST APIs in API Gateway • Develop REST APIs using OpenAPI in API Gateway API endpoint types for REST APIs in API Gateway An API endpoint type refers to the hostname of the API. The API endpoint type can be edge- optimized, regional, or private, depending on where the majority of your API traffic originates from. Edge-optimized API endpoints An edge-optimized API endpoint typically routes requests to the nearest CloudFront Point of Presence (POP), which could help in cases where your clients are geographically distributed. This is the default endpoint type for API Gateway REST APIs. Edge-optimized APIs capitalize the names of HTTP headers (for example, Cookie). CloudFront sorts HTTP cookies in natural order by cookie name before forwarding the request to your origin. For more information about the way CloudFront processes cookies, see Caching Content Based on Cookies. Any custom domain name that you use for an edge-optimized API applies across all regions. Regional API endpoints A Regional API endpoint is intended for clients in the same region. When a client running on an EC2 instance calls an API in the same region, or when an API is intended to serve a small number of clients with high demands, a Regional API reduces connection overhead. For a Regional API, any custom domain name that you use is specific to the region where the API is deployed. If you deploy a regional API in multiple regions, it can have the same custom domain name in all regions. You can use custom domains together with Amazon Route 53 to perform tasks such as latency-based routing. For more information, see the section called “Set up a Regional custom domain name” and the section called “Set up an edge-optimized custom domain name in API Gateway”. Regional API endpoints pass all header names through as-is. API Gateway endpoint types 290 Amazon API Gateway Note Developer Guide In cases where API clients are geographically dispersed, it may still make sense to use a Regional API endpoint, together with your own Amazon CloudFront distribution to ensure that API Gateway does not associate the API with service-controlled CloudFront distributions. For more information about this use case, see How do I set up API Gateway with my own CloudFront distribution?. Private API endpoints A private API endpoint is an API endpoint that can only be accessed from your Amazon Virtual Private Cloud (VPC) using an interface VPC endpoint, which is an endpoint network interface (ENI) that you create in your VPC. For more information, see the section called “Private REST APIs”. Private API endpoints pass all header names through as-is. Change a public or private API endpoint type in API Gateway Changing an API endpoint type requires you to update the API's configuration. You can change an existing API type using the API Gateway console, the AWS CLI, or an AWS SDK for API Gateway. The endpoint type cannot be changed again until the current change is completed, but your API will be available. The following endpoint type changes are supported: • From edge-optimized to Regional or private • From Regional to edge-optimized or private • From private to Regional You cannot change a private API into an edge-optimized API. If you are changing a public API from edge-optimized to Regional or vice versa, note that an edge-optimized API may have different behaviors than a Regional API. For example, an edge- optimized API removes the Content-MD5 header. Any MD5 hash value passed to the backend can be expressed in a request string parameter or a body property. However, the Regional API passes this header through, although it may remap the header name to some other name. Understanding the differences helps
apigateway-dg-077
apigateway-dg.pdf
77
Regional to edge-optimized or private • From private to Regional You cannot change a private API into an edge-optimized API. If you are changing a public API from edge-optimized to Regional or vice versa, note that an edge-optimized API may have different behaviors than a Regional API. For example, an edge- optimized API removes the Content-MD5 header. Any MD5 hash value passed to the backend can be expressed in a request string parameter or a body property. However, the Regional API passes this header through, although it may remap the header name to some other name. Understanding the differences helps you decide how to update an edge-optimized API to a Regional one or from a Regional API to an edge-optimized one. API Gateway endpoint types 291 Amazon API Gateway Topics • Use the API Gateway console to change an API endpoint type • Use the AWS CLI to change an API endpoint type Use the API Gateway console to change an API endpoint type Developer Guide To change the API endpoint type of your API, perform one of the following sets of steps: To convert a public endpoint from Regional or edge-optimized and vice versa 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose API settings. 4. 5. In the API details section, choose Edit. For API endpoint type, select either Edge-optimized or Regional. 6. Choose Save changes. 7. Redeploy your API so that the changes will take effect. To convert a private endpoint to a Regional endpoint 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Edit the resource policy for your API to remove any mention of VPCs or VPC endpoints so that API calls from outside your VPC as well as inside your VPC will succeed. 4. Choose API settings. 5. 6. In the API details section, choose Edit. For API endpoint type, select Regional. 7. Choose Save changes. 8. Remove the resource policy from your API. 9. Redeploy your API so that the changes will take effect. Because you're migrating the endpoint type from private to Regional, API Gateway changes the IP address type to IPv4. For more information, see the section called “IP address types for REST APIs in API Gateway”. API Gateway endpoint types 292 Amazon API Gateway Developer Guide To convert a Regional endpoint to a private endpoint 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Create a resource policy that grants access to your VPC or VPC endpoint. For more information, see ???. 4. Choose API settings. 5. 6. 7. In the API details section, choose Edit. For API endpoint type, select Private. (Optional) For VPC endpoint IDs, select the VPC endpoint IDs that you want to associate with your private API. 8. Choose Save changes. 9. Redeploy your API so that the changes will take effect. Because you're migrating the endpoint type from Regional to private, API Gateway changes the IP address type to dualstack. For more information, see the section called “IP address types for REST APIs in API Gateway”. Use the AWS CLI to change an API endpoint type The following update-rest-api command updates an edge-optimized API to a Regional API: aws apigateway update-rest-api \ --rest-api-id a1b2c3 \ --patch-operations op=replace,path=/endpointConfiguration/types/EDGE,value=REGIONAL The successful response has a status code of 200 OK and a payload similar to the following: { "createdDate": "2017-10-16T04:09:31Z", "description": "Your first API with Amazon API Gateway. This is a sample API that integrates via HTTP with our demo Pet Store endpoints", "endpointConfiguration": { "types": "REGIONAL" }, "id": "a1b2c3", "name": "PetStore imported as edge-optimized" API Gateway endpoint types 293 Amazon API Gateway } Developer Guide The following update-rest-api command updates a Regional API to an edge-optimized API: aws apigateway update-rest-api \ --rest-api-id a1b2c3 \ --patch-operations op=replace,path=/endpointConfiguration/types/REGIONAL,value=EDGE Because put-rest-api is for updating API definitions, it is not applicable to updating an API endpoint type. IP address types for REST APIs in API Gateway When you create an API, you specify the type of IP addresses that can invoke your API. You can choose IPv4 to allow IPv4 addresses to invoke your API, or you can choose dualstack to allow both IPv4 and IPv6 addresses to invoke your API. We recommend that you set the IP address type to dualstack to alleviate IP space exhaustion or for your security posture. For more information about the benefits of a dualstack IP address type, see IPv6 on AWS. To restrict your API to only IPv6 traffic, you can create a resource policy and restrict the source IP addresses to only IPv6 ranges. You can change the IP address type by updating the API’s configuration. This change will take effect immediately, and you don't need to redeploy your API. For
apigateway-dg-078
apigateway-dg.pdf
78
dualstack to allow both IPv4 and IPv6 addresses to invoke your API. We recommend that you set the IP address type to dualstack to alleviate IP space exhaustion or for your security posture. For more information about the benefits of a dualstack IP address type, see IPv6 on AWS. To restrict your API to only IPv6 traffic, you can create a resource policy and restrict the source IP addresses to only IPv6 ranges. You can change the IP address type by updating the API’s configuration. This change will take effect immediately, and you don't need to redeploy your API. For more information, see the section called “Example: Deny API traffic based on source IP address or range” Considerations for IP address types The following considerations might impact your use of IP address types: • The default IP address type for all Regional and edge-optimized APIs is IPv4. • Private APIs can only have a dualstack IP address type. • If you change the IP address type for an existing API from IPv4 to dualstack, confirm that any policies controlling access to your APIs have been updated to account for IPv6 calls. When you change the IP address type, the change takes effect immediately. • If you migrate the endpoint type of an API from Regional or edge-optimized to private, API Gateway changes the IP address type to dualstack. For more information, see the section called “Change a public or private API endpoint type”. IP address types for REST APIs in API Gateway 294 Amazon API Gateway Developer Guide • If you migrate the endpoint type of an API from private to Regional, you must set the IP address type to dualstack. After the endpoint migration is complete, you can change the IP address type to IPv4. For more information, see the section called “Change a public or private API endpoint type”. • Your API can be mapped to a custom domain name with a different IP address type than your API. If you disable your default API endpoint, this might affect how callers can invoke your API. • You can't use an external definition file to configure your API's IP address type. Change the IP address type of a REST API You can change the IP address type by updating the API’s configuration. You can update the API's configuration by using the AWS Management Console, the AWS CLI, AWS CloudFormation, or an AWS SDK. If you change the API’s IP address type, you don't redeploy your API for the changes to take effect. Before you change the IP address type, confirm that any policies controlling access to your APIs have been updated to account for IPv6 calls. AWS Management Console To change the IP address type of a REST API 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose API settings, and then choose Edit. 4. For IP address type, select either IPv4 or Dualstack. 5. Choose Save changes. The change to your API's configuration will take effect immediately. AWS CLI The following update-rest-api command updates an API to have an IP address type of dualstack: aws apigateway update-rest-api \ --rest-api-id abcd1234 \ --patch-operations "op='replace',path='/endpointConfiguration/ ipAddressType',value='dualstack'" IP address types for REST APIs in API Gateway 295 Amazon API Gateway Developer Guide The output will look like the following: { "id": "abcd1234", "name": "MyAPI", "description": "My API with a dualstack IP address type", "createdDate": "2025-02-04T11:47:06-08:00", "apiKeySource": "HEADER", "endpointConfiguration": { "types": [ "REGIONAL" ], "ipAddressType": "dualstack" }, "tags": {}, "disableExecuteApiEndpoint": false, "rootResourceId": "efg456" } Methods for REST APIs in API Gateway In API Gateway, an API method embodies a method request and a method response. You set up an API method to define what a client should or must do to submit a request to access the service at the backend and to define the responses that the client receives in return. For input, you can choose method request parameters, or an applicable payload, for the client to provide the required or optional data at run time. For output, you determine the method response status code, headers, and applicable body as targets to map the backend response data into, before they are returned to the client. To help the client developer understand the behaviors and the input and output formats of your API, you can document your API and provide proper error messages for invalid requests. An API method request is an HTTP request. To set up the method request, you configure an HTTP method (or verb), the path to an API resource, headers, applicable query string parameters. You also configure a payload when the HTTP method is POST, PUT, or PATCH. For example, to retrieve a pet using the PetStore sample API, you define the API method request of GET /pets/{petId}, where {petId}
apigateway-dg-079
apigateway-dg.pdf
79
the client. To help the client developer understand the behaviors and the input and output formats of your API, you can document your API and provide proper error messages for invalid requests. An API method request is an HTTP request. To set up the method request, you configure an HTTP method (or verb), the path to an API resource, headers, applicable query string parameters. You also configure a payload when the HTTP method is POST, PUT, or PATCH. For example, to retrieve a pet using the PetStore sample API, you define the API method request of GET /pets/{petId}, where {petId} is a path parameter that can take a number at run time. GET /pets/1 Host: apigateway.us-east-1.amazonaws.com ... Methods 296 Amazon API Gateway Developer Guide If the client specifies an incorrect path, for example, /pet/1 or /pets/one instead of /pets/1, an exception is thrown. An API method response is an HTTP response with a given status code. For a non-proxy integration, you must set up method responses to specify the required or optional targets of mappings. These transform integration response headers or body to associated method response headers or body. The mapping can be as simple as an identity transform that passes the headers or body through the integration as-is. For example, the following 200 method response shows an example of passthrough of a successful integration response as-is. 200 OK Content-Type: application/json ... { "id": "1", "type": "dog", "price": "$249.99" } In principle, you can define a method response corresponding to a specific response from the backend. Typically, this involves any 2XX, 4XX, and 5XX responses. However, this may not be practical, because often you may not know in advance all the responses that a backend may return. In practice, you can designate one method response as the default to handle the unknown or unmapped responses from the backend. It is good practice to designate the 500 response as the default. In any case, you must set up at least one method response for non-proxy integrations. Otherwise, API Gateway returns a 500 error response to the client even when the request succeeds at the backend. To support a strongly typed SDK, such as a Java SDK, for your API, you should define the data model for input for the method request, and define the data model for output of the method response. Prerequisites Before setting up an API method, verify the following: • You must have the method available in API Gateway. Follow the instructions in Tutorial: Create a REST API with an HTTP non-proxy integration. Methods 297 Amazon API Gateway Developer Guide • If you want the method to communicate with a Lambda function, you must have already created the Lambda invocation role and Lambda execution role in IAM. You must also have created the Lambda function with which your method will communicate in AWS Lambda. To create the roles and function, use the instructions in Create a Lambda function for Lambda non-proxy integration of the Choose an AWS Lambda integration tutorial. • If you want the method to communicate with an HTTP or HTTP proxy integration, you must have already created, and have access to, the HTTP endpoint URL with which your method will communicate. • Verify that your certificates for HTTP and HTTP proxy endpoints are supported by API Gateway. For details see API Gateway-supported certificate authorities for HTTP and HTTP proxy integrations in API Gateway. Topics • Set up a method request in API Gateway • Set up a method response in API Gateway • Set up a method using the API Gateway console Set up a method request in API Gateway Setting up a method request involves performing the following tasks, after creating a RestApi resource: 1. Creating a new API or choosing an existing API Resource entity. 2. Creating an API Method resource that is a specific HTTP verb on the new or chosen API Resource. This task can be further divided into the following sub tasks: • Adding an HTTP method to the method request • Configuring request parameters • Defining a model for the request body • Enacting an authorization scheme • Enabling request validation You can perform these tasks using the following methods: • API Gateway console Methods 298 Amazon API Gateway Developer Guide • AWS CLI commands (create-resource and put-method) • AWS SDK functions (for example, in Node.js, createResource and putMethod) • API Gateway REST API (resource:create and method:put). Topics • Set up API resources • Set up an HTTP method • Set up method request parameters • Set up a method request model • Set up method request authorization • Set up method request validation Set up API resources In an API Gateway API, you expose addressable resources as a tree of API Resources entities, with the root resource (/)
apigateway-dg-080
apigateway-dg.pdf
80
methods: • API Gateway console Methods 298 Amazon API Gateway Developer Guide • AWS CLI commands (create-resource and put-method) • AWS SDK functions (for example, in Node.js, createResource and putMethod) • API Gateway REST API (resource:create and method:put). Topics • Set up API resources • Set up an HTTP method • Set up method request parameters • Set up a method request model • Set up method request authorization • Set up method request validation Set up API resources In an API Gateway API, you expose addressable resources as a tree of API Resources entities, with the root resource (/) at the top of the hierarchy. The root resource is relative to the API's base URL, which consists of the API endpoint and a stage name. In the API Gateway console, this base URI is referred to as the Invoke URI and is displayed in the API's stage editor after the API is deployed. The API endpoint can be a default host name or a custom domain name. The default host name is of the following format: {api-id}.execute-api.{region}.amazonaws.com In this format, the {api-id} represents the API identifier that is generated by API Gateway. The {region} variable represents the AWS Region (for example, us-east-1) that you chose when creating the API. A custom domain name is any user-friendly name under a valid internet domain. For example, if you have registered an internet domain of example.com, any of *.example.com is a valid custom domain name. For more information, see create a custom domain name. For the PetStore sample API, the root resource (/) exposes the pet store. The /pets resource represents the collection of pets available in the pet store. The /pets/{petId} exposes an individual pet of a given identifier (petId). The path parameter of {petId} is part of the request parameters. Methods 299 Amazon API Gateway Developer Guide To set up an API resource, you choose an existing resource as its parent and then create the child resource under this parent resource. You start with the root resource as a parent, add a resource to this parent, add another resource to this child resource as the new parent, and so on, to its parent identifier. Then you add the named resource to the parent. The following get-resources command retrieves all the resources of an API: aws apigateway get-resources --rest-api-id apiId For the PetStore sample API, the output looks like the following: { "items": [ { "path": "/pets", "resourceMethods": { "GET": {} }, "id": "6sxz2j", "pathPart": "pets", "parentId": "svzr2028x8" }, { "path": "/pets/{petId}", "resourceMethods": { "GET": {} }, "id": "rjkmth", "pathPart": "{petId}", "parentId": "6sxz2j" }, { "path": "/", "id": "svzr2028x8" } ] } Each item lists the identifiers of the resource (id) and, except for the root resource, its immediate parent (parentId), as well as the resource name (pathPart). The root resource is special in that it does not have any parent. After choosing a resource as the parent, use the following command to add a child resource: Methods 300 Amazon API Gateway Developer Guide aws apigateway create-resource --rest-api-id apiId \ --parent-id parentId \ --path-part resourceName For example, to add pet food for sale on the PetStore website, use the following command: aws apigateway create-resource --rest-api-id a1b2c3 \ --parent-id svzr2028x8 \ --path-part food The output will look like the following: { "path": "/food", "pathPart": "food", "id": "xdsvhp", "parentId": "svzr2028x8" } Use a proxy resource to streamline API setup As business grows, the PetStore owner may decide to add food, toys, and other pet-related items for sale. To support this, you can add /food, /toys, and other resources under the root resource. Under each sale category, you may also want to add more resources, such as /food/{type}/ {item}, /toys/{type}/{item}, etc. This can get tedious. If you decide to add a middle layer {subtype} to the resource paths to change the path hierarchy into /food/{type}/{subtype}/ {item}, /toys/{type}/{subtype}/{item}, etc., the changes will break the existing API set up. To avoid this, you can use an API Gateway proxy resource to expose a set of API resources all at once. API Gateway defines a proxy resource as a placeholder for a resource to be specified when the request is submitted. A proxy resource is expressed by a special path parameter of {proxy+}, often referred to as a greedy path parameter. The + sign indicates whichever child resources are appended to it. The /parent/{proxy+} placeholder stands for any resource matching the path pattern of /parent/*. You can use any string for the greedy path parameter name. The following create-resource command creates a proxy resource under the root (/{proxy+}): aws apigateway create-resource --rest-api-id apiId \ Methods 301 Amazon API Gateway Developer Guide --parent-id rootResourceId \ --path-part {proxy+} The output will look like the following: { "path": "/{proxy+}", "pathPart": "{proxy+}", "id": "234jdr", "parentId": "svzr2028x8" } For the PetStore API
apigateway-dg-081
apigateway-dg.pdf
81
a special path parameter of {proxy+}, often referred to as a greedy path parameter. The + sign indicates whichever child resources are appended to it. The /parent/{proxy+} placeholder stands for any resource matching the path pattern of /parent/*. You can use any string for the greedy path parameter name. The following create-resource command creates a proxy resource under the root (/{proxy+}): aws apigateway create-resource --rest-api-id apiId \ Methods 301 Amazon API Gateway Developer Guide --parent-id rootResourceId \ --path-part {proxy+} The output will look like the following: { "path": "/{proxy+}", "pathPart": "{proxy+}", "id": "234jdr", "parentId": "svzr2028x8" } For the PetStore API example, you can use /{proxy+} to represent both the /pets and /pets/ {petId}. This proxy resource can also reference any other (existing or to-be-added) resources, such as /food/{type}/{item}, /toys/{type}/{item}, etc., or /food/{type}/{subtype}/ {item}, /toys/{type}/{subtype}/{item}, etc. The backend developer determines the resource hierarchy and the client developer is responsible for understanding it. API Gateway simply passes whatever the client submitted to the backend. An API can have more than one proxy resource. For example, the following proxy resources are allowed within an API, assuming /parent/{proxy+} is not the same parent as /parent/ {child}/{proxy+}. /{proxy+} /parent/{proxy+} /parent/{child}/{proxy+} When a proxy resource has non-proxy siblings, the sibling resources are excluded from the representation of the proxy resource. For the preceding examples, /{proxy+} refers to any resources under the root resource except for the /parent[/*] resources. In other words, a method request against a specific resource takes precedence over a method request against a generic resource at the same level of the resource hierarchy. The following table shows how API Gateway routes requests to the following resources for the prod stage of an API. ANY /{proxy+} GET /pets/{proxy+} GET /pets/dog Methods 302 Amazon API Gateway Developer Guide Request Selected route Explanation GET https://api- GET /pets/dog id.execute- api. region.amazonaw s.com/prod/pets/dog GET https://api- GET /pets/{proxy+} id.execute- api. region.amazonaw s.com/prod/pets/ca ts GET https://api- GET /{proxy+} id.execute- api. region.amazonaw s.com/prod/animals The request fully matches this resource. The /pets/{proxy+} greedy path variable catches this request. The /{proxy+} greedy path variable catches this request. A proxy resource cannot have any child resource. Any API resource after {proxy+} is redundant and ambiguous. The following proxy resources are not allowed within an API. /{proxy+}/child /parent/{proxy+}/{child} /parent/{child}/{proxy+}/{grandchild+} Set up an HTTP method An API method request is encapsulated by the API Gateway Method resource. To set up the method request, you must first instantiate the Method resource, setting at least an HTTP method and an authorization type on the method. Closely associated with the proxy resource, API Gateway supports an HTTP method of ANY. This ANY method represents any HTTP method that is to be supplied at run time. It allows you to use a single API method setup for all of the supported HTTP methods of DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT. You can set up the ANY method on a non-proxy resource as well. Combining the ANY method with a proxy resource, you get a single API method setup for all of the supported HTTP methods against Methods 303 Amazon API Gateway Developer Guide any resources of an API. Furthermore, the backend can evolve without breaking the existing API setup. Before setting up an API method, consider who can call the method. Set the authorization type according to your plan. For open access, set it to NONE. To use IAM permissions, set the authorization type to AWS_IAM. To use a Lambda authorizer function, set this property to CUSTOM. To use an Amazon Cognito user pool, set the authorization type to COGNITO_USER_POOLS. The following put-method command creates a method request for the ANY verb using IAM permissions to control its access. aws apigateway put-method --rest-api-id vaz7da96z6 \ --resource-id 6sxz2j \ --http-method ANY \ --authorization-type AWS_IAM To create an API method request with a different authorization type, see the section called “Set up method request authorization”. Set up method request parameters Method request parameters are a way for a client to provide input data or execution context necessary to complete the method request. A method parameter can be a path parameter, a header, or a query string parameter. As part of method request setup, you must declare required request parameters to make them available for the client. For non-proxy integration, you can translate these request parameters to a form that is compatible with the backend requirement. For example, for the GET /pets/{petId} method request, the {petId} path variable is a required request parameter. You can declare this path parameter when calling the put-method command of the AWS CLI. The following put-method command creates a method with a required path parameter: aws apigateway put-method --rest-api-id vaz7da96z6 \ --resource-id rjkmth \ --http-method GET \ --authorization-type "NONE" \ --request-parameters method.request.path.petId=true Methods 304 Amazon API Gateway Developer Guide If a parameter is not required, you
apigateway-dg-082
apigateway-dg.pdf
82
make them available for the client. For non-proxy integration, you can translate these request parameters to a form that is compatible with the backend requirement. For example, for the GET /pets/{petId} method request, the {petId} path variable is a required request parameter. You can declare this path parameter when calling the put-method command of the AWS CLI. The following put-method command creates a method with a required path parameter: aws apigateway put-method --rest-api-id vaz7da96z6 \ --resource-id rjkmth \ --http-method GET \ --authorization-type "NONE" \ --request-parameters method.request.path.petId=true Methods 304 Amazon API Gateway Developer Guide If a parameter is not required, you can set it to false in request-parameters. For example, if the GET /pets method uses an optional query string parameter of type, and an optional header parameter of age, you can declare them using the following put-method command: aws apigateway put-method --rest-api-id vaz7da96z6 \ --resource-id 6sxz2j \ --http-method GET \ --authorization-type "NONE" \ --request-parameters method.request.querystring.type=false,method.request.header.age=false Instead of this abbreviated form, you can use a JSON string to set the request-parameters value: '{"method.request.querystring.type":false,"method.request.header.age":false}' With this setup, the client can query pets by type: GET /pets?type=dog And the client can query dogs who are puppies as follows: GET /pets?type=dog age:puppy For information on how to map method request parameters to integration request parameters, see the section called “Integrations”. Set up a method request model For an API method that can take input data in a payload, you can use a model. A model is expressed in a JSON schema draft 4 and describes the data structure of the request body. With a model, a client can determine how to construct a method request payload as input. More importantly, API Gateway uses the model to validate a request, generate an SDK, and initialize a mapping template for setting up the integration in the API Gateway console. For information about how to create a model, see Understanding data models. Depending on the content types, a method payload can have different formats. A model is indexed against the media type of the applied payload. API Gateway uses the Content-Type request Methods 305 Amazon API Gateway Developer Guide header to determine the content type. To set up method request models, add key-value pairs of the "media-type":"model-name" format to the requestModels map when calling the AWS CLI put-method command. To use the same model regardless of the content type, specify $default as the key. For example, to set a model on the JSON payload of the POST /pets method request of the PetStore example API, you can use the following put-method command: aws apigateway put-method \ --rest-api-id vaz7da96z6 \ --resource-id 6sxz2j \ --http-method POST \ --authorization-type "NONE" \ --request-models '{"application/json":"petModel"}' Here, petModel is the name property value of a Model resource describing a pet. The actual schema definition is expressed as a JSON string value of the schema property of the Model resource. In a Java, or other strongly typed SDK, of the API, the input data is cast as the petModel class derived from the schema definition. With the request model, the input data in the generated SDK is cast into the Empty class, which is derived from the default Empty model. In this case, the client cannot instantiate the correct data class to provide the required input. Set up method request authorization To control who can call the API method, you can configure the authorization type on the method. You can use this type to enact one of the supported authorizers, including IAM roles and policies (AWS_IAM), an Amazon Cognito user pool (COGNITO_USER_POOLS), or a Lambda authorizer (CUSTOM). To use IAM permissions to authorize access to the API method, set the authorization-type input property to AWS_IAM. When you set this option, API Gateway verifies the caller's signature on the request based on the caller's credentials. If the verified user has permission to call the method, it accepts the request. Otherwise, it rejects the request and the caller receives an unauthorized error response. The call to the method doesn't succeed unless the caller has permission to invoke the API method. The following IAM policy grants permission to the caller to call any API methods created within the same AWS account: Methods 306 Amazon API Gateway Developer Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": "arn:aws:execute-api:*:*:*" } ] } For more information, see the section called “Use IAM permissions”. Currently, you can only grant this policy to the users, groups, and roles within the API owner's AWS account. Users from a different AWS account can call the API methods only if allowed to assume a role within the API owner's AWS account with the necessary permissions to call the execute- api:Invoke action. For information on cross-account permissions, see Using IAM Roles. You can use AWS CLI, an AWS SDK, or a
apigateway-dg-083
apigateway-dg.pdf
83
Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": "arn:aws:execute-api:*:*:*" } ] } For more information, see the section called “Use IAM permissions”. Currently, you can only grant this policy to the users, groups, and roles within the API owner's AWS account. Users from a different AWS account can call the API methods only if allowed to assume a role within the API owner's AWS account with the necessary permissions to call the execute- api:Invoke action. For information on cross-account permissions, see Using IAM Roles. You can use AWS CLI, an AWS SDK, or a REST API client, such as Postman, which implements Signature Version 4 (SigV4) signing. To use a Lambda authorizer to authorize access to the API method, set the authorization-type input property to CUSTOM and set the authorizer-id input property to the id property value of a Lambda authorizer that already exists. The referenced Lambda authorizer can be of the TOKEN or REQUEST type. For information about creating a Lambda authorizer, see the section called “Use Lambda authorizers”. To use an Amazon Cognito user pool to authorize access to the API method, set the authorization-type input property to COGNITO_USER_POOLS and set the authorizer-id input property to the id property value of the COGNITO_USER_POOLS authorizer that was already created. For information about creating an Amazon Cognito user pool authorizer, see the section called “Use Amazon Cognito user pool as authorizer for a REST API”. Set up method request validation You can enable request validation when setting up an API method request. You need to first create a request validator. The following create-request-validator command creates a body-only request validator. Methods 307 Amazon API Gateway Developer Guide aws apigateway create-request-validator \ --rest-api-id 7zw9uyk9kl \ --name bodyOnlyValidator \ --validate-request-body \ --no-validate-request-parameters The output will look like the following: { "validateRequestParameters": false, "validateRequestBody": true, "id": "jgpyy6", "name": "bodyOnlyValidator" } You can use this request validator, to use request validation as part of the method request setup. The following put-method command creates a method request that requires the incoming request body to match the PetModel and has two request parameter that aren't required: aws apigateway put-method \ --rest-api-id 7zw9uyk9kl \ --resource-id xdsvhp \ --http-method PUT \ --authorization-type "NONE" \ --request-parameters '{"method.request.querystring.type": false, "method.request.querystring.page":false}' \ --request-models '{"application/json":"petModel"}' \ --request-validator-id jgpyy6 To include a request parameter in the request validation, you must set validateRequestParameters to true for the request validator, and set the specific request parameter to true in the put-method command. Set up a method response in API Gateway An API method response encapsulates the output of an API method request that the client will receive. The output data includes an HTTP status code, some headers, and possibly a body. With non-proxy integrations, the specified response parameters and body can be mapped from the associated integration response data or can be assigned certain static values according to Methods 308 Amazon API Gateway Developer Guide mappings. These mappings are specified in the integration response. The mapping can be an identical transformation that passes the integration response through as-is. With a proxy integration, API Gateway passes the backend response through to the method response automatically. There is no need for you to set up the API method response. However, with the Lambda proxy integration, the Lambda function must return a result of this output format for API Gateway to successfully map the integration response to a method response. Programmatically, the method response setup amounts to creating a MethodResponse resource of API Gateway and setting the properties of statusCode, responseParameters, and responseModels. When setting status codes for an API method, you should choose one as the default to handle any integration response of an unanticipated status code. It is reasonable to set 500 as the default because this amounts to casting otherwise unmapped responses as a server-side error. For instructional reasons, the API Gateway console sets the 200 response as the default. But you can reset it to the 500 response. To set up a method response, you must have created the method request. Set up method response status code The status code of a method response defines a type of response. For example, responses of 200, 400, and 500 indicate successful, client-side error and server-side error responses, respectively. To set up a method response status code, set the statusCode property to an HTTP status code. The following put-method-response command creates 200 method response. aws apigateway put-method-response \ --rest-api-id vaz7da96z6 \ --resource-id 6sxz2j \ --http-method GET \ --status-code 200 Set up method response parameters Method response parameters define which headers the client receives in response to the associated method request. Response parameters also specify a target to which API Gateway maps an integration response parameter, according to mappings prescribed in the API method's integration response. Methods 309 Amazon API Gateway Developer Guide
apigateway-dg-084
apigateway-dg.pdf
84
client-side error and server-side error responses, respectively. To set up a method response status code, set the statusCode property to an HTTP status code. The following put-method-response command creates 200 method response. aws apigateway put-method-response \ --rest-api-id vaz7da96z6 \ --resource-id 6sxz2j \ --http-method GET \ --status-code 200 Set up method response parameters Method response parameters define which headers the client receives in response to the associated method request. Response parameters also specify a target to which API Gateway maps an integration response parameter, according to mappings prescribed in the API method's integration response. Methods 309 Amazon API Gateway Developer Guide To set up the method response parameters, add to the responseParameters map of MethodResponse key-value pairs of the "{parameter-name}":"{boolean}" format. The following put-method-response command sets the my-header header. aws apigateway put-method-response \ --rest-api-id vaz7da96z6 \ --resource-id 6sxz2j \ --http-method GET \ --status-code 200 \ --response-parameters method.response.header.my-header=false Set up method response models A method response model defines a format of the method response body. Setting up a method response model is necessary when you generate a strongly typed SDK for the API. It ensures that the output is cast into an appropriate class in Java or Objective-C. In other cases, setting a model is optional. Before setting up the response model, you must first create the model in API Gateway. To do so, you can call the create-model command. The following create-model command creates PetStorePet model to describe the body of the response to the GET /pets/{petId} method request. aws apigateway create-model \ --rest-api-id vaz7da96z6 \ --content-type application/json \ --name PetStorePet \ --schema '{ \ "$schema": "http://json-schema.org/draft-04/schema#", \ "title": "PetStorePet", \ "type": "object", \ "properties": { \ "id": { "type": "number" }, \ "type": { "type": "string" }, \ "price": { "type": "number" } \ } \ }' The result is created as an API Gateway Model resource. Methods 310 Amazon API Gateway Developer Guide To set up the method response models to define the payload format, add the "application/ json":"PetStorePet" key-value pair to the requestModels map of MethodResponse resource. The following put-method-response command creates a method response that uses a response model to define the payload format: aws apigateway put-method-response \ --rest-api-id vaz7da96z6 \ --resource-id 6sxz2j \ --http-method GET \ --status-code 200 \ --response-parameters method.response.header.my-header=false \ --response-models '{"application/json":"PetStorePet"}' Set up a method using the API Gateway console When you create a method using the REST API console, you configure both the integration request and the method request. By default, API Gateway creates the 200 method response for your method. The following instructions show how to edit the method request settings and how to create additional method responses for your method. Topics • Edit an API Gateway method request in the API Gateway console • Set up an API Gateway method response using the API Gateway console Edit an API Gateway method request in the API Gateway console These instructions assume you have already created your method request. For more information on how to create a method, see the section called “ Set up integration request using the console”. 1. 2. 3. In the Resources pane, choose your method, and then choose the Method request tab. In the Method request settings section, choose Edit. For Authorization, select an available authorizer. a. To enable open access to the method for any user, select None. This step can be skipped if the default setting has not been changed. Methods 311 Amazon API Gateway Developer Guide b. To use IAM permissions to control the client access to the method, select AWS_IAM. With this choice, only users of the IAM roles with the correct IAM policy attached are allowed to call this method. To create the IAM role, specify an access policy with a format like the following: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "resource-statement" ] } ] } In this access policy, resource-statement is the ARN of your method. You can find the ARN of your method by selecting the method on the Resources page. For more information about setting the IAM permissions, see Control access to a REST API with IAM permissions. To create the IAM role, you can adapt the instructions in the following tutorial, ???. c. To use a Lambda authorizer, select a token or a request authorizer. Create the Lambda authorizer to have this choice displayed in the dropdown menu. For information on how to create a Lambda authorizer, see Use API Gateway Lambda authorizers. d. To use an Amazon Cognito user pool, choose an available user pool under Cognito user pool authorizers. Create a user pool in Amazon Cognito and an Amazon Cognito user pool authorizer in API Gateway to have this choice displayed in the dropdown menu. For information on how to create an Amazon Cognito user pool authorizer, see
apigateway-dg-085
apigateway-dg.pdf
85
tutorial, ???. c. To use a Lambda authorizer, select a token or a request authorizer. Create the Lambda authorizer to have this choice displayed in the dropdown menu. For information on how to create a Lambda authorizer, see Use API Gateway Lambda authorizers. d. To use an Amazon Cognito user pool, choose an available user pool under Cognito user pool authorizers. Create a user pool in Amazon Cognito and an Amazon Cognito user pool authorizer in API Gateway to have this choice displayed in the dropdown menu. For information on how to create an Amazon Cognito user pool authorizer, see Control access to REST APIs using Amazon Cognito user pools as an authorizer. 4. To specify request validation, select a value from the Request Validator dropdown menu. To turn off request validation, select None. For more information about each option, see Request validation for REST APIs in API Gateway. Methods 312 Amazon API Gateway Developer Guide 5. Select API key required to require an API key. When enabled, API keys are used in usage plans to throttle client traffic. 6. (Optional) To assign an operation name in a Java SDK of this API, generated by API Gateway, for Operation name, enter a name. For example, for the method request of GET /pets/ {petId}, the corresponding Java SDK operation name is, by default ,GetPetsPetId. This name is constructed from the method's HTTP verb (GET) and the resource path variable names (Pets and PetId). If you set the operation name as getPetById, the SDK operation name becomes GetPetById. 7. To add a query string parameter to the method, do the following: a. b. c. d. Choose URL Query string parameters, and then choose Add query string. For Name, enter the name of the query string parameter. Select Required if the newly created query string parameter is to be used for request validation. For more information about the request validation, see Request validation for REST APIs in API Gateway. Select Caching if the newly created query string parameter is to be used as part of a caching key. For more information about caching, see Use method or integration parameters as cache keys to index cached responses. To remove the query string parameter, choose Remove. 8. To add a header parameter to the method, do the following: a. b. c. d. Choose HTTP request headers, and then choose Add header. For Name, enter the name of the header. Select Required if the newly created header is to be used for request validation. For more information about the request validation, see Request validation for REST APIs in API Gateway. Select Caching if the newly created header is to be used as part of a caching key. For more information about caching, see Use method or integration parameters as cache keys to index cached responses. To remove the header, choose Remove. 9. To declare the payload format of a method request with the POST, PUT, or PATCH HTTP verb, choose Request body, and do the following: Methods 313 Amazon API Gateway Developer Guide a. b. c. Choose Add model. For Content-type, enter a MIME-type (for example, application/json). For Model, select a model from the dropdown menu. The currently available models for the API include the default Empty and Error models as well as any models you have created and added to the Models collection of the API. For more information about creating a model, see Data models for REST APIs. Note The model is useful to inform the client of the expected data format of a payload. It is helpful to generate a skeletal mapping template. It is important to generate a strongly typed SDK of the API in such languages as Java, C#, Objective-C, and Swift. It is only required if request validation is enabled against the payload. 10. Choose Save. Set up an API Gateway method response using the API Gateway console An API method can have one or more responses. Each response is indexed by its HTTP status code. By default, the API Gateway console adds 200 response to the method responses. You can modify it, for example, to have the method return 201 instead. You can add other responses, for example, 409 for access denial and 500 for uninitialized stage variables used. To use the API Gateway console to modify, delete, or add a response to an API method, follow these instructions. 1. 2. 3. In the Resources pane, choose your method, and then choose the Method response tab. You might need to choose the right arrow button to show the tab. In the Method response settings section, choose Create response. For HTTP status code, enter an HTTP status code such as 200, 400, or 500. When a backend-returned response does not have a corresponding method response defined, API Gateway fails to
apigateway-dg-086
apigateway-dg.pdf
86
for access denial and 500 for uninitialized stage variables used. To use the API Gateway console to modify, delete, or add a response to an API method, follow these instructions. 1. 2. 3. In the Resources pane, choose your method, and then choose the Method response tab. You might need to choose the right arrow button to show the tab. In the Method response settings section, choose Create response. For HTTP status code, enter an HTTP status code such as 200, 400, or 500. When a backend-returned response does not have a corresponding method response defined, API Gateway fails to return the response to the client. Instead, it returns a 500 Internal server error error response. 4. Choose Add header. 5. For Header name, enter a name. Methods 314 Amazon API Gateway Developer Guide To return a header from the backend to the client, add the header in the method response. 6. Choose Add model to define a format of the method response body. Enter the media type of the response payload for Content type and choose a model from the Models dropdown menu. 7. Choose Save. To modify an existing response, navigate to your method response, and then choose Edit. To change the HTTP status code, choose Delete and create a new method response. For every response returned from the backend, you must have a compatible response configured as the method response. However, the configuring method response headers and payload model are optional unless you map the result from the backend to the method response before returning to the client. Also, a method response payload model is important if you are generating a strongly typed SDK for your API. Control and manage access to REST APIs in API Gateway API Gateway supports multiple mechanisms for controlling and managing access to your API. You can use the following mechanisms for authentication and authorization: • Resource policies let you create resource-based policies to allow or deny access to your APIs and methods from specified source IP addresses or VPC endpoints. For more information, see the section called “Use API Gateway resource policies”. • Standard AWS IAM roles and policies offer flexible and robust access controls that can be applied to an entire API or individual methods. IAM roles and policies can be used for controlling who can create and manage your APIs, as well as who can invoke them. For more information, see the section called “Use IAM permissions”. • IAM tags can be used together with IAM policies to control access. For more information, see the section called “Attribute-based access control”. • Endpoint policies for interface VPC endpoints allow you to attach IAM resource policies to interface VPC endpoints to improve the security of your private APIs. For more information, see the section called “Use VPC endpoint policies for private APIs”. • Lambda authorizers are Lambda functions that control access to REST API methods using bearer token authentication—as well as information described by headers, paths, query strings, stage Access control 315 Amazon API Gateway Developer Guide variables, or context variables request parameters. Lambda authorizers are used to control who can invoke REST API methods. For more information, see the section called “Use Lambda authorizers”. • Amazon Cognito user pools let you create customizable authentication and authorization solutions for your REST APIs. Amazon Cognito user pools are used to control who can invoke REST API methods. For more information, see the section called “Use Amazon Cognito user pool as authorizer for a REST API”. You can use the following mechanisms for performing other tasks related to access control: • Cross-origin resource sharing (CORS) lets you control how your REST API responds to cross- domain resource requests. For more information, see the section called “CORS”. • Client-side SSL certificates can be used to verify that HTTP requests to your backend system are from API Gateway. For more information, see the section called “Client certificates”. • AWS WAF can be used to protect your API Gateway API from common web exploits. For more information, see the section called “AWS WAF”. You can use the following mechanisms for tracking and limiting the access that you have granted to authorized clients: • Usage plans let you provide API keys to your customers—and then track and limit usage of your API stages and methods for each API key. For more information, see the section called “Usage plans”. Control access to a REST API with API Gateway resource policies Amazon API Gateway resource policies are JSON policy documents that you attach to an API to control whether a specified principal (typically an IAM role or group) can invoke the API. You can use API Gateway resource policies to allow your API to be securely invoked by: • Users from a specified AWS account. • Specified source IP
apigateway-dg-087
apigateway-dg.pdf
87
you provide API keys to your customers—and then track and limit usage of your API stages and methods for each API key. For more information, see the section called “Usage plans”. Control access to a REST API with API Gateway resource policies Amazon API Gateway resource policies are JSON policy documents that you attach to an API to control whether a specified principal (typically an IAM role or group) can invoke the API. You can use API Gateway resource policies to allow your API to be securely invoked by: • Users from a specified AWS account. • Specified source IP address ranges or CIDR blocks. • Specified virtual private clouds (VPCs) or VPC endpoints (in any account). Access control 316 Amazon API Gateway Developer Guide You can attach a resource policy for any API endpoint type in API Gateway by using the AWS Management Console, AWS CLI, or AWS SDKs. For private APIs, you can use resource policies together with VPC endpoint policies to control which principals have access to which resources and actions. For more information, see the section called “Use VPC endpoint policies for private APIs”. API Gateway resource policies are different from IAM identity-based policies. IAM identity-based policies are attached to IAM users, groups, or roles and define what actions those identities are capable of doing on which resources. API Gateway resource policies are attached to resources. You can use API Gateway resource policies together with IAM policies. For more information, see Identity-Based Policies and Resource-Based Policies. Topics • Access policy language overview for Amazon API Gateway • How API Gateway resource policies affect authorization workflow • API Gateway resource policy examples • Create and attach an API Gateway resource policy to an API • AWS condition keys that can be used in API Gateway resource policies Access policy language overview for Amazon API Gateway This page describes the basic elements used in Amazon API Gateway resource policies. Resource policies are specified using the same syntax as IAM policies. For complete policy language information, see Overview of IAM Policies and AWS Identity and Access Management Policy Reference in the IAM User Guide. For information about how an AWS service decides whether a given request should be allowed or denied, see Determining Whether a Request is Allowed or Denied. Common elements in an access policy In its most basic sense, a resource policy contains the following elements: • Resources – APIs are the Amazon API Gateway resources for which you can allow or deny permissions. In a policy, you use the Amazon Resource Name (ARN) to identify the resource. You can also use abbreviated syntax, which API Gateway automatically expands to the full ARN when you save a resource policy. To learn more, see API Gateway resource policy examples. Access control 317 Amazon API Gateway Developer Guide For the format of the full Resource element, see Resource format of permissions for executing API in API Gateway. • Actions – For each resource, Amazon API Gateway supports a set of operations. You identify resource operations that you will allow (or deny) by using action keywords. For example, the execute-api:Invoke permission will allow the user permission to invoke an API upon a client request. For the format of the Action element, see Action format of permissions for executing API in API Gateway. • Effect – What the effect is when the user requests the specific action—this can be either Allow or Deny. You can also explicitly deny access to a resource, which you might do in order to make sure that a user cannot access it, even if a different policy grants access. Note "Implicit deny" is the same thing as "deny by default". An "implicit deny" is different from an "explicit deny". For more information, see The Difference Between Denying by Default and Explicit Deny. • Principal – The account or user allowed access to the actions and resources in the statement. In a resource policy, the principal is the user or account who receives this permission. The following example resource policy shows the previous common policy elements. The policy grants access to the API under the specified account-id in the specified region to any user whose source IP address is in the address block 123.4.5.6/24. The policy denies all access to the API if the user's source IP is not within the range. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:region:account-id:*" }, { Access control 318 Amazon API Gateway Developer Guide "Effect": "Deny", "Principal": "*", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:region:account-id:*", "Condition": { "NotIpAddress": { "aws:SourceIp": "123.4.5.6/24" } } } ] } How API Gateway resource policies affect authorization workflow When API Gateway evaluates the resource policy attached to your API, the result is affected by the authentication type that you have defined for
apigateway-dg-088
apigateway-dg.pdf
88
address is in the address block 123.4.5.6/24. The policy denies all access to the API if the user's source IP is not within the range. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:region:account-id:*" }, { Access control 318 Amazon API Gateway Developer Guide "Effect": "Deny", "Principal": "*", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:region:account-id:*", "Condition": { "NotIpAddress": { "aws:SourceIp": "123.4.5.6/24" } } } ] } How API Gateway resource policies affect authorization workflow When API Gateway evaluates the resource policy attached to your API, the result is affected by the authentication type that you have defined for the API, as illustrated in the flowcharts in the following sections. Topics • API Gateway resource policy only • Lambda authorizer and resource policy • IAM authentication and resource policy • Amazon Cognito authentication and resource policy • Policy evaluation outcome tables API Gateway resource policy only In this workflow, an API Gateway resource policy is attached to the API, but no authentication type is defined for the API. Evaluation of the policy involves seeking an explicit allow based on the inbound criteria of the caller. An implicit denial or any explicit denial results in denying the caller. Access control 319 Amazon API Gateway Developer Guide The following is an example of such a resource policy. { "Version": "2012-10-17", "Statement": [ { Access control 320 Amazon API Gateway Developer Guide "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:region:account-id:api-id/", "Condition": { "IpAddress": { "aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ] } } } ] } Lambda authorizer and resource policy In this workflow, a Lambda authorizer is configured for the API in addition to a resource policy. The resource policy is evaluated in two phases. Before calling the Lambda authorizer, API Gateway first evaluates the policy and checks for any explicit denials. If found, the caller is denied access immediately. Otherwise, the Lambda authorizer is called, and it returns a policy document, which is evaluated in conjunction with the resource policy. The result is determined based on Table A. The following example resource policy allows calls only from the VPC endpoint whose VPC endpoint ID is vpce-1a2b3c4d. During the "pre-auth" evaluation, only the calls coming from the VPC endpoint indicated in the example are allowed to move forward and evaluate the Lambda authorizer. All remaining calls are blocked. Access control 321 Amazon API Gateway Developer Guide Access control 322 Amazon API Gateway Developer Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Deny", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "arn:aws:execute-api:region:account-id:api-id/" ], "Condition" : { "StringNotEquals": { "aws:SourceVpce": "vpce-1a2b3c4d" } } } ] } IAM authentication and resource policy In this workflow, you configure IAM authentication for the API in addition to a resource policy. After you authenticate the user with the IAM service, the API evaluates both the policies attached to the user and the resource policy. The outcome varies based on whether the caller is in the same AWS account or a separate AWS account, from the API owner. If the caller and API owner are from separate accounts, both the IAM policies and the resource policy explicitly allow the caller to proceed. For more information, see Table B. However, if the caller and the API owner are in the same AWS account, then either the IAM user policies or the resource policy must explicitly allow the caller to proceed. For more information, see Table A. Access control 323 Amazon API Gateway Developer Guide The following is an example of a cross-account resource policy. Assuming the IAM policy contains an allow effect, this resource policy allows calls only from the VPC whose VPC ID is vpc-2f09a348. For more information, see Table B. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", Access control 324 Amazon API Gateway "Resource": [ "arn:aws:execute-api:region:account-id:api-id/" ], "Condition" : { "StringEquals": { "aws:SourceVpc": "vpc-2f09a348" Developer Guide } } } ] } Amazon Cognito authentication and resource policy In this workflow, an Amazon Cognito user pool is configured for the API in addition to a resource policy. API Gateway first attempts to authenticate the caller through Amazon Cognito. This is typically performed through a JWT token that is provided by the caller. If authentication is successful, the resource policy is evaluated independently, and an explicit allow is required. A deny or "neither allow or deny" results in a deny. The following is an example of a resource policy that might be used together with Amazon Cognito user pools. Access control 325 Amazon API Gateway Developer Guide Access control 326 Amazon API Gateway Developer Guide The following is an example of a resource policy that allows calls only from specified source IPs, assuming that the Amazon Cognito authentication token contains an allow. For more information, see Table B. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action":
apigateway-dg-089
apigateway-dg.pdf
89
policy is evaluated independently, and an explicit allow is required. A deny or "neither allow or deny" results in a deny. The following is an example of a resource policy that might be used together with Amazon Cognito user pools. Access control 325 Amazon API Gateway Developer Guide Access control 326 Amazon API Gateway Developer Guide The following is an example of a resource policy that allows calls only from specified source IPs, assuming that the Amazon Cognito authentication token contains an allow. For more information, see Table B. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:region:account-id:api-id/", "Condition": { "IpAddress": { "aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ] } } } ] } Policy evaluation outcome tables Table A lists the resulting behavior when access to an API Gateway API is controlled by an IAM policy or a Lambda authorizer and an API Gateway resource policy, both of which are in the same AWS account. IAM policy (or Lambda authorizer) Allow Allow Allow Neither Allow nor Deny API Gateway resource policy Resulting behavior Allow Neither Allow nor Deny Deny Allow Allow Allow Explicit Deny Allow Neither Allow nor Deny Neither Allow nor Deny Implicit Deny Neither Allow nor Deny Deny Explicit Deny Access control 327 Amazon API Gateway Developer Guide IAM policy (or Lambda authorizer) API Gateway resource policy Resulting behavior Deny Deny Deny Allow Explicit Deny Neither Allow nor Deny Explicit Deny Deny Explicit Deny Table B lists the resulting behavior when access to an API Gateway API is controlled by an IAM policy or a Amazon Cognito user pools authorizer and an API Gateway resource policy, which are in different AWS accounts. If either is silent (neither allow nor deny), cross-account access is denied. This is because cross-account access requires that both the resource policy and the IAM policy or Amazon Cognito user pools authorizer explicitly grant access. IAM policy (or Amazon Cognito user pools authorize API Gateway resource policy Resulting behavior r) Allow Allow Allow Neither Allow nor Deny Allow Allow Neither Allow nor Deny Implicit Deny Deny Allow Explicit Deny Implicit Deny Neither Allow nor Deny Neither Allow nor Deny Implicit Deny Neither Allow nor Deny Deny Deny Deny Deny Allow Explicit Deny Explicit Deny Neither Allow nor Deny Explicit Deny Deny Explicit Deny Access control 328 Amazon API Gateway Developer Guide API Gateway resource policy examples This page presents a few examples of typical use cases for API Gateway resource policies. The following example policies use a simplified syntax to specify the API resource. This simplified syntax is an abbreviated way that you can refer to an API resource, instead of specifying the full Amazon Resource Name (ARN). API Gateway converts the abbreviated syntax to the full ARN when you save the policy. For example, you can specify the resource execute-api:/stage- name/GET/pets in a resource policy. API Gateway converts the resource to arn:aws:execute- api:us-east-2:123456789012:aabbccddee/stage-name/GET/pets when you save the resource policy. API Gateway builds the full ARN by using the current Region, your AWS account ID, and the ID of the REST API that the resource policy is associated with. You can use execute- api:/* to represent all stages, methods, and paths in the current API. For information about access policy language, see Access policy language overview for Amazon API Gateway. Topics • Example: Allow roles in another AWS account to use an API • Example: Deny API traffic based on source IP address or range • Example: Deny API traffic based on source IP address or range when using a private API • Example: Allow private API traffic based on source VPC or VPC endpoint Example: Allow roles in another AWS account to use an API The following example resource policy grants API access in one AWS account to two roles in a different AWS account via Signature Version 4 (SigV4) protocols. Specifically, the developer and the administrator role for the AWS account identified by account-id-2 are granted the execute- api:Invoke action to execute the GET action on the pets resource (API) in your AWS account. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::account-id-2:role/developer", "arn:aws:iam::account-id-2:role/Admin" ] }, Access control 329 Amazon API Gateway Developer Guide "Action": "execute-api:Invoke", "Resource": [ "execute-api:/stage/GET/pets" ] } ] } Example: Deny API traffic based on source IP address or range The following example resource policy denies (blocks) incoming traffic to an API from two specified source IP address blocks. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ] }, { "Effect": "Deny", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ], "Condition" : { "IpAddress": { "aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ] } } } ] } If you use any IAM user policies or API Gateway resource policies to control access to API Gateway or any API
apigateway-dg-090
apigateway-dg.pdf
90
"Resource": [ "execute-api:/stage/GET/pets" ] } ] } Example: Deny API traffic based on source IP address or range The following example resource policy denies (blocks) incoming traffic to an API from two specified source IP address blocks. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ] }, { "Effect": "Deny", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ], "Condition" : { "IpAddress": { "aws:SourceIp": ["192.0.2.0/24", "198.51.100.0/24" ] } } } ] } If you use any IAM user policies or API Gateway resource policies to control access to API Gateway or any API Gateway APIs, confirm that your policies are updated to include IPv6 address ranges. Policies that aren’t updated to handle IPv6 addresses might impact client’s access to API Gateway Access control 330 Amazon API Gateway Developer Guide when they start using the dualstack endpoint. For more information, see the section called “Using IPv6 addresses in IAM policies”. Example: Deny API traffic based on source IP address or range when using a private API The following example resource policy denies (blocks) incoming traffic to a private API from two specified source IP address blocks. When using private APIs, the VPC endpoint for execute-api re-writes the original source IP address. The aws:VpcSourceIp condition filters the request against the original requester IP address. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ] }, { "Effect": "Deny", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ], "Condition" : { "IpAddress": { "aws:VpcSourceIp": ["192.0.2.0/24", "198.51.100.0/24"] } } } ] } Example: Allow private API traffic based on source VPC or VPC endpoint The following example resource policies allow incoming traffic to a private API only from a specified virtual private cloud (VPC) or VPC endpoint. This example resource policy specifies a source VPC: Access control 331 Amazon API Gateway Developer Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ] }, { "Effect": "Deny", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ], "Condition" : { "StringNotEquals": { "aws:SourceVpc": "vpc-1a2b3c4d" } } } ] } This example resource policy specifies a source VPC endpoint: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ] }, { "Effect": "Deny", "Principal": "*", Access control 332 Amazon API Gateway Developer Guide "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ], "Condition" : { "StringNotEquals": { "aws:SourceVpce": "vpce-1a2b3c4d" } } } ] } Create and attach an API Gateway resource policy to an API To allow a user to access your API by calling the API execution service, you must create an API Gateway resource policy and attach the policy to the API. When you attach a policy to your API, it applies the permissions in the policy to the methods in the API. If you update the resource policy, you'll need to deploy the API. Topics • Prerequisites • Attach a resource policy to an API Gateway API • Troubleshoot your resource policy Prerequisites To update an API Gateway resource policy, you'll need the apigateway:UpdateRestApiPolicy permission and the apigateway:PATCH permission. For an edge-optimized or Regional API, you can attach your resource policy to your API as you create it, or after it has been deployed. For a private API, you can't deploy your API without a resource policy. For more information, see the section called “Private REST APIs”. Attach a resource policy to an API Gateway API The following procedure shows you how to attach a resource policy to an API Gateway API. Access control 333 Amazon API Gateway AWS Management Console To attach a resource policy to an API Gateway API Developer Guide 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. In the main navigation pane, choose Resource policy. 4. Choose Create policy. 5. (Optional) Choose Select a template to generate an example policy. In the example policies, placeholders are enclosed in double curly braces ("{{placeholder}}"). Replace each of the placeholders, including the curly braces, with the necessary information. 6. If you don't use one of the template examples, enter your resource policy. 7. Choose Save changes. If the API has been deployed previously in the API Gateway console, you'll need to redeploy it for the resource policy to take effect. AWS CLI To use the AWS CLI to create a new API and attach a resource policy to it, use the following create-rest-api command: aws apigateway create-rest-api \ --name "api-name" \ --policy "{\"jsonEscapedPolicyDocument\"}" To use the AWS CLI to attach a resource policy to an existing API, use the following update-rest- api command: aws apigateway update-rest-api \ --rest-api-id api-id \ --patch-operations op=replace,path=/ policy,value='"{\"jsonEscapedPolicyDocument\"}"' You can also attach your resource policy as a separate policy.json file and including it in your create-rest-api command. The following
apigateway-dg-091
apigateway-dg.pdf
91
the API Gateway console, you'll need to redeploy it for the resource policy to take effect. AWS CLI To use the AWS CLI to create a new API and attach a resource policy to it, use the following create-rest-api command: aws apigateway create-rest-api \ --name "api-name" \ --policy "{\"jsonEscapedPolicyDocument\"}" To use the AWS CLI to attach a resource policy to an existing API, use the following update-rest- api command: aws apigateway update-rest-api \ --rest-api-id api-id \ --patch-operations op=replace,path=/ policy,value='"{\"jsonEscapedPolicyDocument\"}"' You can also attach your resource policy as a separate policy.json file and including it in your create-rest-api command. The following create-rest-api command creates a new API with a resource policy: Access control 334 Amazon API Gateway Developer Guide aws apigateway create-rest-api \ --name "api-name" \ --policy file://policy.json policy.json is an API Gateway resource policy, such as the section called “Example: Deny API traffic based on source IP address or range”. AWS CloudFormation You can use AWS CloudFormation to create an API with a resource policy. The following example creates a REST API with the example resource policy, the section called “Example: Deny API traffic based on source IP address or range”. AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Name: testapi Policy: Statement: - Action: 'execute-api:Invoke' Effect: Allow Principal: '*' Resource: 'execute-api:/*' - Action: 'execute-api:Invoke' Effect: Deny Principal: '*' Resource: 'execute-api:/*' Condition: IpAddress: 'aws:SourceIp': ["192.0.2.0/24", "198.51.100.0/24" ] Version: 2012-10-17 Resource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'helloworld' MethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api Access control 335 Amazon API Gateway Developer Guide ResourceId: !Ref Resource HttpMethod: GET ApiKeyRequired: false AuthorizationType: NONE Integration: Type: MOCK RequestTemplates: application/json: '{"statusCode": 200}' IntegrationResponses: - StatusCode: 200 ResponseTemplates: application/json: '{}' MethodResponses: - StatusCode: 200 ResponseModels: application/json: 'Empty' ApiDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: - MethodGet Properties: RestApiId: !Ref Api StageName: test Troubleshoot your resource policy The following troubleshooting guidance might help resolve issues with your resource policy. My API returns {"Message":"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-east-1:********/****/****/"} In your resource policy, if you set the Principal to an AWS principal, such as the following: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", ""Principal": { "AWS": [ "arn:aws:iam::account-id:role/developer", "arn:aws:iam::account-id:role/Admin" ] Access control 336 Amazon API Gateway }, "Action": "execute-api:Invoke", "Resource": [ "execute-api:/*" ] }, ... } Developer Guide You must use AWS_IAM authorization for every method in your API, or else your API returns the previous error message. For more instructions on how to turn on AWS_IAM authorization for a method, see the section called “Methods”. My resource policy is not updating If you update the resource policy after the API is created, you'll need to deploy the API to propagate the changes after you've attached the updated policy. Updating or saving the policy alone won't change the runtime behavior of the API. For more information about deploying your API, see the section called “Deploy REST APIs”. My resource policy returns the following error: Invalid policy document. Please check the policy syntax and ensure that Principals are valid. To troubleshoot this error, we first recommend that you check the policy syntax. For more information, see the section called “Access policy language overview for Amazon API Gateway”. We also recommend that you check that all the principals specified are valid and haven’t been deleted. In addition, if your API is in an opt-in Region, verify that all accounts in the resource policy have the Region enabled. AWS condition keys that can be used in API Gateway resource policies The following table contains AWS condition keys that can be used in resource policies for APIs in API Gateway for each authorization type. For more information about AWS condition keys, see AWS Global Condition Context Keys. Condition keys Criteria Needs AuthN? Authorization type aws:CurrentTime None aws:EpochTime None No No All All Access control 337 Amazon API Gateway Developer Guide Condition keys Criteria Needs AuthN? Authorization type aws:Token IssueTime aws:Multi FactorAut hPresent Key is present only in requests that are signed using temporary security credentials. Key is present only in requests that are signed using temporary security credentials. Yes IAM Yes IAM aws:Multi FactorAuthAge Key is present only if MFA is present in the Yes Yes Yes Yes aws:Princ ipalAccount aws:Princ ipalArn aws:Princ ipalOrgID aws:Princ ipalOrgPaths requests. None None This key is included in the request context only if the principal is a member of an organization. This key is included in the request context only if the principal is a member of an organization. IAM IAM IAM IAM Yes IAM Access control 338 Amazon API Gateway Developer Guide Condition keys Criteria Needs AuthN? Authorization type aws:Princ ipalTag This key is included in the request context Yes if the principal is using an IAM user with attached tags. It is included for a principal using an IAM role with attached tags or session tags. None
apigateway-dg-092
apigateway-dg.pdf
92
ipalOrgPaths requests. None None This key is included in the request context only if the principal is a member of an organization. This key is included in the request context only if the principal is a member of an organization. IAM IAM IAM IAM Yes IAM Access control 338 Amazon API Gateway Developer Guide Condition keys Criteria Needs AuthN? Authorization type aws:Princ ipalTag This key is included in the request context Yes if the principal is using an IAM user with attached tags. It is included for a principal using an IAM role with attached tags or session tags. None Key is present only if the value is provided by the caller in the HTTP header. None None None This key can be used only for private APIs. This key can be used only for private APIs. This key can be used only for private APIs. Yes No No No No No No No aws:Princ ipalType aws:Referer aws:Secur eTransport aws:SourceArn aws:SourceIp aws:SourceVpc aws:SourceVpce aws:VpcSourceIp IAM IAM All All All All All All All Access control 339 Amazon API Gateway Developer Guide Condition keys Criteria Needs AuthN? Authorization type aws:UserAgent Key is present only if the value is provided by the caller in the HTTP header. aws:userid aws:username None None No Yes Yes All IAM IAM Control access to a REST API with IAM permissions You control access to your Amazon API Gateway API with IAM permissions by controlling access to the following two API Gateway component processes: • To create, deploy, and manage an API in API Gateway, you must grant the API developer permissions to perform the required actions supported by the API management component of API Gateway. • To call a deployed API or to refresh the API caching, you must grant the API caller permissions to perform required IAM actions supported by the API execution component of API Gateway. The access control for the two processes involves different permissions models, explained next. API Gateway permissions model for creating and managing an API To allow an API developer to create and manage an API in API Gateway, you must create IAM permissions policies that allow a specified API developer to create, update, deploy, view, or delete required API entities. You attach the permissions policy to a user, role, or group. To provide access, add permissions to your users, groups, or roles: • Users and groups in AWS IAM Identity Center: Create a permission set. Follow the instructions in Create a permission set in the AWS IAM Identity Center User Guide. • Users managed in IAM through an identity provider: Access control 340 Amazon API Gateway Developer Guide Create a role for identity federation. Follow the instructions in Create a role for a third-party identity provider (federation) in the IAM User Guide. • IAM users: • Create a role that your user can assume. Follow the instructions in Create a role for an IAM user in the IAM User Guide. • (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in Adding permissions to a user (console) in the IAM User Guide. For more information on how to use this permissions model, see the section called “API Gateway identity-based policies”. API Gateway permissions model for invoking an API To allow an API caller to invoke the API or refresh its caching, you must create IAM policies that permit a specified API caller to invoke the API method for which user authentication is enabled. The API developer sets the method's authorizationType property to AWS_IAM to require that the caller submit the user's credentials to be authenticated. Then, you attach the policy to a user, role, or group. In this IAM permissions policy statement, the IAM Resource element contains a list of deployed API methods identified by given HTTP verbs and API Gateway resource paths. The IAM Action element contains the required API Gateway API executing actions. These actions include execute- api:Invoke or execute-api:InvalidateCache, where execute-api designates the underlying API execution component of API Gateway. For more information on how to use this permissions model, see Control access for invoking an API. When an API is integrated with an AWS service (for example, AWS Lambda) in the back end, API Gateway must also have permissions to access integrated AWS resources (for example, invoking a Lambda function) on behalf of the API caller. To grant these permissions, create an IAM role of the AWS service for API Gateway type. When you create this role in the IAM Management console, this resulting role contains the following IAM trust policy that declares API Gateway as a trusted entity permitted to assume the role: { "Version": "2012-10-17", "Statement": [ { Access control 341 Amazon API Gateway "Sid": "", "Effect": "Allow", "Principal": { "Service": "apigateway.amazonaws.com"
apigateway-dg-093
apigateway-dg.pdf
93
service (for example, AWS Lambda) in the back end, API Gateway must also have permissions to access integrated AWS resources (for example, invoking a Lambda function) on behalf of the API caller. To grant these permissions, create an IAM role of the AWS service for API Gateway type. When you create this role in the IAM Management console, this resulting role contains the following IAM trust policy that declares API Gateway as a trusted entity permitted to assume the role: { "Version": "2012-10-17", "Statement": [ { Access control 341 Amazon API Gateway "Sid": "", "Effect": "Allow", "Principal": { "Service": "apigateway.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } Developer Guide If you create the IAM role by calling the create-role command of CLI or a corresponding SDK method, you must supply the above trust policy as the input parameter of assume-role- policy-document. Do not attempt to create such a policy directly in the IAM Management console or calling AWS CLI create-policy command or a corresponding SDK method. For API Gateway to call the integrated AWS service, you must also attach to this role appropriate IAM permissions policies for calling integrated AWS services. For example, to call a Lambda function, you must include the following IAM permissions policy in the IAM role: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": "*" } ] } Note that Lambda supports resource-based access policy, which combines both trust and permissions policies. When integrating an API with a Lambda function using the API Gateway console, you are not asked to set this IAM role explicitly, because the console sets the resource- based permissions on the Lambda function for you, with your consent. Note To enact access control to an AWS service, you can use either the caller-based permissions model, where a permissions policy is directly attached to the caller's user or group, or the role-based permission model, where a permissions policy is attached to an IAM role that API Gateway can assume. The permissions policies may differ in the two models. For Access control 342 Amazon API Gateway Developer Guide example, the caller-based policy blocks the access while the role-based policy allows it. You can take advantage of this to require that a user access an AWS service through an API Gateway API only. Control access for invoking an API In this section, you learn about the permissions model for controlling access to your API using IAM permissions. We show a template IAM policy statement and the policy statement reference. The policy statement reference includes the formats of Action and Resource fields related to the API execution service. Use these references to create your IAM policy statement. When you create your IAM policy statement, you might need to consider the how API Gateway resource policies affect the authorization workflow. For more information, see the section called “How resource policies affect authorization workflow”. For private APIs, you should use a combination of an API Gateway resource policy and a VPC endpoint policy. For more information, see the following topics: • the section called “Use API Gateway resource policies” • the section called “Use VPC endpoint policies for private APIs” Control who can call an API Gateway API method with IAM policies To control who can or cannot call a deployed API with IAM permissions, create an IAM policy document with required permissions. A template for such a policy document is shown as follows. { "Version": "2012-10-17", "Statement": [ { "Effect": "Permission", "Action": [ "execute-api:Execution-operation" ], "Resource": [ "arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource- path" ] } ] Access control 343 Amazon API Gateway } Developer Guide Here, Permission is to be replaced by Allow or Deny depending on whether you want to grant or revoke the included permissions. Execution-operation is to be replaced by the operations supported by the API execution service. METHOD_HTTP_VERB stands for a HTTP verb supported by the specified resources. Resource-path is the placeholder for the URL path of a deployed API Resource instance supporting the said METHOD_HTTP_VERB. For more information, see Statement reference of IAM policies for executing API in API Gateway. Note For IAM policies to be effective, you must have enabled IAM authentication on API methods by setting AWS_IAM for the methods' authorizationType property. Failing to do so will make these API methods publicly accessible. For example, to grant a user permission to view a list of pets exposed by a specified API, but to deny the user permission to add a pet to the list, you could include the following statement in the IAM policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:account-id:api-id/*/GET/pets" ] }, { "Effect": "Deny", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:account-id:api-id/*/POST/pets" ] } Access control 344 Amazon API Gateway ] } Developer Guide To grant a user permission to view a specific
apigateway-dg-094
apigateway-dg.pdf
94
Failing to do so will make these API methods publicly accessible. For example, to grant a user permission to view a list of pets exposed by a specified API, but to deny the user permission to add a pet to the list, you could include the following statement in the IAM policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:account-id:api-id/*/GET/pets" ] }, { "Effect": "Deny", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:account-id:api-id/*/POST/pets" ] } Access control 344 Amazon API Gateway ] } Developer Guide To grant a user permission to view a specific pet exposed by an API that is configured as GET / pets/{petId}, you could include the following statement in the IAM policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:account-id:api-id/*/GET/pets/a1b2" ] } ] } Statement reference of IAM policies for executing API in API Gateway The following information describes the Action and Resource format of IAM policy statements of access permissions for executing an API. Action format of permissions for executing API in API Gateway The API-executing Action expression has the following general format: execute-api:action where action is an available API-executing action: • *, which represents all of the following actions. • Invoke, used to invoke an API upon a client request. • InvalidateCache, used to invalidate API cache upon a client request. Resource format of permissions for executing API in API Gateway The API-executing Resource expression has the following general format: Access control 345 Amazon API Gateway Developer Guide arn:aws:execute-api:region:account-id:api-id/stage-name/HTTP-VERB/resource-path- specifier where: • region is the AWS region (such as us-east-1 or * for all AWS regions) that corresponds to the deployed API for the method. • account-id is the 12-digit AWS account Id of the REST API owner. • api-id is the identifier API Gateway has assigned to the API for the method. • stage-name is the name of the stage associated with the method. • HTTP-VERB is the HTTP verb for the method. It can be one of the following: GET, POST, PUT, DELETE, PATCH. • resource-path-specifier is the path to the desired method. Note If you specify a wildcard (*), the Resource expression applies the wildcard to the rest of the expression. Some example resource expressions include: • arn:aws:execute-api:*:*:* for any resource path in any stage, for any API in any AWS region. • arn:aws:execute-api:us-east-1:*:* for any resource path in any stage, for any API in the AWS region of us-east-1. • arn:aws:execute-api:us-east-1:*:api-id/* for any resource path in any stage, for the API with the identifier of api-id in the AWS region of us-east-1. • arn:aws:execute-api:us-east-1:*:api-id/test/* for any resource path in the stage of test, for the API with the identifier of api-id in the AWS region of us-east-1. To learn more, see API Gateway Amazon Resource Name (ARN) reference. IAM policy examples for API execution permissions For permissions model and other background information, see Control access for invoking an API. Access control 346 Amazon API Gateway Developer Guide The following policy statement gives the user permission to call any POST method along the path of mydemoresource, in the stage of test, for the API with the identifier of a123456789, assuming the corresponding API has been deployed to the AWS region of us-east-1: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:*:a123456789/test/POST/mydemoresource/*" ] } ] } The following example policy statement gives the user permission to call any method on the resource path of petstorewalkthrough/pets, in any stage, for the API with the identifier of a123456789, in any AWS region where the corresponding API has been deployed: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:*:*:a123456789/*/*/petstorewalkthrough/pets" ] } ] } Create and attach a policy to a user To enable a user to call the API managing service or the API execution service, you must create an IAM policy which controls access to the API Gateway entities. Access control 347 Amazon API Gateway Developer Guide To use the JSON policy editor to create a policy 1. Sign in to the AWS Management Console and open the IAM console at https:// console.aws.amazon.com/iam/. 2. In the navigation pane on the left, choose Policies. If this is your first time choosing Policies, the Welcome to Managed Policies page appears. Choose Get Started. 3. At the top of the page, choose Create policy. 4. 5. In the Policy editor section, choose the JSON option. Enter the following JSON policy document: { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "action-statement" ], "Resource" : [ "resource-statement" ] }, { "Effect" : "Allow", "Action" : [ "action-statement" ], "Resource" : [ "resource-statement" ] } ] } 6. Choose Next. Access control 348 Amazon API Gateway Note Developer Guide You
apigateway-dg-095
apigateway-dg.pdf
95
the left, choose Policies. If this is your first time choosing Policies, the Welcome to Managed Policies page appears. Choose Get Started. 3. At the top of the page, choose Create policy. 4. 5. In the Policy editor section, choose the JSON option. Enter the following JSON policy document: { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "action-statement" ], "Resource" : [ "resource-statement" ] }, { "Effect" : "Allow", "Action" : [ "action-statement" ], "Resource" : [ "resource-statement" ] } ] } 6. Choose Next. Access control 348 Amazon API Gateway Note Developer Guide You can switch between the Visual and JSON editor options anytime. However, if you make changes or choose Next in the Visual editor, IAM might restructure your policy to optimize it for the visual editor. For more information, see Policy restructuring in the IAM User Guide. 7. On the Review and create page, enter a Policy name and a Description (optional) for the policy that you are creating. Review Permissions defined in this policy to see the permissions that are granted by your policy. 8. Choose Create policy to save your new policy. In this statement, substitute action-statement and resource-statement as needed, and add other statements to specify the API Gateway entities you want to allow the user to manage, the API methods the user can call, or both. By default, the user does not have permissions unless there is an explicit corresponding Allow statement. You have just created an IAM policy. It won't have any effect until you attach it. To provide access, add permissions to your users, groups, or roles: • Users and groups in AWS IAM Identity Center: Create a permission set. Follow the instructions in Create a permission set in the AWS IAM Identity Center User Guide. • Users managed in IAM through an identity provider: Create a role for identity federation. Follow the instructions in Create a role for a third-party identity provider (federation) in the IAM User Guide. • IAM users: • Create a role that your user can assume. Follow the instructions in Create a role for an IAM user in the IAM User Guide. • (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in Adding permissions to a user (console) in the IAM User Guide. Access control 349 Amazon API Gateway Developer Guide To attach an IAM policy document to an IAM group 1. Choose Groups from the main navigation pane. 2. Choose the Permissions tab under the chosen group. 3. Choose Attach policy. 4. Choose the policy document that you previously created, and then choose Attach policy. For API Gateway to call other AWS services on your behalf, create an IAM role of the Amazon API Gateway type. To create an Amazon API Gateway type of role 1. Choose Roles from the main navigation pane. 2. Choose Create New Role. 3. Type a name for Role name and then choose Next Step. 4. Under Select Role Type, in AWS Service Roles, choose Select next to Amazon API Gateway. 5. Choose an available managed IAM permissions policy, for example, AmazonAPIGatewayPushToCloudWatchLog if you want API Gateway to log metrics in CloudWatch, under Attach Policy and then choose Next Step. 6. Under Trusted Entities, verify that apigateway.amazonaws.com is listed as an entry, and then choose Create Role. 7. In the newly created role, choose the Permissions tab and then choose Attach Policy. 8. Choose the previously created custom IAM policy document and then choose Attach Policy. Use VPC endpoint policies for private APIs in API Gateway To improve the security of your private API, you can create a VPC endpoint policy. A VPC endpoint policy is an IAM resource policy that you attach to a VPC endpoint. For more information, see Controlling Access to Services with VPC Endpoints. You might want to create a VPC endpoint policy to do the following tasks. • Allow only certain organizations or resources to access your VPC endpoint and invoke your API. • Use a single policy and avoid session-based or role-based policies to control traffic to your API. • Tighten the security perimeter of your application while migrating from on premises to AWS. Access control 350 Amazon API Gateway Developer Guide VPC endpoint policy considerations The following are considerations for your VPC endpoint policy. • The identity of the invoker is evaluated based on the Authorization header value. Depending on your authorizationType, this may lead to an 403 IncompleteSignatureException or an 403 InvalidSignatureException error. The following table shows the Authorization header values for each authorizationType. authorizationType Authorization header evaluated? Allowed Authorization header values NONE with the default full access policy NONE with a custom access policy IAM CUSTOM or COGNITO_U SER_POOLS No Yes Yes No Not
apigateway-dg-096
apigateway-dg.pdf
96
while migrating from on premises to AWS. Access control 350 Amazon API Gateway Developer Guide VPC endpoint policy considerations The following are considerations for your VPC endpoint policy. • The identity of the invoker is evaluated based on the Authorization header value. Depending on your authorizationType, this may lead to an 403 IncompleteSignatureException or an 403 InvalidSignatureException error. The following table shows the Authorization header values for each authorizationType. authorizationType Authorization header evaluated? Allowed Authorization header values NONE with the default full access policy NONE with a custom access policy IAM CUSTOM or COGNITO_U SER_POOLS No Yes Yes No Not passed Must be a valid SigV4 value Must be a valid SigV4 value Not passed • If a policy restricts access to a specific IAM principal, such as arn:aws:iam::account- id:role/developer, you must set the authorizationType of your API's method to AWS_IAM or NONE. For more instructions on how to set the authorizationType for a method, see the section called “Methods”. • VPC endpoint policies can be used together with API Gateway resource policies. The API Gateway resource policy specifies which principals can access the API. The endpoint policy specifies who can access the VPC and which APIs can be called from the VPC endpoint. Your private API needs a resource policy but you don't need to create a custom VPC endpoint policy. VPC endpoint policy examples You can create policies for Amazon Virtual Private Cloud endpoints for Amazon API Gateway in which you can specify the following. • The principal that can perform actions. Access control 351 Amazon API Gateway Developer Guide • The actions that can be performed. • The resources that can have actions performed on them. To attach the policy to the VPC endpoint, you'll need to use the VPC console. For more information, see Controlling Access to Services with VPC Endpoints. Example 1: VPC endpoint policy granting access to two APIs The following example policy grants access to only two specific APIs via the VPC endpoint that the policy is attached to. { "Statement": [ { "Principal": "*", "Action": [ "execute-api:Invoke" ], "Effect": "Allow", "Resource": [ "arn:aws:execute-api:us-east-1:123412341234:a1b2c3d4e5/*", "arn:aws:execute-api:us-east-1:123412341234:aaaaa11111/*" ] } ] } Example 2: VPC endpoint policy granting access to GET methods The following example policy grants users access to GET methods for a specific API via the VPC endpoint that the policy is attached to. { "Statement": [ { "Principal": "*", "Action": [ "execute-api:Invoke" ], "Effect": "Allow", "Resource": [ Access control 352 Amazon API Gateway Developer Guide "arn:aws:execute-api:us-east-1:123412341234:a1b2c3d4e5/stageName/GET/*" ] } ] } Example 3: VPC endpoint policy granting a specific user access to a specific API The following example policy grants a specific user access to a specific API via the VPC endpoint that the policy is attached to. In this case, because the policy restricts access to specific IAM principals, you must set the authorizationType of the method to AWS_IAM or NONE. { "Statement": [ { "Principal": { "AWS": [ "arn:aws:iam::123412341234:user/MyUser" ] }, "Action": [ "execute-api:Invoke" ], "Effect": "Allow", "Resource": [ "arn:aws:execute-api:us-east-1:123412341234:a1b2c3d4e5/*" ] } ] } Example 4: VPC endpoint policy granting users access to a specific custom domain name and every API mapped to the domain The following example policy grants users access to a specific custom domain name for private APIs via the VPC endpoint that the policy is attached to. With this policy, as long as a user has created a domain name access association between the VPC endpoint and the custom domain name and is granted access to invoke the custom domain name and any private API's mapped to the custom domain name, the user can invoke any APIs mapped to this custom domain name. For more information, see the section called “Custom domain names for private APIs”. Access control 353 Amazon API Gateway Developer Guide { "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "execute-api:Invoke", "Resource": [ "*" ], "Condition": { "ArnEquals": { "execute-api:viaDomainArn": "arn:aws:execute-api:us-west-2:111122223333:/ domainnames/private.test.com+f4g5h6", } } } ] } Example 5: VPC endpoint policy granting or denying access to specific APIs and domain resources The following example policy grants users access to specific APIs and domain resources. With this policy, as long as a user has created a domain name access association between the VPC endpoint and the custom domain name and is granted access to invoke the custom domain name and any private API's mapped to the custom domain name, the user can invoke allowed private APIs and domain resources. For more information, see the section called “Custom domain names for private APIs”. { "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "execute-api:Invoke", "Resource": [ "arn:aws:execute-api:us-west-2:111122223333:/domainnames/private.test.com +f4g5h6", Access control 354 Amazon API Gateway Developer Guide "arn:aws:execute-api:us-west-2:111122223333:a1b2c3d4e5/*" ] }, { "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": "execute-api:Invoke", "Resource": [ "arn:aws:execute-api:us-west-2:111122223333:a1b2c3d4e5/admin/*", "arn:aws:execute-api:us-west-2:111122223333:bcd123455/*" ] } ] } Use tags to control
apigateway-dg-097
apigateway-dg.pdf
97
VPC endpoint and the custom domain name and is granted access to invoke the custom domain name and any private API's mapped to the custom domain name, the user can invoke allowed private APIs and domain resources. For more information, see the section called “Custom domain names for private APIs”. { "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "execute-api:Invoke", "Resource": [ "arn:aws:execute-api:us-west-2:111122223333:/domainnames/private.test.com +f4g5h6", Access control 354 Amazon API Gateway Developer Guide "arn:aws:execute-api:us-west-2:111122223333:a1b2c3d4e5/*" ] }, { "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": "execute-api:Invoke", "Resource": [ "arn:aws:execute-api:us-west-2:111122223333:a1b2c3d4e5/admin/*", "arn:aws:execute-api:us-west-2:111122223333:bcd123455/*" ] } ] } Use tags to control access to REST APIs in API Gateway Permission to access REST APIs can be fine-tuned using attribute-based access control in IAM policies. For more information, see the section called “Attribute-based access control”. Use API Gateway Lambda authorizers Use a Lambda authorizer (formerly known as a custom authorizer) to control access to your API. When a client makes a request your API's method, API Gateway calls your Lambda authorizer. The Lambda authorizer takes the caller's identity as the input and returns an IAM policy as the output. Use a Lambda authorizer to implement a custom authorization scheme. Your scheme can use request parameters to determine the caller's identity or use a bearer token authentication strategy such as OAuth or SAML. Create a Lambda authorizer in the API Gateway REST API console, using the AWS CLI, or an AWS SDK. Lambda authorizer authorization workflow The following diagram shows the authorization workflow for a Lambda authorizer. Access control 355 Amazon API Gateway Developer Guide API Gateway Lambda authorization workflow 1. The client calls a method on an API Gateway API, passing a bearer token or request parameters. 2. API Gateway checks if the method request is configured with a Lambda authorizer. If it is, API Gateway calls the Lambda function. 3. The Lambda function authenticates the caller. The function can authenticate in the following ways: • By calling out to an OAuth provider to get an OAuth access token. • By calling out to a SAML provider to get a SAML assertion. • By generating an IAM policy based on the request parameter values. • By retrieving credentials from a database. 4. The Lambda function returns an IAM policy and a principal identifier. If the Lambda function does not return that information, the call fails. 5. API Gateway evaluates the IAM policy. Access control 356 Amazon API Gateway Developer Guide • If access is denied, API Gateway returns a suitable HTTP status code, such as 403 ACCESS_DENIED. • If access is allowed, API Gateway invokes the method. If you enable authorization caching, API Gateway caches the policy so that the Lambda authorizer function isn't invoked again. You can customize the 403 ACCESS_DENIED or the 401 UNAUTHORIZED gateway responses. To learn more, see the section called “Gateway responses”. Choosing a type of Lambda authorizer There are two types of Lambda authorizers: Request parameter-based Lambda authorizer (REQUEST authorizer) A REQUEST authorizer receives the caller's identity in a combination of headers, query string parameters, stageVariables, and $context variables. You can use a REQUEST authorizer to create fine-grained policies based on the information from multiple identity sources, such as the $context.path and $context.httpMethod context variables. If you turn on authorization caching for a REQUEST authorizer, API Gateway verifies that all specified identity sources are present in the request. If a specified identify source is missing, null, or empty, API Gateway returns a 401 Unauthorized HTTP response without calling the Lambda authorizer function. When multiple identity sources are defined, they are all used to derive the authorizer's cache key, with the order preserved. You can define a fine-grained cache key by using multiple identity sources. If you change any of the cache key parts, and redeploy your API, the authorizer discards the cached policy document and generates a new one. If you turn off authorization caching for a REQUEST authorizer, API Gateway directly passes the request to the Lambda function. Token-based Lambda authorizer (TOKEN authorizer) A TOKEN authorizer receives the caller's identity in a bearer token, such as a JSON Web Token (JWT) or an OAuth token. Access control 357 Amazon API Gateway Developer Guide If you turn on authorization caching for a TOKEN authorizer, the header name specified in the token source becomes the cache key. Additionally, you can use token validation to enter a RegEx statement. API Gateway performs initial validation of the input token against this expression and invokes the Lambda authorizer function upon successful validation. This helps reduce calls to your API. The IdentityValidationExpression property is supported for TOKEN authorizers only. For more information, see the section called “x-amazon-apigateway-authorizer”. Note We recommend that you use a REQUEST authorizer to control access to your API. You can control access to your API based on multiple
apigateway-dg-098
apigateway-dg.pdf
98
on authorization caching for a TOKEN authorizer, the header name specified in the token source becomes the cache key. Additionally, you can use token validation to enter a RegEx statement. API Gateway performs initial validation of the input token against this expression and invokes the Lambda authorizer function upon successful validation. This helps reduce calls to your API. The IdentityValidationExpression property is supported for TOKEN authorizers only. For more information, see the section called “x-amazon-apigateway-authorizer”. Note We recommend that you use a REQUEST authorizer to control access to your API. You can control access to your API based on multiple identity sources when using a REQUEST authorizer, compared to a single identity source when using a TOKEN authorizer. In addition, you can separate cache keys using multiple identity sources for a REQUEST authorizer. Example REQUEST authorizer Lambda function The following example code creates a Lambda authorizer function that allows a request if the client-supplied HeaderAuth1 header, QueryString1 query parameter, and stage variable of StageVar1 all match the specified values of headerValue1, queryValue1, and stageValue1, respectively. Node.js // A simple request-based authorizer example to demonstrate how to use request // parameters to allow or deny a request. In this example, a request is // authorized if the client-supplied HeaderAuth1 header, QueryString1 // query parameter, and stage variable of StageVar1 all match // specified values of 'headerValue1', 'queryValue1', and 'stageValue1', // respectively. export const handler = function(event, context, callback) { console.log('Received event:', JSON.stringify(event, null, 2)); // Retrieve request parameters from the Lambda function input: var headers = event.headers; Access control 358 Amazon API Gateway Developer Guide var queryStringParameters = event.queryStringParameters; var pathParameters = event.pathParameters; var stageVariables = event.stageVariables; // Parse the input for the parameter values var tmp = event.methodArn.split(':'); var apiGatewayArnTmp = tmp[5].split('/'); var awsAccountId = tmp[4]; var region = tmp[3]; var restApiId = apiGatewayArnTmp[0]; var stage = apiGatewayArnTmp[1]; var method = apiGatewayArnTmp[2]; var resource = '/'; // root resource if (apiGatewayArnTmp[3]) { resource += apiGatewayArnTmp[3]; } // Perform authorization to return the Allow policy for correct parameters and // the 'Unauthorized' error, otherwise. if (headers.HeaderAuth1 === "headerValue1" && queryStringParameters.QueryString1 === "queryValue1" && stageVariables.StageVar1 === "stageValue1") { callback(null, generateAllow('me', event.methodArn)); } else { callback("Unauthorized"); } } // Help function to generate an IAM policy var generatePolicy = function(principalId, effect, resource) { // Required output: var authResponse = {}; authResponse.principalId = principalId; if (effect && resource) { var policyDocument = {}; policyDocument.Version = '2012-10-17'; // default version policyDocument.Statement = []; var statementOne = {}; statementOne.Action = 'execute-api:Invoke'; // default action statementOne.Effect = effect; statementOne.Resource = resource; policyDocument.Statement[0] = statementOne; Access control 359 Amazon API Gateway Developer Guide authResponse.policyDocument = policyDocument; } // Optional output with custom properties of the String, Number or Boolean type. authResponse.context = { "stringKey": "stringval", "numberKey": 123, "booleanKey": true }; return authResponse; } var generateAllow = function(principalId, resource) { return generatePolicy(principalId, 'Allow', resource); } var generateDeny = function(principalId, resource) { return generatePolicy(principalId, 'Deny', resource); } Python # A simple request-based authorizer example to demonstrate how to use request # parameters to allow or deny a request. In this example, a request is # authorized if the client-supplied headerauth1 header, QueryString1 # query parameter, and stage variable of StageVar1 all match # specified values of 'headerValue1', 'queryValue1', and 'stageValue1', # respectively. def lambda_handler(event, context): print(event) # Retrieve request parameters from the Lambda function input: headers = event['headers'] queryStringParameters = event['queryStringParameters'] pathParameters = event['pathParameters'] stageVariables = event['stageVariables'] # Parse the input for the parameter values tmp = event['methodArn'].split(':') apiGatewayArnTmp = tmp[5].split('/') awsAccountId = tmp[4] region = tmp[3] restApiId = apiGatewayArnTmp[0] Access control 360 Amazon API Gateway Developer Guide stage = apiGatewayArnTmp[1] method = apiGatewayArnTmp[2] resource = '/' if (apiGatewayArnTmp[3]): resource += apiGatewayArnTmp[3] # Perform authorization to return the Allow policy for correct parameters # and the 'Unauthorized' error, otherwise. if (headers['HeaderAuth1'] == "headerValue1" and queryStringParameters['QueryString1'] == "queryValue1" and stageVariables['StageVar1'] == "stageValue1"): response = generateAllow('me', event['methodArn']) print('authorized') return response else: print('unauthorized') raise Exception('Unauthorized') # Return a 401 Unauthorized response # Help function to generate IAM policy def generatePolicy(principalId, effect, resource): authResponse = {} authResponse['principalId'] = principalId if (effect and resource): policyDocument = {} policyDocument['Version'] = '2012-10-17' policyDocument['Statement'] = [] statementOne = {} statementOne['Action'] = 'execute-api:Invoke' statementOne['Effect'] = effect statementOne['Resource'] = resource policyDocument['Statement'] = [statementOne] authResponse['policyDocument'] = policyDocument authResponse['context'] = { "stringKey": "stringval", "numberKey": 123, "booleanKey": True } return authResponse Access control 361 Amazon API Gateway Developer Guide def generateAllow(principalId, resource): return generatePolicy(principalId, 'Allow', resource) def generateDeny(principalId, resource): return generatePolicy(principalId, 'Deny', resource) In this example, the Lambda authorizer function checks the input parameters and acts as follows: • If all the required parameter values match the expected values, the authorizer function returns a 200 OK HTTP response and an IAM policy that looks like the following, and the method request succeeds: { "Version": "2012-10-17", "Statement": [ { "Action": "execute-api:Invoke", "Effect": "Allow", "Resource":
apigateway-dg-099
apigateway-dg.pdf
99
policyDocument['Statement'] = [statementOne] authResponse['policyDocument'] = policyDocument authResponse['context'] = { "stringKey": "stringval", "numberKey": 123, "booleanKey": True } return authResponse Access control 361 Amazon API Gateway Developer Guide def generateAllow(principalId, resource): return generatePolicy(principalId, 'Allow', resource) def generateDeny(principalId, resource): return generatePolicy(principalId, 'Deny', resource) In this example, the Lambda authorizer function checks the input parameters and acts as follows: • If all the required parameter values match the expected values, the authorizer function returns a 200 OK HTTP response and an IAM policy that looks like the following, and the method request succeeds: { "Version": "2012-10-17", "Statement": [ { "Action": "execute-api:Invoke", "Effect": "Allow", "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ ESTestInvoke-stage/GET/" } ] } • Otherwise, the authorizer function returns a 401 Unauthorized HTTP response, and the method request fails. In addition to returning an IAM policy, the Lambda authorizer function must also return the caller's principal identifier. Optionally, it can return a context object containing additional information that can be passed into the integration backend. For more information, see Output from an API Gateway Lambda authorizer. In production code, you might need to authenticate the user before granting authorization. You can add authentication logic in the Lambda function by calling an authentication provider as directed in the documentation for that provider. Access control 362 Amazon API Gateway Developer Guide Example TOKEN authorizer Lambda function The following example code creates a TOKEN Lambda authorizer function that allows a caller to invoke a method if the client-supplied token value is allow. The caller is not allowed to invoke the request if the token value is deny. If the token value is unauthorized or an empty string, the authorizer function returns an 401 UNAUTHORIZED response. Node.js // A simple token-based authorizer example to demonstrate how to use an authorization token // to allow or deny a request. In this example, the caller named 'user' is allowed to invoke // a request if the client-supplied token value is 'allow'. The caller is not allowed to invoke // the request if the token value is 'deny'. If the token value is 'unauthorized' or an empty // string, the authorizer function returns an HTTP 401 status code. For any other token value, // the authorizer returns an HTTP 500 status code. // Note that token values are case-sensitive. export const handler = function(event, context, callback) { var token = event.authorizationToken; switch (token) { case 'allow': callback(null, generatePolicy('user', 'Allow', event.methodArn)); break; case 'deny': callback(null, generatePolicy('user', 'Deny', event.methodArn)); break; case 'unauthorized': callback("Unauthorized"); // Return a 401 Unauthorized response break; default: callback("Error: Invalid token"); // Return a 500 Invalid token response } }; // Help function to generate an IAM policy var generatePolicy = function(principalId, effect, resource) { var authResponse = {}; Access control 363 Amazon API Gateway Developer Guide authResponse.principalId = principalId; if (effect && resource) { var policyDocument = {}; policyDocument.Version = '2012-10-17'; policyDocument.Statement = []; var statementOne = {}; statementOne.Action = 'execute-api:Invoke'; statementOne.Effect = effect; statementOne.Resource = resource; policyDocument.Statement[0] = statementOne; authResponse.policyDocument = policyDocument; } // Optional output with custom properties of the String, Number or Boolean type. authResponse.context = { "stringKey": "stringval", "numberKey": 123, "booleanKey": true }; return authResponse; } Python # A simple token-based authorizer example to demonstrate how to use an authorization token # to allow or deny a request. In this example, the caller named 'user' is allowed to invoke # a request if the client-supplied token value is 'allow'. The caller is not allowed to invoke # the request if the token value is 'deny'. If the token value is 'unauthorized' or an empty # string, the authorizer function returns an HTTP 401 status code. For any other token value, # the authorizer returns an HTTP 500 status code. # Note that token values are case-sensitive. import json def lambda_handler(event, context): token = event['authorizationToken'] if token == 'allow': Access control 364 Amazon API Gateway Developer Guide print('authorized') response = generatePolicy('user', 'Allow', event['methodArn']) elif token == 'deny': print('unauthorized') response = generatePolicy('user', 'Deny', event['methodArn']) elif token == 'unauthorized': print('unauthorized') raise Exception('Unauthorized') # Return a 401 Unauthorized response return 'unauthorized' try: return json.loads(response) except BaseException: print('unauthorized') return 'unauthorized' # Return a 500 error def generatePolicy(principalId, effect, resource): authResponse = {} authResponse['principalId'] = principalId if (effect and resource): policyDocument = {} policyDocument['Version'] = '2012-10-17' policyDocument['Statement'] = [] statementOne = {} statementOne['Action'] = 'execute-api:Invoke' statementOne['Effect'] = effect statementOne['Resource'] = resource policyDocument['Statement'] = [statementOne] authResponse['policyDocument'] = policyDocument authResponse['context'] = { "stringKey": "stringval", "numberKey": 123, "booleanKey": True } authResponse_JSON = json.dumps(authResponse) return authResponse_JSON In this example, when the API receives a method request, API Gateway passes the source token to this Lambda authorizer function in the event.authorizationToken attribute. The Lambda authorizer function reads the token and acts as follows: Access control 365 Amazon API Gateway Developer Guide • If the token value is allow, the authorizer function returns a 200 OK HTTP response and an IAM
apigateway-dg-100
apigateway-dg.pdf
100
'2012-10-17' policyDocument['Statement'] = [] statementOne = {} statementOne['Action'] = 'execute-api:Invoke' statementOne['Effect'] = effect statementOne['Resource'] = resource policyDocument['Statement'] = [statementOne] authResponse['policyDocument'] = policyDocument authResponse['context'] = { "stringKey": "stringval", "numberKey": 123, "booleanKey": True } authResponse_JSON = json.dumps(authResponse) return authResponse_JSON In this example, when the API receives a method request, API Gateway passes the source token to this Lambda authorizer function in the event.authorizationToken attribute. The Lambda authorizer function reads the token and acts as follows: Access control 365 Amazon API Gateway Developer Guide • If the token value is allow, the authorizer function returns a 200 OK HTTP response and an IAM policy that looks like the following, and the method request succeeds: { "Version": "2012-10-17", "Statement": [ { "Action": "execute-api:Invoke", "Effect": "Allow", "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ ESTestInvoke-stage/GET/" } ] } • If the token value is deny, the authorizer function returns a 200 OK HTTP response and a Deny IAM policy that looks like the following, and the method request fails: { "Version": "2012-10-17", "Statement": [ { "Action": "execute-api:Invoke", "Effect": "Deny", "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ ESTestInvoke-stage/GET/" } ] } Note Outside of the test environment, API Gateway returns a 403 Forbidden HTTP response and the method request fails. • If the token value is unauthorized or an empty string, the authorizer function returns a 401 Unauthorized HTTP response, and the method call fails. • If the token is anything else, the client receives a 500 Invalid token response, and the method call fails. Access control 366 Amazon API Gateway Developer Guide In addition to returning an IAM policy, the Lambda authorizer function must also return the caller's principal identifier. Optionally, it can return a context object containing additional information that can be passed into the integration backend. For more information, see Output from an API Gateway Lambda authorizer. In production code, you might need to authenticate the user before granting authorization. You can add authentication logic in the Lambda function by calling an authentication provider as directed in the documentation for that provider. Additional examples of Lambda authorizer functions The following list shows additional examples of Lambda authorizer functions. You can create a Lambda function in the same account, or a different account, from where you created your API. For the previous example Lambda functions, you can use the built-in AWSLambdaBasicExecutionRole, as these functions don't call other AWS services. If your Lambda function calls other AWS services, you'll need to assign an IAM execution role to the Lambda function. To create the role, follow the instructions in AWS Lambda Execution Role. Additional examples of Lambda authorizer functions • For an example application, see Open Banking Brazil - Authorization Samples on GitHub. • For more example Lambda functions, see aws-apigateway-lambda-authorizer-blueprints on GitHub. • You can create a Lambda authorizer that authenticates users using Amazon Cognito user pools and authorizes callers based on a policy store using Verified Permissions. For more information, see the section called “Control access based on an identity’s attributes with Verified Permissions”. • The Lambda console provides a Python blueprint, which you can use by choosing Use a blueprint and choosing the api-gateway-authorizer-python blueprint. Configure an API Gateway Lambda authorizer After you create a Lambda function, you configure the Lambda function as an authorizer for your API. You then configure your method to invoke your Lambda authorizer to determine if a caller can invoke your method. You can create a Lambda function in the same account, or a different account, from where you created your API. Access control 367 Amazon API Gateway Developer Guide You can test your Lambda authorizer using built-in tools in the API Gateway console or by using Postman. For instructions for how to use Postman to test your Lambda authorizer function, see the section called “Call an API with Lambda authorizers”. Configure a Lambda authorizer (console) The following procedure shows how to create a Lambda authorizer in the API Gateway REST API console. To learn more about the different types of Lambda authorizers, see the section called “Choosing a type of Lambda authorizer”. REQUEST authorizer To configure a REQUEST Lambda authorizer 1. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Select an API, and then choose Authorizers. 3. Choose Create authorizer. 4. 5. 6. For Authorizer name, enter a name for the authorizer. For Authorizer type, select Lambda. For Lambda function, select the AWS Region where you created your Lambda authorizer function, and then enter the function name. 7. Keep Lambda invoke role blank to let the API Gateway REST API console set a resource- based policy. The policy grants API Gateway permissions to invoke the Lambda authorizer function. You can also choose to enter the name of an IAM role to allow API Gateway to invoke the Lambda authorizer function. For an example role, see Create an assumable IAM 8. 9. role. For Lambda event payload,
apigateway-dg-101
apigateway-dg.pdf
101
enter a name for the authorizer. For Authorizer type, select Lambda. For Lambda function, select the AWS Region where you created your Lambda authorizer function, and then enter the function name. 7. Keep Lambda invoke role blank to let the API Gateway REST API console set a resource- based policy. The policy grants API Gateway permissions to invoke the Lambda authorizer function. You can also choose to enter the name of an IAM role to allow API Gateway to invoke the Lambda authorizer function. For an example role, see Create an assumable IAM 8. 9. role. For Lambda event payload, select Request. For Identity source type, select a parameter type. Supported parameter types are Header, Query string, Stage variable, and Context. To add more identity sources, choose Add parameter. 10. To cache the authorization policy generated by the authorizer, keep Authorization caching turned on. When policy caching is enabled, you can modify the TTL value. Setting the TTL to zero disables policy caching. If you enable caching, your authorizer must return a policy that is applicable to all methods across an API. To enforce a method-specific policy, use the context variables $context.path and $context.httpMethod. Access control 368 Amazon API Gateway Developer Guide 11. Choose Create authorizer. TOKEN authorizer To configure a TOKEN Lambda authorizer 1. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Select an API, and then choose Authorizers. 3. Choose Create authorizer. 4. 5. 6. For Authorizer name, enter a name for the authorizer. For Authorizer type, select Lambda. For Lambda function, select the AWS Region where you created your Lambda authorizer function, and then enter the function name. 7. Keep Lambda invoke role blank to let the API Gateway REST API console set a resource- based policy. The policy grants API Gateway permissions to invoke the Lambda authorizer function. You can also choose to enter the name of an IAM role to allow API Gateway to invoke the Lambda authorizer function. For an example role, see Create an assumable IAM 8. 9. role. For Lambda event payload, select Token. For Token source, enter the header name that contains the authorization token. The caller must include a header of this name to send the authorization token to the Lambda authorizer. 10. (Optional) For Token validation, enter a RegEx statement. API Gateway performs initial validation of the input token against this expression and invokes the authorizer upon successful validation. 11. To cache the authorization policy generated by the authorizer, keep Authorization caching turned on. When policy caching is enabled, the header name specified in Token source becomes the cache key. When policy caching is enabled, you can modify the TTL value. Setting the TTL to zero disables policy caching. If you enable caching, your authorizer must return a policy that is applicable to all methods across an API. To enforce a method-specific policy, you can turn off Authorization caching. 12. Choose Create authorizer. Access control 369 Amazon API Gateway Developer Guide After your create your Lambda authorizer, you can test it. The following procedure shows how to test your Lambda authorizer. REQUEST authorizer To test a REQUEST Lambda authorizer 1. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Select the name of your authorizer. 3. Under Test authorizer, enter a value for your identity source. If you are using the the section called “Example REQUEST authorizer Lambda function”, do the following: a. Select Header and enter headerValue1, and then choose Add parameter. b. Under Identity source type, select Query string and enter queryValue1, and then choose Add parameter. c. Under Identity source type, select Stage variable and enter stageValue1. You can't modify the context variables for the test invocation, but you can modify the API Gateway Authorizer test event template for your Lambda function. Then, you can test your Lambda authorizer function with modified context variables. For more information, see Testing Lambda functions in the console in the AWS Lambda Developer Guide. 4. Choose Test authorizer. TOKEN authorizer To test a TOKEN Lambda authorizer 1. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Select the name of your authorizer. 3. Under Test authorizer, enter a value for your token. If you are using the the section called “Example TOKEN authorizer Lambda function”, do the following: • For the authorizationToken, enter allow. Access control 370 Amazon API Gateway Developer Guide 4. Choose Test authorizer. If your Lambda authorizer successfully denies a request in the test environment, the test responds with a 200 OK HTTP response. However, outside of the test environment, API Gateway returns a 403 Forbidden HTTP response and the method request fails. Configure a Lambda authorizer (AWS CLI) The following create-authorizer command shows to create a Lambda authorizer using the AWS CLI. REQUEST authorizer The following create-authorizer command creates a REQUEST authorizer
apigateway-dg-102
apigateway-dg.pdf
102
the the section called “Example TOKEN authorizer Lambda function”, do the following: • For the authorizationToken, enter allow. Access control 370 Amazon API Gateway Developer Guide 4. Choose Test authorizer. If your Lambda authorizer successfully denies a request in the test environment, the test responds with a 200 OK HTTP response. However, outside of the test environment, API Gateway returns a 403 Forbidden HTTP response and the method request fails. Configure a Lambda authorizer (AWS CLI) The following create-authorizer command shows to create a Lambda authorizer using the AWS CLI. REQUEST authorizer The following create-authorizer command creates a REQUEST authorizer and uses the Authorizer header and accountId context variable as identity sources: aws apigateway create-authorizer \ --rest-api-id 1234123412 \ --name 'First_Request_Custom_Authorizer' \ --type REQUEST \ --authorizer-uri 'arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:123412341234:function:customAuthFunction/invocations' \ --identity-source 'method.request.header.Authorization,context.accountId' \ --authorizer-result-ttl-in-seconds 300 TOKEN authorizer The following create-authorizer command creates a TOKEN authorizer and uses the Authorization header as the identity source: aws apigateway create-authorizer \ --rest-api-id 1234123412 \ --name 'First_Token_Custom_Authorizer' \ --type TOKEN \ --authorizer-uri 'arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:123412341234:function:customAuthFunction/invocations' \ --identity-source 'method.request.header.Authorization' \ --authorizer-result-ttl-in-seconds 300 After your create your Lambda authorizer, you can test it. The following test-invoke-authorizer command tests a Lambda authorizer: Access control 371 Amazon API Gateway Developer Guide aws apigateway test-invoke-authorizer --rest-api-id 1234123412 \ --authorizer-id efg1234 \ --headers Authorization='Value' Configure a method to use a Lambda authorizer (console) After you configure your Lambda authorizer, you must attach it to a method for your API. To configure an API method to use a Lambda authorizer 1. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Select an API. 3. Choose Resources, and then choose a new method or choose an existing method. 4. On the Method request tab, under Method request settings, choose Edit. 5. 6. For Authorizer, from the dropdown menu, select the Lambda authorizer you just created. (Optional) If you want to pass the authorization token to the backend, choose HTTP request headers. Choose Add header, and then add the name of the authorization header. For Name, enter the header name that matches the Token source name you specified when you created the Lambda authorizer for the API. This step does not apply to REQUEST authorizers. 7. Choose Save. 8. Choose Deploy API to deploy the API to a stage. For a REQUEST authorizer using stage variables, you must also define the required stage variables and specify their values while on the Stages page. Configure a method to use a Lambda authorizer (AWS CLI) After you configure your Lambda authorizer, you must attach it to a method for your API. You can create a new method or use a patch operation to attach an authorizer to an existing method. The following put-method command creates a new method that uses an Lambda authorizer: aws apigateway put-method --rest-api-id 1234123412 \ --resource-id a1b2c3 \ --http-method PUT \ --authorization-type CUSTOM \ --authorizer-id efg1234 Access control 372 Amazon API Gateway Developer Guide The following update-method command update an existing method to use a Lambda authorizer: aws apigateway update-method \ --rest-api-id 1234123412 \ --resource-id a1b2c3 \ --http-method PUT \ --patch-operations op="replace",path="/authorizationType",value="CUSTOM" op="replace",path="/authorizerId",value="efg1234" Input to an API Gateway Lambda authorizer The following section explains the format of the input from API Gateway to a Lambda authorizer. TOKEN input format For a Lambda authorizer (formerly known as a custom authorizer) of the TOKEN type, you must specify a custom header as the Token Source when you configure the authorizer for your API. The API client must pass the required authorization token in that header in the incoming request. Upon receiving the incoming method request, API Gateway extracts the token from the custom header. It then passes the token as the authorizationToken property of the event object of the Lambda function, in addition to the method ARN as the methodArn property: { "type":"TOKEN", "authorizationToken":"{caller-supplied-token}", "methodArn":"arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/ [{resource}/[{child-resources}]]" } In this example, the type property specifies the authorizer type, which is a TOKEN authorizer. The {caller-supplied-token} originates from the authorization header in a client request, and can be any string value. The methodArn is the ARN of the incoming method request and is populated by API Gateway in accordance with the Lambda authorizer configuration. REQUEST input format For a Lambda authorizer of the REQUEST type, API Gateway passes request parameters to the authorizer Lambda function as part of the event object. The request parameters include headers, path parameters, query string parameters, stage variables, and some of request context variables. The API caller can set the path parameters, headers, and query string parameters. The API Access control 373 Amazon API Gateway Developer Guide developer must set the stage variables during the API deployment and API Gateway provides the request context at run time. Note Path parameters can be passed as request parameters to the Lambda authorizer function, but they cannot be used as identity sources. The following
apigateway-dg-103
apigateway-dg.pdf
103
Gateway passes request parameters to the authorizer Lambda function as part of the event object. The request parameters include headers, path parameters, query string parameters, stage variables, and some of request context variables. The API caller can set the path parameters, headers, and query string parameters. The API Access control 373 Amazon API Gateway Developer Guide developer must set the stage variables during the API deployment and API Gateway provides the request context at run time. Note Path parameters can be passed as request parameters to the Lambda authorizer function, but they cannot be used as identity sources. The following example shows an input to a REQUEST authorizer for an API method (GET / request) with a proxy integration: { "type": "REQUEST", "methodArn": "arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request", "resource": "/request", "path": "/request", "httpMethod": "GET", "headers": { "X-AMZ-Date": "20170718T062915Z", "Accept": "*/*", "HeaderAuth1": "headerValue1", "CloudFront-Viewer-Country": "US", "CloudFront-Forwarded-Proto": "https", "CloudFront-Is-Tablet-Viewer": "false", "CloudFront-Is-Mobile-Viewer": "false", "User-Agent": "..." }, "queryStringParameters": { "QueryString1": "queryValue1" }, "pathParameters": {}, "stageVariables": { "StageVar1": "stageValue1" }, "requestContext": { "path": "/request", "accountId": "123456789012", "resourceId": "05c7jb", "stage": "test", "requestId": "...", "identity": { Access control 374 Amazon API Gateway "apiKey": "...", "sourceIp": "...", "clientCert": { "clientCertPem": "CERT_CONTENT", "subjectDN": "www.example.com", "issuerDN": "Example issuer", "serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1", "validity": { "notBefore": "May 28 12:30:02 2019 GMT", "notAfter": "Aug 5 09:36:04 2021 GMT" Developer Guide } } }, "resourcePath": "/request", "httpMethod": "GET", "apiId": "abcdef123" } } The requestContext is a map of key-value pairs and corresponds to the $context variable. Its outcome is API-dependent. API Gateway might add new keys to the map. For more information about Lambda function input in Lambda proxy integration, see Input format of a Lambda function for proxy integration. Output from an API Gateway Lambda authorizer A Lambda authorizer function's output is a dictionary-like object, which must include the principal identifier (principalId) and a policy document (policyDocument) containing a list of policy statements. The output can also include a context map containing key-value pairs. If the API uses a usage plan (the apiKeySource is set to AUTHORIZER), the Lambda authorizer function must return one of the usage plan's API keys as the usageIdentifierKey property value. The following shows an example of this output. { "principalId": "yyyyyyyy", // The principal user identification associated with the token sent by the client. "policyDocument": { "Version": "2012-10-17", "Statement": [ { Access control 375 Amazon API Gateway Developer Guide "Action": "execute-api:Invoke", "Effect": "Allow|Deny", "Resource": "arn:aws:execute- api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/[{resource}/[{child-resources}]]" } ] }, "context": { "stringKey": "value", "numberKey": "1", "booleanKey": "true" }, "usageIdentifierKey": "{api-key}" } Here, a policy statement specifies whether to allow or deny (Effect) the API Gateway execution service to invoke (Action) the specified API method (Resource). You can use a wild card (*) to specify a resource type (method). For information about setting valid policies for calling an API, see Statement reference of IAM policies for executing API in API Gateway. For an authorization-enabled method ARN, e.g., arn:aws:execute- api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/[{resource}/[{child- resources}]], the maximum length is 1600 bytes. The path parameter values, the size of which are determined at run time, can cause the ARN length to exceed the limit. When this happens, the API client will receive a 414 Request URI too long response. In addition, the Resource ARN, as shown in the policy statement output by the authorizer, is currently limited to 512 characters long. For this reason, you must not use URI with a JWT token of a significant length in a request URI. You can safely pass the JWT token in a request header, instead. You can access the principalId value in a mapping template using the $context.authorizer.principalId variable. This is useful if you want to pass the value to the backend. For more information, see Context variables for data transformations. You can access the stringKey, numberKey, or booleanKey value (for example, "value", "1", or "true") of the context map in a mapping template by calling $context.authorizer.stringKey, $context.authorizer.numberKey, or $context.authorizer.booleanKey, respectively. The returned values are all stringified. Notice that you cannot set a JSON object or array as a valid value of any key in the context map. Access control 376 Amazon API Gateway Developer Guide You can use the context map to return cached credentials from the authorizer to the backend, using an integration request mapping template. This enables the backend to provide an improved user experience by using the cached credentials to reduce the need to access the secret keys and open the authorization tokens for every request. For the Lambda proxy integration, API Gateway passes the context object from a Lambda authorizer directly to the backend Lambda function as part of the input event. You can retrieve the context key-value pairs in the Lambda function by calling $event.requestContext.authorizer.key. {api-key} stands for an API key in the API stage's usage plan. For more information, see the section called “Usage plans”. The following shows example output from the example Lambda authorizer.
apigateway-dg-104
apigateway-dg.pdf
104
to provide an improved user experience by using the cached credentials to reduce the need to access the secret keys and open the authorization tokens for every request. For the Lambda proxy integration, API Gateway passes the context object from a Lambda authorizer directly to the backend Lambda function as part of the input event. You can retrieve the context key-value pairs in the Lambda function by calling $event.requestContext.authorizer.key. {api-key} stands for an API key in the API stage's usage plan. For more information, see the section called “Usage plans”. The following shows example output from the example Lambda authorizer. The example output contains a policy statement to block (Deny) calls to the GET method for the dev stage of an API (ymy8tbxw7b) of an AWS account (123456789012). { "principalId": "user", "policyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": "execute-api:Invoke", "Effect": "Deny", "Resource": "arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/dev/GET/" } ] } } Call an API with an API Gateway Lambda authorizer Having configured the Lambda authorizer (formerly known as the custom authorizer) and deployed the API, you should test the API with the Lambda authorizer enabled. For this, you need a REST client, such as cURL or Postman. For the following examples, we use Postman. Note When calling an authorizer-enabled method, API Gateway does not log the call to CloudWatch if the required token for the TOKEN authorizer is not set, is null, or is Access control 377 Amazon API Gateway Developer Guide invalidated by the specified Token validation expression. Similarly, API Gateway does not log the call to CloudWatch if any of the required identity sources for the REQUEST authorizer are not set, are null, or are empty. In the following, we show how to use Postman to call or test an API with a Lambda TOKEN authorizer. The method can be applied to calling an API with a Lambda REQUEST authorizer, if you specify the required path, header, or query string parameters explicitly. To call an API with the custom TOKEN authorizer 1. Open Postman, choose the GET method, and paste the API's Invoke URL into the adjacent URL field. Add the Lambda authorization token header and set the value to allow. Choose Send. Access control 378 Amazon API Gateway Developer Guide The response shows that the API Gateway Lambda authorizer returns a 200 OK response and successfully authorizes the call to access the HTTP endpoint (http://httpbin.org/get) integrated with the method. 2. Still in Postman, change the Lambda authorization token header value to deny. Choose Send. The response shows that the API Gateway Lambda authorizer returns a 403 Forbidden response without authorizing the call to access the HTTP endpoint. 3. In Postman, change the Lambda authorization token header value to unauthorized and choose Send. Access control 379 Amazon API Gateway Developer Guide The response shows that API Gateway returns a 401 Unauthorized response without authorizing the call to access the HTTP endpoint. 4. Now, change the Lambda authorization token header value to fail. Choose Send. Access control 380 Amazon API Gateway Developer Guide The response shows that API Gateway returns a 500 Internal Server Error response without authorizing the call to access the HTTP endpoint. Configure a cross-account API Gateway Lambda authorizer You can now also use an AWS Lambda function from a different AWS account as your API authorizer function. Each account can be in any region where Amazon API Gateway is available. The Lambda authorizer function can use bearer token authentication strategies such as OAuth or SAML. This makes it easy to centrally manage and share a central Lambda authorizer function across multiple API Gateway APIs. In this section, we show how to configure a cross-account Lambda authorizer function using the Amazon API Gateway console. These instructions assume that you already have an API Gateway API in one AWS account and a Lambda authorizer function in another account. Configure a cross-account Lambda authorizer using the API Gateway console Log in to the Amazon API Gateway console in the account that has your API in it, and then do the following: 1. Choose your API, and then in the main navigation pane, choose Authorizers. 2. Choose Create authorizer. 3. 4. 5. For Authorizer name, enter a name for the authorizer. For Authorizer type, select Lambda. For Lambda Function, enter the full ARN for the Lambda authorizer function that you have in your second account. Note In the Lambda console, you can find the ARN for your function in the upper right corner of the console window. 6. A warning with an aws lambda add-permission command string will appear. This policy grants API Gateway permission to invoke the authorizer Lambda function. Copy the command and save it for later. You run the command after you create the authorizer. Access control 381 Amazon API Gateway Developer Guide 7. For Lambda event payload, select
apigateway-dg-105
apigateway-dg.pdf
105
Authorizer type, select Lambda. For Lambda Function, enter the full ARN for the Lambda authorizer function that you have in your second account. Note In the Lambda console, you can find the ARN for your function in the upper right corner of the console window. 6. A warning with an aws lambda add-permission command string will appear. This policy grants API Gateway permission to invoke the authorizer Lambda function. Copy the command and save it for later. You run the command after you create the authorizer. Access control 381 Amazon API Gateway Developer Guide 7. For Lambda event payload, select either Token for a TOKEN authorizer or Request for a REQUEST authorizer. 8. Depending on the choice of the previous step, do one of the following: a. For the Token option, do the following: • For Token source, enter the header name that contains the authorization token. The API client must include a header of this name to send the authorization token to the Lambda authorizer. • Optionally, for Token validation, enter a RegEx statement. API Gateway performs initial validation of the input token against this expression and invokes the authorizer upon successful validation. This helps reduce calls to your API. • To cache the authorization policy generated by the authorizer, keep Authorization caching turned on. When policy caching is enabled, you can choose to modify the TTL value. Setting the TTL to zero disables policy caching. When policy caching is enabled, the header name specified in Token source becomes the cache key. If multiple values are passed to this header in the request, all values will become the cache key, with the order preserved. Note The default TTL value is 300 seconds. The maximum value is 3600 seconds; this limit cannot be increased. b. For the Request option, do the following: • For Identity source type, select a parameter type. Supported parameter types are Header, Query string, Stage variable, and Context. To add more identity sources, choose Add parameter. • To cache the authorization policy generated by the authorizer, keep Authorization caching turned on. When policy caching is enabled, you can choose to modify the TTL value. Setting the TTL to zero disables policy caching. API Gateway uses the specified identity sources as the request authorizer caching key. When caching is enabled, API Gateway calls the authorizer's Lambda function only after successfully verifying that all the specified identity sources are present at runtime. Access control 382 Amazon API Gateway Developer Guide If a specified identify source is missing, null, or empty, API Gateway returns a 401 Unauthorized response without calling the authorizer Lambda function. When multiple identity sources are defined, they are all used to derive the authorizer's cache key. Changing any of the cache key parts causes the authorizer to discard the cached policy document and generate a new one. If a header with multiple values is passed in the request, then all values will be part of the cache key, with the order preserved. • When caching is turned off, it is not necessary to specify an identity source. Note To enable caching, your authorizer must return a policy that is applicable to all methods across an API. To enforce method-specific policy, you can turn off Authorization caching. 9. Choose Create authorizer. 10. Paste the aws lambda add-permission command string that you copied in a previous step into an AWS CLI window that is configured for your second account. Replace AUTHORIZER_ID with your authorizer's ID. This will grant your first account access to your second account's Lambda authorizer function. Control access based on an identity’s attributes with Verified Permissions Use Amazon Verified Permissions to control access to your API Gateway API. When you use API Gateway with Verified Permissions, Verified Permissions creates a Lambda authorizer that uses fine-grained authorization decisions to control access to your API. Verified Permissions authorizes callers based on a policy store schema and policies using the Cedar policy language to define fine- grained permissions for application users. For more information, see Create a policy store with a connected API and identity provider in the Amazon Verified Permissions User Guide. Verified Permissions supports Amazon Cognito user pools or OpenID Connect (OIDC) identity providers as identity sources. Verified Permissions presumes that the principal has been previously identified and authenticated. Verified Permissions is only supported for Regional and edge- optimized REST APIs. Access control 383 Amazon API Gateway Developer Guide Create a Lambda authorizer using Verified Permissions Verified Permissions creates a Lambda authorizer to determine if a principal is allowed to perform an action on your API. You create the Cedar policy that Verified Permissions uses to perform its authorization tasks. The following is an example Cedar policy that allows access to invoke an API based on the Amazon Cognito user pool, us-east-1_ABC1234 for the developer
apigateway-dg-106
apigateway-dg.pdf
106
identity sources. Verified Permissions presumes that the principal has been previously identified and authenticated. Verified Permissions is only supported for Regional and edge- optimized REST APIs. Access control 383 Amazon API Gateway Developer Guide Create a Lambda authorizer using Verified Permissions Verified Permissions creates a Lambda authorizer to determine if a principal is allowed to perform an action on your API. You create the Cedar policy that Verified Permissions uses to perform its authorization tasks. The following is an example Cedar policy that allows access to invoke an API based on the Amazon Cognito user pool, us-east-1_ABC1234 for the developer group on the GET /users resource of an API. Verified Permissions determines group membership by parsing the bearer token for the caller's identity. permit( principal in MyAPI::UserGroup::"us-east-1_ABC1234|developer", action in [ MyAPI::Action::"get /users" ], resource ); Optionally, Verified Permissions can attach the authorizer to the methods of your API. On production stages for your API, we recommend that you don't allow Verified Permissions to attach the authorizer for you. The following list show how to configure Verified Permissions to attach or not to attach the Lambda authorizer to the method request of your API's methods. Attach the authorizer for you (AWS Management Console) When you choose Create policy store in the Verified Permissions console, on the Deploy app integration page, choose Now. Don't attach the authorizer for you (AWS Management Console) When you choose Create policy store in the Verified Permissions console, on the Deploy app integration page, choose Later. Verified Permissions still creates a Lambda authorizer for you. The Lambda authorizer starts with AVPAuthorizerLambda-. For more instructions on how to attach your authorizer on a method, see the section called “Configure a method to use a Lambda authorizer (console)”. Attach the authorizer for you (AWS CloudFormation) In the Verified Permissions-generated AWS CloudFormation template, in the Conditions section, set "Ref": "shouldAttachAuthorizer" to true. Access control 384 Amazon API Gateway Developer Guide Don't attach the authorizer for you (AWS CloudFormation) In the Verified Permissions-generated AWS CloudFormation template, in the Conditions section, set "Ref": "shouldAttachAuthorizer" to false. Verified Permissions still creates a Lambda authorizer for you. The Lambda authorizer starts with AVPAuthorizerLambda-. For more instructions on how to attach your authorizer on a method, see the section called “Configure a method to use a Lambda authorizer (AWS CLI)”. Call a Lambda authorizer using Verified Permissions You can call your Lambda authorizer by providing an identity or access token in the Authorization header. For more information, see the section called “Call an API with Lambda authorizers”. API Gateway caches the policy that your Lambda authorizer returns for 120 seconds. You can modify the TTL in the API Gateway console or by using the AWS CLI. Control access to REST APIs using Amazon Cognito user pools as an authorizer As an alternative to using IAM roles and policies or Lambda authorizers (formerly known as custom authorizers), you can use an Amazon Cognito user pool to control who can access your API in Amazon API Gateway. To use an Amazon Cognito user pool with your API, you must first create an authorizer of the COGNITO_USER_POOLS type and then configure an API method to use that authorizer. After the API is deployed, the client must first sign the user in to the user pool, obtain an identity or access token for the user, and then call the API method with one of the tokens, which are typically set to the request's Authorization header. The API call succeeds only if the required token is supplied and the supplied token is valid, otherwise, the client isn't authorized to make the call because the client did not have credentials that could be authorized. The identity token is used to authorize API calls based on identity claims of the signed-in user. The access token is used to authorize API calls based on the custom scopes of specified access- protected resources. For more information, see Using Tokens with User Pools and Resource Server and Custom Scopes. To create and configure an Amazon Cognito user pool for your API, you perform the following tasks: Access control 385 Amazon API Gateway Developer Guide • Use the Amazon Cognito console, CLI/SDK, or API to create a user pool—or use one that's owned by another AWS account. • Use the API Gateway console, CLI/SDK, or API to create an API Gateway authorizer with the chosen user pool. • Use the API Gateway console, CLI/SDK, or API to enable the authorizer on selected API methods. To call any API methods with a user pool enabled, your API clients perform the following tasks: • Use the Amazon Cognito CLI/SDK or API to sign a user in to the chosen user pool, and obtain an identity token or access token. To learn more about using the SDKs, see Code
apigateway-dg-107
apigateway-dg.pdf
107
a user pool—or use one that's owned by another AWS account. • Use the API Gateway console, CLI/SDK, or API to create an API Gateway authorizer with the chosen user pool. • Use the API Gateway console, CLI/SDK, or API to enable the authorizer on selected API methods. To call any API methods with a user pool enabled, your API clients perform the following tasks: • Use the Amazon Cognito CLI/SDK or API to sign a user in to the chosen user pool, and obtain an identity token or access token. To learn more about using the SDKs, see Code examples for Amazon Cognito using AWS SDKs. • Use a client-specific framework to call the deployed API Gateway API and supply the appropriate token in the Authorization header. As the API developer, you must provide your client developers with the user pool ID, a client ID, and possibly the associated client secrets that are defined as part of the user pool. Note To let a user sign in using Amazon Cognito credentials and also obtain temporary credentials to use with the permissions of an IAM role, use Amazon Cognito Federated Identities. For each API resource endpoint HTTP method, set the authorization type, category Method Execution, to AWS_IAM. In this section, we describe how to create a user pool, how to integrate an API Gateway API with the user pool, and how to invoke an API that's integrated with the user pool. Topics • Obtain permissions to create Amazon Cognito user pool authorizers for a REST API • Create an Amazon Cognito user pool for a REST API • Integrate a REST API with an Amazon Cognito user pool • Call a REST API integrated with an Amazon Cognito user pool • Configure cross-account Amazon Cognito authorizer for a REST API using the API Gateway console Access control 386 Amazon API Gateway Developer Guide • Create an Amazon Cognito authorizer for a REST API using AWS CloudFormation Obtain permissions to create Amazon Cognito user pool authorizers for a REST API To create an authorizer with an Amazon Cognito user pool, you must have Allow permissions to create or update an authorizer with the chosen Amazon Cognito user pool. The following IAM policy document shows an example of such permissions: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "apigateway:POST" ], "Resource": "arn:aws:apigateway:*::/restapis/*/authorizers", "Condition": { "ArnLike": { "apigateway:CognitoUserPoolProviderArn": [ "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us- east-1_aD06NQmjO", "arn:aws:cognito-idp:us-east-1:234567890123:userpool/us- east-1_xJ1MQtPEN" ] } } }, { "Effect": "Allow", "Action": [ "apigateway:PATCH" ], "Resource": "arn:aws:apigateway:*::/restapis/*/authorizers/*", "Condition": { "ArnLike": { "apigateway:CognitoUserPoolProviderArn": [ "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us- east-1_aD06NQmjO", "arn:aws:cognito-idp:us-east-1:234567890123:userpool/us- east-1_xJ1MQtPEN" ] } Access control 387 Amazon API Gateway } } ] } Developer Guide Make sure that the policy is attached to an IAM group that you belong to or an IAM role that you're assigned to. In the preceding policy document, the apigateway:POST action is for creating a new authorizer, and the apigateway:PATCH action is for updating an existing authorizer. You can restrict the policy to a specific region or a particular API by overriding the first two wildcard (*) characters of the Resource values, respectively. The Condition clauses that are used here are to restrict the Allowed permissions to the specified user pools. When a Condition clause is present, access to any user pools that don't match the conditions is denied. When a permission doesn't have a Condition clause, access to any user pool is allowed. You have the following options to set the Condition clause: • You can set an ArnLike or ArnEquals conditional expression to permit creating or updating COGNITO_USER_POOLS authorizers with the specified user pools only. • You can set an ArnNotLike or ArnNotEquals conditional expression to permit creating or updating COGNITO_USER_POOLS authorizers with any user pool that isn't specified in the expression. • You can omit the Condition clause to permit creating or updating COGNITO_USER_POOLS authorizers with any user pool, of any AWS account, and in any region. For more information on the Amazon Resource Name (ARN) conditional expressions, see Amazon Resource Name Condition Operators. As shown in the example, apigateway:CognitoUserPoolProviderArn is a list of ARNs of the COGNITO_USER_POOLS user pools that can or can't be used with an API Gateway authorizer of the COGNITO_USER_POOLS type. Create an Amazon Cognito user pool for a REST API Before integrating your API with a user pool, you must create the user pool in Amazon Cognito. Your user pool configuration must follow all resource quotas for Amazon Cognito. All user- Access control 388 Amazon API Gateway Developer Guide defined Amazon Cognito variables such as groups, users, and roles should use only alphanumeric characters. For instructions on how to create a user pool, see Tutorial: Creating a user pool in the Amazon Cognito Developer Guide. Note the user pool ID, client ID, and any client secret. The client must provide them to Amazon
apigateway-dg-108
apigateway-dg.pdf
108
Cognito user pool for a REST API Before integrating your API with a user pool, you must create the user pool in Amazon Cognito. Your user pool configuration must follow all resource quotas for Amazon Cognito. All user- Access control 388 Amazon API Gateway Developer Guide defined Amazon Cognito variables such as groups, users, and roles should use only alphanumeric characters. For instructions on how to create a user pool, see Tutorial: Creating a user pool in the Amazon Cognito Developer Guide. Note the user pool ID, client ID, and any client secret. The client must provide them to Amazon Cognito for the user to register with the user pool, to sign in to the user pool, and to obtain an identity or access token to be included in requests to call API methods that are configured with the user pool. Also, you must specify the user pool name when you configure the user pool as an authorizer in API Gateway, as described next. If you're using access tokens to authorize API method calls, be sure to configure the app integration with the user pool to set up the custom scopes that you want on a given resource server. For more information about using tokens with Amazon Cognito user pools, see Using Tokens with User Pools. For more information about resource servers, see Defining Resource Servers for Your User Pool. Note the configured resource server identifiers and custom scope names. You need them to construct the access scope full names for OAuth Scopes, which is used by the COGNITO_USER_POOLS authorizer. Access control 389 Amazon API Gateway Developer Guide Integrate a REST API with an Amazon Cognito user pool After creating an Amazon Cognito user pool, in API Gateway, you must then create a COGNITO_USER_POOLS authorizer that uses the user pool. The following procedure shows you how to do this using the API Gateway console. Note You can use the CreateAuthorizer action to create a COGNITO_USER_POOLS authorizer that uses multiple user pools. You can use up to 1,000 user pools for one COGNITO_USER_POOLS authorizer. This limit cannot be increased. Important After performing any of the procedures below, you'll need to deploy or redeploy your API to propagate the changes. For more information about deploying your API, see Deploy REST APIs in API Gateway. To create a COGNITO_USER_POOLS authorizer by using the API Gateway console 1. Create a new API, or select an existing API in API Gateway. 2. In the main navigation pane, choose Authorizers. 3. Choose Create authorizer. 4. To configure the new authorizer to use a user pool, do the following: a. b. c. For Authorizer name, enter a name. For Authorizer type, select Cognito. For Cognito user pool, choose the AWS Region where you created your Amazon Cognito and select an available user pool. You can use a stage variable to define your user pool. Use the following format for your user pool: arn:aws:cognito-idp:us-east-2:111122223333:userpool/ ${stageVariables.MyUserPool}. d. For Token source, enter Authorization as the header name to pass the identity or access token that's returned by Amazon Cognito when a user signs in successfully. Access control 390 Amazon API Gateway Developer Guide e. (Optional) Enter a regular expression in the Token validation field to validate the aud (audience) field of the identity token before the request is authorized with Amazon Cognito. Note that when using an access token this validation rejects the request due to the access token not containing the aud field. f. Choose Create authorizer. 5. After creating the COGNITO_USER_POOLS authorizer, you can test invoke it by supplying an identity token that's provisioned from the user pool. You can't use an access token to test invoke your authorizer. You can obtain this identity token by calling the Amazon Cognito Identity SDK to perform user sign-in. You can also use the InitiateAuth action. If you do not configure any Authorization scopes, API Gateway treats the supplied token as an identity token. The preceding procedure creates a COGNITO_USER_POOLS authorizer that uses the newly created Amazon Cognito user pool. Depending on how you enable the authorizer on an API method, you can use either an identity token or an access token that's provisioned from the integrated user pool. To configure a COGNITO_USER_POOLS authorizer on methods 1. Choose Resources. Choose a new method or choose an existing method. If necessary, create a resource. 2. On the Method request tab, under Method request settings, choose Edit. 3. For Authorizer, from the dropdown menu, select the Amazon Cognito user pool authorizers you just created. 4. To use an identity token, do the following: a. Keep Authorization Scopes empty. b. If needed, in the Integration request, add the $context.authorizer.claims['property-name'] or $context.authorizer.claims.property-name expressions in a body-mapping template to pass the specified identity claims property from the user pool to the backend. For simple property names,
apigateway-dg-109
apigateway-dg.pdf
109
a COGNITO_USER_POOLS authorizer on methods 1. Choose Resources. Choose a new method or choose an existing method. If necessary, create a resource. 2. On the Method request tab, under Method request settings, choose Edit. 3. For Authorizer, from the dropdown menu, select the Amazon Cognito user pool authorizers you just created. 4. To use an identity token, do the following: a. Keep Authorization Scopes empty. b. If needed, in the Integration request, add the $context.authorizer.claims['property-name'] or $context.authorizer.claims.property-name expressions in a body-mapping template to pass the specified identity claims property from the user pool to the backend. For simple property names, such as sub or custom-sub, the two notations are identical. For complex property names, such as custom:role, you can't use the dot notation. For example, the following mapping expressions pass the claim's standard fields of sub and email to the backend: Access control 391 Amazon API Gateway Developer Guide { "context" : { "sub" : "$context.authorizer.claims.sub", "email" : "$context.authorizer.claims.email" } } If you declared a custom claim field when you configured a user pool, you can follow the same pattern to access the custom fields. The following example gets a custom role field of a claim: { "context" : { "role" : "$context.authorizer.claims.role" } } If the custom claim field is declared as custom:role, use the following example to get the claim's property: { "context" : { "role" : "$context.authorizer.claims['custom:role']" } } 5. To use an access token, do the following: a. For Authorization Scopes, enter one or more full names of a scope that has been configured when the Amazon Cognito user pool was created. For example, following the example given in Create an Amazon Cognito user pool for a REST API, one of the scopes is https://my-petstore-api.example.com/cats.read. At runtime, the method call succeeds if any scope that's specified on the method in this step matches a scope that's claimed in the incoming token. Otherwise, the call fails with a 401 Unauthorized response. b. Choose Save. 6. Repeat these steps for other methods that you choose. Access control 392 Amazon API Gateway Developer Guide With the COGNITO_USER_POOLS authorizer, if the OAuth Scopes option isn't specified, API Gateway treats the supplied token as an identity token and verifies the claimed identity against the one from the user pool. Otherwise, API Gateway treats the supplied token as an access token and verifies the access scopes that are claimed in the token against the authorization scopes declared on the method. Instead of using the API Gateway console, you can also enable an Amazon Cognito user pool on a method by specifying an OpenAPI definition file and importing the API definition into API Gateway. To import a COGNITO_USER_POOLS authorizer with an OpenAPI definition file 1. Create (or export) an OpenAPI definition file for your API. 2. Specify the COGNITO_USER_POOLS authorizer (MyUserPool) JSON definition as part of the securitySchemes section in OpenAPI 3.0 or the securityDefinitions section in Open API 2.0 as follows: OpenAPI 3.0 "securitySchemes": { "MyUserPool": { "type": "apiKey", "name": "Authorization", "in": "header", "x-amazon-apigateway-authtype": "cognito_user_pools", "x-amazon-apigateway-authorizer": { "type": "cognito_user_pools", "providerARNs": [ "arn:aws:cognito-idp:{region}:{account_id}:userpool/{user_pool_id}" ] } } OpenAPI 2.0 "securityDefinitions": { "MyUserPool": { "type": "apiKey", "name": "Authorization", "in": "header", "x-amazon-apigateway-authtype": "cognito_user_pools", "x-amazon-apigateway-authorizer": { Access control 393 Amazon API Gateway Developer Guide "type": "cognito_user_pools", "providerARNs": [ "arn:aws:cognito-idp:{region}:{account_id}:userpool/{user_pool_id}" ] } } 3. To use the identity token for method authorization, add { "MyUserPool": [] } to the security definition of the method, as shown in the following GET method on the root resource. "paths": { "/": { "get": { "consumes": [ "application/json" ], "produces": [ "text/html" ], "responses": { "200": { "description": "200 response", "headers": { "Content-Type": { "type": "string" } } } }, "security": [ { "MyUserPool": [] } ], "x-amazon-apigateway-integration": { "type": "mock", "responses": { "default": { "statusCode": "200", "responseParameters": { "method.response.header.Content-Type": "'text/html'" }, Access control 394 Amazon API Gateway Developer Guide } }, "requestTemplates": { "application/json": "{\"statusCode\": 200}" }, "passthroughBehavior": "when_no_match" } }, ... } 4. To use the access token for method authorization, change the above security definition to { "MyUserPool": [resource-server/scope, ...] }: "paths": { "/": { "get": { "consumes": [ "application/json" ], "produces": [ "text/html" ], "responses": { "200": { "description": "200 response", "headers": { "Content-Type": { "type": "string" } } } }, "security": [ { "MyUserPool": ["https://my-petstore-api.example.com/cats.read", "http://my.resource.com/file.read"] } ], "x-amazon-apigateway-integration": { "type": "mock", "responses": { "default": { Access control 395 Amazon API Gateway Developer Guide "statusCode": "200", "responseParameters": { "method.response.header.Content-Type": "'text/html'" }, } }, "requestTemplates": { "application/json": "{\"statusCode\": 200}" }, "passthroughBehavior": "when_no_match" } }, ... } 5. If needed, you can set other API configuration settings by using the appropriate OpenAPI definitions or extensions. For more information, see OpenAPI extensions for API Gateway. Call a REST API integrated with an Amazon Cognito user pool To call a method with a user pool authorizer configured, the client must do
apigateway-dg-110
apigateway-dg.pdf
110
} } }, "security": [ { "MyUserPool": ["https://my-petstore-api.example.com/cats.read", "http://my.resource.com/file.read"] } ], "x-amazon-apigateway-integration": { "type": "mock", "responses": { "default": { Access control 395 Amazon API Gateway Developer Guide "statusCode": "200", "responseParameters": { "method.response.header.Content-Type": "'text/html'" }, } }, "requestTemplates": { "application/json": "{\"statusCode\": 200}" }, "passthroughBehavior": "when_no_match" } }, ... } 5. If needed, you can set other API configuration settings by using the appropriate OpenAPI definitions or extensions. For more information, see OpenAPI extensions for API Gateway. Call a REST API integrated with an Amazon Cognito user pool To call a method with a user pool authorizer configured, the client must do the following: • Enable the user to sign up with the user pool. • Enable the user to sign in to the user pool. • Obtain an identity or access token of the signed-in user from the user pool. • Include the token in the Authorization header (or another header you specified when you created the authorizer). You can use AWS Amplify to perform these tasks. See Integrating Amazon Cognito With Web and Mobile Apps for more information. • For Android, see Getting Started with Amplify for Android. • To use iOS see Getting started with Amplify for iOS. • To use JavaScript, see Getting Started with Amplify for Javascript. Access control 396 Amazon API Gateway Developer Guide Configure cross-account Amazon Cognito authorizer for a REST API using the API Gateway console You can now also use a Amazon Cognito user pool from a different AWS account as your API authorizer. The Amazon Cognito user pool can use bearer token authentication strategies such as OAuth or SAML. This makes it easy to centrally manage and share a central Amazon Cognito user pool authorizer across multiple API Gateway APIs. In this section, we show how to configure a cross-account Amazon Cognito user pool using the Amazon API Gateway console. These instructions assume that you already have an API Gateway API in one AWS account and a Amazon Cognito user pool in another account. Create a cross-account Amazon Cognito authorizer for a REST API Log in to the Amazon API Gateway console in the account that has your API in it, and then do the following: 1. Create a new API, or select an existing API in API Gateway. 2. In the main navigation pane, choose Authorizers. 3. Choose Create authorizer. 4. To configure the new authorizer to use a user pool, do the following: a. b. c. d. e. For Authorizer name, enter a name. For Authorizer type, select Cognito. For Cognito user pool, enter the full ARN for the user pool that you have in your second account. Note In the Amazon Cognito console, you can find the ARN for your user pool in the Pool ARN field of the General Settings pane. For Token source, enter Authorization as the header name to pass the identity or access token that's returned by Amazon Cognito when a user signs in successfully. (Optional) Enter a regular expression in the Token validation field to validate the aud (audience) field of the identity token before the request is authorized with Amazon Access control 397 Amazon API Gateway Developer Guide Cognito. Note that when using an access token this validation rejects the request due to the access token not containing the aud field. f. Choose Create authorizer. Create an Amazon Cognito authorizer for a REST API using AWS CloudFormation You can use AWS CloudFormation to create an Amazon Cognito user pool and an Amazon Cognito authorizer. The example AWS CloudFormation template does the following: • Create an Amazon Cognito user pool. The client must first sign the user in to the user pool and obtain an identity or access token. If you're using access tokens to authorize API method calls, be sure to configure the app integration with the user pool to set up the custom scopes that you want on a given resource server. • Creates an API Gateway API with a GET method. • Creates an Amazon Cognito authorizer that uses the Authorization header as the token source. AWSTemplateFormatVersion: 2010-09-09 Resources: UserPool: Type: AWS::Cognito::UserPool Properties: AccountRecoverySetting: RecoveryMechanisms: - Name: verified_phone_number Priority: 1 - Name: verified_email Priority: 2 AdminCreateUserConfig: AllowAdminCreateUserOnly: true EmailVerificationMessage: The verification code to your new account is {####} EmailVerificationSubject: Verify your new account SmsVerificationMessage: The verification code to your new account is {####} VerificationMessageTemplate: DefaultEmailOption: CONFIRM_WITH_CODE EmailMessage: The verification code to your new account is {####} EmailSubject: Verify your new account SmsMessage: The verification code to your new account is {####} UpdateReplacePolicy: Retain Access control 398 Amazon API Gateway Developer Guide DeletionPolicy: Retain CogAuthorizer: Type: AWS::ApiGateway::Authorizer Properties: Name: CognitoAuthorizer RestApiId: Ref: Api Type: COGNITO_USER_POOLS IdentitySource: method.request.header.Authorization ProviderARNs: - Fn::GetAtt: - UserPool - Arn Api: Type: AWS::ApiGateway::RestApi Properties: Name: MyCogAuthApi ApiDeployment: Type: AWS::ApiGateway::Deployment Properties: RestApiId: Ref: Api DependsOn: - CogAuthorizer - ApiGET
apigateway-dg-111
apigateway-dg.pdf
111
code to your new account is {####} EmailVerificationSubject: Verify your new account SmsVerificationMessage: The verification code to your new account is {####} VerificationMessageTemplate: DefaultEmailOption: CONFIRM_WITH_CODE EmailMessage: The verification code to your new account is {####} EmailSubject: Verify your new account SmsMessage: The verification code to your new account is {####} UpdateReplacePolicy: Retain Access control 398 Amazon API Gateway Developer Guide DeletionPolicy: Retain CogAuthorizer: Type: AWS::ApiGateway::Authorizer Properties: Name: CognitoAuthorizer RestApiId: Ref: Api Type: COGNITO_USER_POOLS IdentitySource: method.request.header.Authorization ProviderARNs: - Fn::GetAtt: - UserPool - Arn Api: Type: AWS::ApiGateway::RestApi Properties: Name: MyCogAuthApi ApiDeployment: Type: AWS::ApiGateway::Deployment Properties: RestApiId: Ref: Api DependsOn: - CogAuthorizer - ApiGET ApiDeploymentStageprod: Type: AWS::ApiGateway::Stage Properties: RestApiId: Ref: Api DeploymentId: Ref: ApiDeployment StageName: prod ApiGET: Type: AWS::ApiGateway::Method Properties: HttpMethod: GET ResourceId: Fn::GetAtt: - Api - RootResourceId RestApiId: Ref: Api AuthorizationType: COGNITO_USER_POOLS Access control 399 Amazon API Gateway Developer Guide AuthorizerId: Ref: CogAuthorizer Integration: IntegrationHttpMethod: GET Type: HTTP_PROXY Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets Outputs: ApiEndpoint: Value: Fn::Join: - "" - - https:// - Ref: Api - .execute-api. - Ref: AWS::Region - "." - Ref: AWS::URLSuffix - / - Ref: ApiDeploymentStageprod - / Integrations for REST APIs in API Gateway After setting up an API method, you must integrate it with an endpoint in the backend. A backend endpoint is also referred to as an integration endpoint and can be a Lambda function, an HTTP webpage, or an AWS service action. As with the API method, the API integration has an integration request and an integration response. An integration request encapsulates an HTTP request received by the backend. It might or might not differ from the method request submitted by the client. An integration response is an HTTP response encapsulating the output returned by the backend. Setting up an integration request involves the following: configuring how to pass client-submitted method requests to the backend; configuring how to transform the request data, if necessary, to the integration request data; and specifying which Lambda function to call, specifying which HTTP server to forward the incoming request to, or specifying the AWS service action to invoke. Setting up an integration response (applicable to non-proxy integrations only) involves the following: configuring how to pass the backend-returned result to a method response of a given status code, configuring how to transform specified integration response parameters to Integrations 400 Amazon API Gateway Developer Guide preconfigured method response parameters, and configuring how to map the integration response body to the method response body according to the specified body-mapping templates. Programmatically, an integration request is encapsulated by the Integration resource and an integration response by the IntegrationResponse resource of API Gateway. To set up an integration request, you create an Integration resource and use it to configure the integration endpoint URL. You then set the IAM permissions to access the backend, and specify mappings to transform the incoming request data before passing it to the backend. To set up an integration response for non-proxy integration, you create an IntegrationResponse resource and use it to set its target method response. You then configure how to map backend output to the method response. Topics • Set up an integration request in API Gateway • Set up an integration response in API Gateway • Lambda integrations for REST APIs in API Gateway • HTTP integrations for REST APIs in API Gateway • Private integrations for REST APIs in API Gateway • Mock integrations for REST APIs in API Gateway Set up an integration request in API Gateway To set up an integration request, you perform the following required and optional tasks: 1. Choose an integration type that determines how method request data is passed to the backend. 2. For non-mock integrations, specify an HTTP method and the URI of the targeted integration endpoint, except for the MOCK integration. 3. For integrations with Lambda functions and other AWS service actions, set an IAM role with required permissions for API Gateway to call the backend on your behalf. 4. For non-proxy integrations, set necessary parameter mappings to map predefined method request parameters to appropriate integration request parameters. 5. For non-proxy integrations, set necessary body mappings to map the incoming method request body of a given content type according to the specified mapping template. 6. For non-proxy integrations, specify the condition under which the incoming method request data is passed through to the backend as-is. Integrations 401 Amazon API Gateway Developer Guide 7. Optionally, specify how to handle type conversion for a binary payload. 8. Optionally, declare a cache namespace name and cache key parameters to enable API caching. Performing these tasks involves creating an Integration resource of API Gateway and setting appropriate property values. You can do so using the API Gateway console, AWS CLI commands, an AWS SDK, or the API Gateway REST API. Topics • Basic tasks of an API integration request • Choose an API Gateway API
apigateway-dg-112
apigateway-dg.pdf
112
under which the incoming method request data is passed through to the backend as-is. Integrations 401 Amazon API Gateway Developer Guide 7. Optionally, specify how to handle type conversion for a binary payload. 8. Optionally, declare a cache namespace name and cache key parameters to enable API caching. Performing these tasks involves creating an Integration resource of API Gateway and setting appropriate property values. You can do so using the API Gateway console, AWS CLI commands, an AWS SDK, or the API Gateway REST API. Topics • Basic tasks of an API integration request • Choose an API Gateway API integration type • Set up a proxy integration with a proxy resource • Set up an API integration request using the API Gateway console Basic tasks of an API integration request An integration request is an HTTP request that API Gateway submits to the backend, passing along the client-submitted request data, and transforming the data, if necessary. The HTTP method (or verb) and URI of the integration request are dictated by the backend (that is, the integration endpoint). They can be the same as or different from the method request's HTTP method and URI, respectively. For example, when a Lambda function returns a file that is fetched from Amazon S3, you can expose this operation intuitively as a GET method request to the client even though the corresponding integration request requires that a POST request be used to invoke the Lambda function. For an HTTP endpoint, it is likely that the method request and the corresponding integration request both use the same HTTP verb. However, this is not required. You can integrate the following method request: GET /{var}?query=value Host: api.domain.net With the following integration request: POST / Host: service.domain.com Content-Type: application/json Integrations 402 Amazon API Gateway Content-Length: ... { path: "{var}'s value", type: "value" } Developer Guide As an API developer, you can use whatever HTTP verb and URI for a method request suit your requirements. But you must follow the requirements of the integration endpoint. When the method request data differs from the integration request data, you can reconcile the difference by providing mappings from the method request data to the integration request data. In the preceding examples, the mapping translates the path variable ({var}) and the query parameter (query) values of the GET method request to the values of the integration request's payload properties of path and type. Other mappable request data includes request headers and body. These are described in the section called “Parameter mapping”. When setting up the HTTP or HTTP proxy integration request, you assign the backend HTTP endpoint URL as the integration request URI value. For example, in the PetStore API, the method request to get a page of pets has the following integration request URI: http://petstore-demo-endpoint.execute-api.com/petstore/pets When setting up the Lambda or Lambda proxy integration, you assign the Amazon Resource Name (ARN) for invoking the Lambda function as the integration request URI value. This ARN has the following format: arn:aws:apigateway:api-region:lambda:path//2015-03-31/functions/arn:aws:lambda:lambda- region:account-id:function:lambda-function-name/invocations The part after arn:aws:apigateway:api-region:lambda:path/, namely, /2015-03-31/ functions/arn:aws:lambda:lambda-region:account-id:function:lambda-function- name/invocations, is the REST API URI path of the Lambda Invoke action. If you use the API Gateway console to set up the Lambda integration, API Gateway creates the ARN and assigns it to the integration URI after prompting you to choose the lambda-function-name from a region. When setting up the integration request with another AWS service action, the integration request URI is also an ARN, similar to the integration with the Lambda Invoke action. For example, for the Integrations 403 Amazon API Gateway Developer Guide integration with the GetBucket action of Amazon S3, the integration request URI is an ARN of the following format: arn:aws:apigateway:api-region:s3:path/{bucket} The integration request URI is of the path convention to specify the action, where {bucket} is the placeholder of a bucket name. Alternatively, an AWS service action can be referenced by its name. Using the action name, the integration request URI for the GetBucket action of Amazon S3 becomes the following: arn:aws:apigateway:api-region:s3:action/GetBucket With the action-based integration request URI, the bucket name ({bucket}) must be specified in the integration request body ({ Bucket: "{bucket}" }), following the input format of GetBucket action. For AWS integrations, you must also configure credentials to allow API Gateway to call the integrated actions. You can create a new or choose an existing IAM role for API Gateway to call the action and then specify the role using its ARN. The following shows an example of this ARN: arn:aws:iam::account-id:role/iam-role-name This IAM role must contain a policy to allow the action to be executed. It must also have API Gateway declared (in the role's trust relationship) as a trusted entity to assume the role. Such permissions can be granted on the action itself. They are known as resource-based permissions. For the Lambda integration, you can call
apigateway-dg-113
apigateway-dg.pdf
113
to allow API Gateway to call the integrated actions. You can create a new or choose an existing IAM role for API Gateway to call the action and then specify the role using its ARN. The following shows an example of this ARN: arn:aws:iam::account-id:role/iam-role-name This IAM role must contain a policy to allow the action to be executed. It must also have API Gateway declared (in the role's trust relationship) as a trusted entity to assume the role. Such permissions can be granted on the action itself. They are known as resource-based permissions. For the Lambda integration, you can call the Lambda's addPermission action to set the resource-based permissions and then set credentials to null in the API Gateway integration request. We discussed the basic integration setup. Advanced settings involve mapping method request data to the integration request data. For more information, see the section called “Data transformations”. Choose an API Gateway API integration type You choose an API integration type according to the types of integration endpoint you work with and how you want data to pass to and from the integration endpoint. For a Lambda function, you can have the Lambda proxy integration, or the Lambda custom integration. For an HTTP endpoint, Integrations 404 Amazon API Gateway Developer Guide you can have the HTTP proxy integration or the HTTP custom integration. For an AWS service action, you have the AWS integration of the non-proxy type only. API Gateway also supports the mock integration, where API Gateway serves as an integration endpoint to respond to a method request. The Lambda custom integration is a special case of the AWS integration, where the integration endpoint corresponds to the function-invoking action of the Lambda service. Programmatically, you choose an integration type by setting the type property on the Integration resource. For the Lambda proxy integration, the value is AWS_PROXY. For the Lambda custom integration and all other AWS integrations, it is AWS. For the HTTP proxy integration and HTTP integration, the value is HTTP_PROXY and HTTP, respectively. For the mock integration, the type value is MOCK. The Lambda proxy integration supports a streamlined integration setup with a single Lambda function. The setup is simple and can evolve with the backend without having to tear down the existing setup. For these reasons, it is highly recommended for integration with a Lambda function. In contrast, the Lambda custom integration allows for reuse of configured mapping templates for various integration endpoints that have similar requirements of the input and output data formats. The setup is more involved and is recommended for more advanced application scenarios. Similarly, the HTTP proxy integration has a streamlined integration setup and can evolve with the backend without having to tear down the existing setup. The HTTP custom integration is more involved to set up, but allows for reuse of configured mapping templates for other integration endpoints. The following list summarizes the supported integration types: • AWS: This type of integration lets an API expose AWS service actions. In AWS integration, you must configure both the integration request and integration response and set up necessary data mappings from the method request to the integration request, and from the integration response to the method response. • AWS_PROXY: This type of integration lets an API method be integrated with the Lambda function invocation action with a flexible, versatile, and streamlined integration setup. This integration relies on direct interactions between the client and the integrated Lambda function. With this type of integration, also known as the Lambda proxy integration, you do not set the integration request or the integration response. API Gateway passes the incoming request Integrations 405 Amazon API Gateway Developer Guide from the client as the input to the backend Lambda function. The integrated Lambda function takes the input of this format and parses the input from all available sources, including request headers, URL path variables, query string parameters, and applicable body. The function returns the result following this output format. This is the preferred integration type to call a Lambda function through API Gateway and is not applicable to any other AWS service actions, including Lambda actions other than the function- invoking action. • HTTP: This type of integration lets an API expose HTTP endpoints in the backend. With the HTTP integration, also known as the HTTP custom integration, you must configure both the integration request and integration response. You must set up necessary data mappings from the method request to the integration request, and from the integration response to the method response. • HTTP_PROXY: The HTTP proxy integration allows a client to access the backend HTTP endpoints with a streamlined integration setup on single API method. You do not set the integration request or the integration response. API Gateway passes the incoming request from the client to the HTTP
apigateway-dg-114
apigateway-dg.pdf
114
an API expose HTTP endpoints in the backend. With the HTTP integration, also known as the HTTP custom integration, you must configure both the integration request and integration response. You must set up necessary data mappings from the method request to the integration request, and from the integration response to the method response. • HTTP_PROXY: The HTTP proxy integration allows a client to access the backend HTTP endpoints with a streamlined integration setup on single API method. You do not set the integration request or the integration response. API Gateway passes the incoming request from the client to the HTTP endpoint and passes the outgoing response from the HTTP endpoint to the client. • MOCK: This type of integration lets API Gateway return a response without sending the request further to the backend. This is useful for API testing because it can be used to test the integration set up without incurring charges for using the backend and to enable collaborative development of an API. In collaborative development, a team can isolate their development effort by setting up simulations of API components owned by other teams by using the MOCK integrations. It is also used to return CORS-related headers to ensure that the API method permits CORS access. In fact, the API Gateway console integrates the OPTIONS method to support CORS with a mock integration. Gateway responses are other examples of mock integrations. Set up a proxy integration with a proxy resource To set up a proxy integration in an API Gateway API with a proxy resource, you perform the following tasks: • Create a proxy resource with a greedy path variable of {proxy+}. • Set the ANY method on the proxy resource. • Integrate the resource and method with a backend using the HTTP or Lambda integration type. Integrations 406 Amazon API Gateway Note Developer Guide Greedy path variables, ANY methods, and proxy integration types are independent features, although they are commonly used together. You can configure a specific HTTP method on a greedy resource or apply non-proxy integration types to a proxy resource. API Gateway enacts certain restrictions and limitations when handling methods with either a Lambda proxy integration or an HTTP proxy integration. For details, see the section called “Important notes”. Note When using proxy integration with a passthrough, API Gateway returns the default Content-Type:application/json header if the content type of a payload is unspecified. A proxy resource is most powerful when it is integrated with a backend using either HTTP proxy integration or Lambda proxy integration. HTTP proxy integration with a proxy resource The HTTP proxy integration, designated by HTTP_PROXY in the API Gateway REST API, is for integrating a method request with a backend HTTP endpoint. With this integration type, API Gateway simply passes the entire request and response between the frontend and the backend, subject to certain restrictions and limitations. Note HTTP proxy integration supports multi-valued headers and query strings. When applying the HTTP proxy integration to a proxy resource, you can set up your API to expose a portion or an entire endpoint hierarchy of the HTTP backend with a single integration setup. For example, suppose the backend of the website is organized into multiple branches of tree nodes off the root node (/site) as: /site/a0/a1/.../aN, /site/b0/b1/.../bM, etc. If you integrate the ANY method on a proxy resource of /api/{proxy+} with the backend endpoints with URL paths Integrations 407 Amazon API Gateway Developer Guide of /site/{proxy}, a single integration request can support any HTTP operations (GET, POST, etc.) on any of [a0, a1, ..., aN, b0, b1, ...bM, ...]. If you apply a proxy integration to a specific HTTP method, for example, GET, instead, the resulting integration request works with the specified (that is, GET) operations on any of those backend nodes. Lambda proxy integration with a proxy resource The Lambda proxy integration, designated by AWS_PROXY in the API Gateway REST API, is for integrating a method request with a Lambda function in the backend. With this integration type, API Gateway applies a default mapping template to send the entire request to the Lambda function and transforms the output from the Lambda function to HTTP responses. Similarly, you can apply the Lambda proxy integration to a proxy resource of /api/{proxy+} to set up a single integration to have a backend Lambda function react individually to changes in any of the API resources under /api. Set up an API integration request using the API Gateway console An API method setup defines the method and describes its behaviors. To set up a method, you must specify a resource, including the root ("/"), on which the method is exposed, an HTTP method (GET, POST, etc.), and how it will be integrated with the targeted backend. The method request and response specify the contract with the calling
apigateway-dg-115
apigateway-dg.pdf
115
integration to a proxy resource of /api/{proxy+} to set up a single integration to have a backend Lambda function react individually to changes in any of the API resources under /api. Set up an API integration request using the API Gateway console An API method setup defines the method and describes its behaviors. To set up a method, you must specify a resource, including the root ("/"), on which the method is exposed, an HTTP method (GET, POST, etc.), and how it will be integrated with the targeted backend. The method request and response specify the contract with the calling app, stipulating which parameters the API can receive and what the response looks like. The following procedures describe how to use the API Gateway console to create an integration request. Topics • Set up a Lambda integration • Set up an HTTP integration • Set up an AWS service integration • Set up a mock integration Set up a Lambda integration Use a Lambda function integration to integrate your API with a Lambda function. At the API level, this is an AWS integration type if you create a non-proxy integration, or an AWS_PROXY integration type if you create a proxy integration. Integrations 408 Amazon API Gateway To set up a Lambda integration Developer Guide 1. 2. 3. 4. In the Resources pane, choose Create method. For Method type, select an HTTP method. For Integration type, choose Lambda function. To use a Lambda proxy integration, turn on Lambda proxy integration. To learn more about Lambda proxy integrations, see the section called “ Understand Lambda proxy integration ”. 5. For Lambda function, enter the name of the Lambda function. If you are using a Lambda function in a different Region than your API, select the Region from the dropdown menu and enter the name of the Lambda function. If you are using a cross- account Lambda function, enter the function ARN. 6. To use the default timeout value of 29 seconds, keep Default timeout turned on. To set a custom timeout, choose Default timeout and enter a timeout value between 50 and 29000 milliseconds. 7. (Optional) You can configure the method request settings using the following dropdown menus. Choose Method request settings and configure your method request. For more information, see step 3 of the section called “Edit a method request in the console”. You can also configure your method request settings after you create your method. 8. Choose Create method. Set up an HTTP integration Use an HTTP integration to integrate your API with an HTTP endpoint. At the API level, this is the HTTP integration type. To set up an HTTP integration 1. 2. 3. 4. 5. In the Resources pane, choose Create method. For Method type, select an HTTP method. For Integration type, choose HTTP. To use an HTTP proxy integration, turn on HTTP proxy integration. To learn more about HTTP proxy integrations, see the section called “Set up HTTP proxy integrations in API Gateway”. For HTTP method, choose the HTTP method type that most closely matches the method in the HTTP backend. Integrations 409 Amazon API Gateway Developer Guide 6. 7. 8. 9. For Endpoint URL, enter the URL of the HTTP backend you want this method to use. For Content handling, select a content handling behavior. To use the default timeout value of 29 seconds, keep Default timeout turned on. To set a custom timeout, choose Default timeout and enter a timeout value between 50 and 29000 milliseconds. (Optional) You can configure the method request settings using the following dropdown menus. Choose Method request settings and configure your method request. For more information, see step 3 of the section called “Edit a method request in the console”. You can also configure your method request settings after you create your method. 10. Choose Create method. Set up an AWS service integration Use an AWS service integration to integrate your API directly with an AWS service. At the API level, this is the AWS integration type. To set up an API Gateway API to do any of the following: • Create a new Lambda function. • Set a resource permission on the Lambda function. • Perform any other Lambda service actions. You must choose AWS service. To set up an AWS service integration 1. 2. 3. 4. 5. 6. In the Resources pane, choose Create method. For Method type, select an HTTP method. For Integration type, choose AWS service. For AWS Region, choose the AWS Region you want this method to use to call the action. For AWS service, choose the AWS service you want this method to call. For AWS subdomain, enter the subdomain used by the AWS service. Typically, you would leave this blank. Some AWS services can support subdomains as part of the hosts. Consult the
apigateway-dg-116
apigateway-dg.pdf
116
service actions. You must choose AWS service. To set up an AWS service integration 1. 2. 3. 4. 5. 6. In the Resources pane, choose Create method. For Method type, select an HTTP method. For Integration type, choose AWS service. For AWS Region, choose the AWS Region you want this method to use to call the action. For AWS service, choose the AWS service you want this method to call. For AWS subdomain, enter the subdomain used by the AWS service. Typically, you would leave this blank. Some AWS services can support subdomains as part of the hosts. Consult the service documentation for the availability and, if available, details. Integrations 410 Amazon API Gateway Developer Guide 7. 8. For HTTP method, choose the HTTP method type that corresponds to the action. For HTTP method type, see the API reference documentation for the AWS service you chose for AWS service. For Action type, select to either Use action name to use an API action or Use path override to use a custom resource path. For available actions and custom resource paths, see the API reference documentation for the AWS service you chose for AWS service. 9. Enter either an Action name or Path override. 10. For Execution role, enter the ARN of the IAM role that the method will use to call the action. To create the IAM role, you can adapt the instructions in the section called “Step 1: Create the AWS service proxy execution role”. Specify an access policy of the following format, with the desired number of action and resource statements: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "action-statement" ], "Resource": [ "resource-statement" ] }, ... ] } For the action and resource statement syntax, see the documentation for the AWS service you chose for AWS service. For the IAM role's trust relationship, specify the following, which enables API Gateway to take action on behalf of your AWS account: { "Version": "2012-10-17", "Statement": [ { "Sid": "", Integrations 411 Amazon API Gateway Developer Guide "Effect": "Allow", "Principal": { "Service": "apigateway.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } 11. To use the default timeout value of 29 seconds, keep Default timeout turned on. To set a custom timeout, choose Default timeout and enter a timeout value between 50 and 29000 milliseconds. 12. (Optional) You can configure the method request settings using the following dropdown menus. Choose Method request settings and configure your method request. For more information, see step 3 of the section called “Edit a method request in the console”. You can also configure your method request settings after you create your method. 13. Choose Create method. Set up a mock integration Use a mock integration if you want API Gateway to act as your backend to return static responses. At the API level, this is the MOCK integration type. Typically, you can use the MOCK integration when your API is not yet final, but you want to generate API responses to unblock dependent teams for testing. For the OPTION method, API Gateway sets the MOCK integration as default to return CORS- enabling headers for the applied API resource. To set up a mock integration 1. 2. 3. 4. In the Resources pane, choose Create method. For Method type, select an HTTP method. For Integration type, choose Mock. (Optional) You can configure the method request settings using the following dropdown menus. Choose Method request settings and configure your method request. For more information, see step 3 of the section called “Edit a method request in the console”. You can also configure your method request settings after you create your method. 5. Choose Create method. Integrations 412 Amazon API Gateway Developer Guide Set up an integration response in API Gateway For a non-proxy integration, you must set up at least one integration response, and make it the default response, to pass the result returned from the backend to the client. You can choose to pass through the result as-is or to transform the integration response data to the method response data if the two have different formats. For a proxy integration, API Gateway automatically passes the backend output to the client as an HTTP response. You do not set either an integration response or a method response. To set up an integration response, you perform the following required and optional tasks: 1. Specify an HTTP status code of a method response to which the integration response data is mapped. This is required. 2. Define a regular expression to select backend output to be represented by this integration response. If you leave this empty, the response is the default response that is used to catch any response not yet configured. 3. If needed, declare mappings consisting of key-value pairs to map specified integration response parameters to given method
apigateway-dg-117
apigateway-dg.pdf
117
not set either an integration response or a method response. To set up an integration response, you perform the following required and optional tasks: 1. Specify an HTTP status code of a method response to which the integration response data is mapped. This is required. 2. Define a regular expression to select backend output to be represented by this integration response. If you leave this empty, the response is the default response that is used to catch any response not yet configured. 3. If needed, declare mappings consisting of key-value pairs to map specified integration response parameters to given method response parameters. 4. If needed, add body-mapping templates to transform given integration response payloads into specified method response payloads. 5. If needed, specify how to handle type conversion for a binary payload. An integration response is an HTTP response encapsulating the backend response. For an HTTP endpoint, the backend response is an HTTP response. The integration response status code can take the backend-returned status code, and the integration response body is the backend- returned payload. For a Lambda endpoint, the backend response is the output returned from the Lambda function. With the Lambda integration, the Lambda function output is returned as a 200 OK response. The payload can contain the result as JSON data, including a JSON string or a JSON object, or an error message as a JSON object. You can assign a regular expression to the selectionPattern property to map an error response to an appropriate HTTP error response. For more information about the Lambda function error response, see Handle Lambda errors in API Gateway. With the Lambda proxy integration, the Lambda function must return output of the following format: { statusCode: "...", // a valid HTTP status code Integrations 413 Amazon API Gateway headers: { custom-header: "..." // any API-specific custom header }, body: "...", // a JSON string. isBase64Encoded: true|false // for binary support } Developer Guide There is no need to map the Lambda function response to its proper HTTP response. To return the result to the client, set up the integration response to pass the endpoint response through as-is to the corresponding method response. Or you can map the endpoint response data to the method response data. The response data that can be mapped includes the response status code, response header parameters, and response body. If no method response is defined for the returned status code, API Gateway returns a 500 error. For more information, see Override your API's request and response parameters and status codes for REST APIs in API Gateway. Lambda integrations for REST APIs in API Gateway You can integrate an API method with a Lambda function using Lambda proxy integration or Lambda non-proxy (custom) integration. In Lambda proxy integration, the required setup is simple. Set the integration's HTTP method to POST, the integration endpoint URI to the ARN of the Lambda function invocation action of a specific Lambda function, and grant API Gateway permission to call the Lambda function on your behalf. In Lambda non-proxy integration, in addition to the proxy integration setup steps, you also specify how the incoming request data is mapped to the integration request and how the resulting integration response data is mapped to the method response. Topics • Lambda proxy integrations in API Gateway • Set up Lambda custom integrations in API Gateway • Set up asynchronous invocation of the backend Lambda function • Handle Lambda errors in API Gateway Lambda proxy integrations in API Gateway The following section shows how to use a Lambda proxy integration. Integrations 414 Amazon API Gateway Topics • Understand API Gateway Lambda proxy integration • Support for multi-value headers and query string parameters • Input format of a Lambda function for proxy integration • Output format of a Lambda function for proxy integration Developer Guide • Set up Lambda proxy integration for API Gateway using the AWS CLI • Set up a proxy resource with Lambda proxy integration with an OpenAPI definition Understand API Gateway Lambda proxy integration Amazon API Gateway Lambda proxy integration is a simple, powerful, and nimble mechanism to build an API with a setup of a single API method. The Lambda proxy integration allows the client to call a single Lambda function in the backend. The function accesses many resources or features of other AWS services, including calling other Lambda functions. In Lambda proxy integration, when a client submits an API request, API Gateway passes to the integrated Lambda function an event object, except that the order of the request parameters is not preserved. This request data includes the request headers, query string parameters, URL path variables, payload, and API configuration data. The configuration data can include current deployment stage name, stage variables, user identity, or authorization context (if any). The backend Lambda function parses
apigateway-dg-118
apigateway-dg.pdf
118
client to call a single Lambda function in the backend. The function accesses many resources or features of other AWS services, including calling other Lambda functions. In Lambda proxy integration, when a client submits an API request, API Gateway passes to the integrated Lambda function an event object, except that the order of the request parameters is not preserved. This request data includes the request headers, query string parameters, URL path variables, payload, and API configuration data. The configuration data can include current deployment stage name, stage variables, user identity, or authorization context (if any). The backend Lambda function parses the incoming request data to determine the response that it returns. For API Gateway to pass the Lambda output as the API response to the client, the Lambda function must return the result in this format. Because API Gateway doesn't intervene very much between the client and the backend Lambda function for the Lambda proxy integration, the client and the integrated Lambda function can adapt to changes in each other without breaking the existing integration setup of the API. To enable this, the client must follow application protocols enacted by the backend Lambda function. You can set up a Lambda proxy integration for any API method. But a Lambda proxy integration is more potent when it is configured for an API method involving a generic proxy resource. The generic proxy resource can be denoted by a special templated path variable of {proxy+}, the catch-all ANY method placeholder, or both. The client can pass the input to the backend Lambda function in the incoming request as request parameters or applicable payload. The request parameters include headers, URL path variables, query string parameters, and the applicable payload. The integrated Lambda function verifies all of the input sources before processing the Integrations 415 Amazon API Gateway Developer Guide request and responding to the client with meaningful error messages if any of the required input is missing. When calling an API method integrated with the generic HTTP method of ANY and the generic resource of {proxy+}, the client submits a request with a particular HTTP method in place of ANY. The client also specifies a particular URL path instead of {proxy+}, and includes any required headers, query string parameters, or an applicable payload. The following list summarizes runtime behaviors of different API methods with the Lambda proxy integration: • ANY /{proxy+}: The client must choose a particular HTTP method, must set a particular resource path hierarchy, and can set any headers, query string parameters, and applicable payload to pass the data as input to the integrated Lambda function. • ANY /res: The client must choose a particular HTTP method and can set any headers, query string parameters, and applicable payload to pass the data as input to the integrated Lambda function. • GET|POST|PUT|... /{proxy+}: The client can set a particular resource path hierarchy, any headers, query string parameters, and applicable payload to pass the data as input to the integrated Lambda function. • GET|POST|PUT|... /res/{path}/...: The client must choose a particular path segment (for the {path} variable) and can set any request headers, query string parameters, and applicable payload to pass input data to the integrated Lambda function. • GET|POST|PUT|... /res: The client can choose any request headers, query string parameters, and applicable payload to pass input data to the integrated Lambda function. Both the proxy resource of {proxy+} and the custom resource of {custom} are expressed as templated path variables. However {proxy+} can refer to any resource along a path hierarchy, while {custom} refers to a particular path segment only. For example, a grocery store might organize its online product inventory by department names, produce categories, and product types. The grocery store's website can then represent available products by the following templated path variables of custom resources: /{department}/{produce-category}/ {product-type}. For example, apples are represented by /produce/fruit/apple and carrots by /produce/vegetables/carrot. It can also use /{proxy+} to represent any department, any produce category, or any product type that a customer can search for while shopping in the online store. For example, /{proxy+} can refer to any of the following items: Integrations 416 Amazon API Gateway • /produce • /produce/fruit • /produce/vegetables/carrot Developer Guide To let customers search for any available product, its produce category, and the associated store department, you can expose a single method of GET /{proxy+} with read-only permissions. Similarly, to allow a supervisor to update the produce department's inventory, you can set up another single method of PUT /produce/{proxy+} with read/write permissions. To allow a cashier to update the running total of a vegetable, you can set up a POST /produce/ vegetables/{proxy+} method with read/write permissions. To let a store manager perform any possible action on any available product, the online store developer can expose the ANY / {proxy+} method with
apigateway-dg-119
apigateway-dg.pdf
119
let customers search for any available product, its produce category, and the associated store department, you can expose a single method of GET /{proxy+} with read-only permissions. Similarly, to allow a supervisor to update the produce department's inventory, you can set up another single method of PUT /produce/{proxy+} with read/write permissions. To allow a cashier to update the running total of a vegetable, you can set up a POST /produce/ vegetables/{proxy+} method with read/write permissions. To let a store manager perform any possible action on any available product, the online store developer can expose the ANY / {proxy+} method with read/write permissions. In any case, at run time, the customer or the employee must select a particular product of a given type in a chosen department, a specific produce category in a chosen department, or a specific department. For more information about setting up API Gateway proxy integrations, see Set up a proxy integration with a proxy resource. Proxy integration requires that the client have more detailed knowledge of the backend requirements. Therefore, to ensure optimal app performance and user experience, the backend developer must communicate clearly to the client developer the requirements of the backend, and provide a robust error feedback mechanism when the requirements are not met. Support for multi-value headers and query string parameters API Gateway supports multiple headers and query string parameters that have the same name. Multi-value headers as well as single-value headers and parameters can be combined in the same requests and responses. For more information, see Input format of a Lambda function for proxy integration and Output format of a Lambda function for proxy integration. Input format of a Lambda function for proxy integration In Lambda proxy integration, API Gateway maps the entire client request to the input event parameter of the backend Lambda function. The following example shows the structure of an event that API Gateway sends to a Lambda proxy integration. { "resource": "/my/path", Integrations 417 Amazon API Gateway Developer Guide "path": "/my/path", "httpMethod": "GET", "headers": { "header1": "value1", "header2": "value1,value2" }, "multiValueHeaders": { "header1": [ "value1" ], "header2": [ "value1", "value2" ] }, "queryStringParameters": { "parameter1": "value1,value2", "parameter2": "value" }, "multiValueQueryStringParameters": { "parameter1": [ "value1", "value2" ], "parameter2": [ "value" ] }, "requestContext": { "accountId": "123456789012", "apiId": "id", "authorizer": { "claims": null, "scopes": null }, "domainName": "id.execute-api.us-east-1.amazonaws.com", "domainPrefix": "id", "extendedRequestId": "request-id", "httpMethod": "GET", "identity": { "accessKey": null, "accountId": null, "caller": null, "cognitoAuthenticationProvider": null, Integrations 418 Amazon API Gateway Developer Guide "cognitoAuthenticationType": null, "cognitoIdentityId": null, "cognitoIdentityPoolId": null, "principalOrgId": null, "sourceIp": "IP", "user": null, "userAgent": "user-agent", "userArn": null, "clientCert": { "clientCertPem": "CERT_CONTENT", "subjectDN": "www.example.com", "issuerDN": "Example issuer", "serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1", "validity": { "notBefore": "May 28 12:30:02 2019 GMT", "notAfter": "Aug 5 09:36:04 2021 GMT" } } }, "path": "/my/path", "protocol": "HTTP/1.1", "requestId": "id=", "requestTime": "04/Mar/2020:19:15:17 +0000", "requestTimeEpoch": 1583349317135, "resourceId": null, "resourcePath": "/my/path", "stage": "$default" }, "pathParameters": null, "stageVariables": null, "body": "Hello from Lambda!", "isBase64Encoded": false } Note In the input: • The headers key can only contain single-value headers. • The multiValueHeaders key can contain multi-value headers as well as single-value headers. Integrations 419 Amazon API Gateway Developer Guide • If you specify values for both headers and multiValueHeaders, API Gateway merges them into a single list. If the same key-value pair is specified in both, only the values from multiValueHeaders will appear in the merged list. In the input to the backend Lambda function, the requestContext object is a map of key-value pairs. In each pair, the key is the name of a $context variable property, and the value is the value of that property. API Gateway might add new keys to the map. Depending on the features that are enabled, the requestContext map may vary from API to API. For example, in the preceding example, no authorization type is specified, so no $context.authorizer.* or $context.identity.* properties are present. When an authorization type is specified, this causes API Gateway to pass authorized user information to the integration endpoint in a requestContext.identity object as follows: • When the authorization type is AWS_IAM, the authorized user information includes $context.identity.* properties. • When the authorization type is COGNITO_USER_POOLS (Amazon Cognito authorizer), the authorized user information includes $context.identity.cognito* and $context.authorizer.claims.* properties. • When the authorization type is CUSTOM (Lambda authorizer), the authorized user information includes $context.authorizer.principalId and other applicable $context.authorizer.* properties. Output format of a Lambda function for proxy integration In Lambda proxy integration, API Gateway requires the backend Lambda function to return output according to the following JSON format: { "isBase64Encoded": true|false, "statusCode": httpStatusCode, "headers": { "headerName": "headerValue", ... }, "multiValueHeaders": { "headerName": ["headerValue", "headerValue2", ...], ... }, "body": "..." } In the output: Integrations 420 Amazon API Gateway Developer Guide • The headers and multiValueHeaders keys can be unspecified if no extra response headers are to be returned. • The headers key can only
apigateway-dg-120
apigateway-dg.pdf
120
is CUSTOM (Lambda authorizer), the authorized user information includes $context.authorizer.principalId and other applicable $context.authorizer.* properties. Output format of a Lambda function for proxy integration In Lambda proxy integration, API Gateway requires the backend Lambda function to return output according to the following JSON format: { "isBase64Encoded": true|false, "statusCode": httpStatusCode, "headers": { "headerName": "headerValue", ... }, "multiValueHeaders": { "headerName": ["headerValue", "headerValue2", ...], ... }, "body": "..." } In the output: Integrations 420 Amazon API Gateway Developer Guide • The headers and multiValueHeaders keys can be unspecified if no extra response headers are to be returned. • The headers key can only contain single-value headers. • The multiValueHeaders key can contain multi-value headers as well as single-value headers. You can use the multiValueHeaders key to specify all of your extra headers, including any single-value ones. • If you specify values for both headers and multiValueHeaders, API Gateway merges them into a single list. If the same key-value pair is specified in both, only the values from multiValueHeaders will appear in the merged list. To enable CORS for the Lambda proxy integration, you must add Access-Control-Allow- Origin:domain-name to the output headers. domain-name can be * for any domain name. The output body is marshalled to the frontend as the method response payload. If body is a binary blob, you can encode it as a Base64-encoded string by setting isBase64Encoded to true and configuring */* as a Binary Media Type. Otherwise, you can set it to false or leave it unspecified. Note For more information about enabling binary support, see Enabling binary support using the API Gateway console. For an example Lambda function, see Return binary media from a Lambda proxy integration in API Gateway. If the function output is of a different format, API Gateway returns a 502 Bad Gateway error response. To return a response in a Lambda function in Node.js, you can use commands such as the following: • To return a successful result, call callback(null, {"statusCode": 200, "body": "results"}). • To throw an exception, call callback(new Error('internal server error')). • For a client-side error (if, for example, a required parameter is missing), you can call callback(null, {"statusCode": 400, "body": "Missing parameters of ..."}) to return the error without throwing an exception. In a Lambda async function in Node.js, the equivalent syntax would be: Integrations 421 Amazon API Gateway Developer Guide • To return a successful result, call return {"statusCode": 200, "body": "results"}. • To throw an exception, call throw new Error("internal server error"). • For a client-side error (if, for example, a required parameter is missing), you can call return {"statusCode": 400, "body": "Missing parameters of ..."} to return the error without throwing an exception. Set up Lambda proxy integration for API Gateway using the AWS CLI In this section, we show how to set up an API with the Lambda proxy integration using the AWS CLI. For detailed instructions for using the API Gateway console to configure a proxy resource with the Lambda proxy integration, see Tutorial: Create a REST API with a Lambda proxy integration. As an example, we use the following sample Lambda function as the backend of the API: export const handler = async(event, context) => { console.log('Received event:', JSON.stringify(event, null, 2)); var res ={ "statusCode": 200, "headers": { "Content-Type": "*/*" } }; var greeter = 'World'; if (event.greeter && event.greeter!=="") { greeter = event.greeter; } else if (event.body && event.body !== "") { var body = JSON.parse(event.body); if (body.greeter && body.greeter !== "") { greeter = body.greeter; } } else if (event.queryStringParameters && event.queryStringParameters.greeter && event.queryStringParameters.greeter !== "") { greeter = event.queryStringParameters.greeter; } else if (event.multiValueHeaders && event.multiValueHeaders.greeter && event.multiValueHeaders.greeter != "") { greeter = event.multiValueHeaders.greeter.join(" and "); } else if (event.headers && event.headers.greeter && event.headers.greeter != "") { greeter = event.headers.greeter; } res.body = "Hello, " + greeter + "!"; return res Integrations 422 Amazon API Gateway }; Developer Guide Comparing this to the Lambda custom integration setup in the section called “ Set up Lambda custom integrations ”, the input to this Lambda function can be expressed in the request parameters and body. You have more latitude to allow the client to pass the same input data. Here, the client can pass the greeter's name in as a query string parameter, a header, or a body property. The function can also support the Lambda custom integration. The API setup is simpler. You do not configure the method response or integration response at all. To set up a Lambda proxy integration using the AWS CLI 1. Use the following create-rest-api command to create an API: aws apigateway create-rest-api --name 'HelloWorld (AWS CLI)' The output will look like the following: { "name": "HelloWorldProxy (AWS CLI)", "id": "te6si5ach7", "rootResourceId" : "krznpq9xpg", "createdDate": 1508461860 } You use the API id (te6si5ach7) and the rootResourceId ( krznpq9xpg) throughout
apigateway-dg-121
apigateway-dg.pdf
121
greeter's name in as a query string parameter, a header, or a body property. The function can also support the Lambda custom integration. The API setup is simpler. You do not configure the method response or integration response at all. To set up a Lambda proxy integration using the AWS CLI 1. Use the following create-rest-api command to create an API: aws apigateway create-rest-api --name 'HelloWorld (AWS CLI)' The output will look like the following: { "name": "HelloWorldProxy (AWS CLI)", "id": "te6si5ach7", "rootResourceId" : "krznpq9xpg", "createdDate": 1508461860 } You use the API id (te6si5ach7) and the rootResourceId ( krznpq9xpg) throughout this example. 2. Use the following create-resource command to create an API Gateway Resource of / greeting: aws apigateway create-resource \ --rest-api-id te6si5ach7 \ --parent-id krznpq9xpg \ --path-part {proxy+} The output will look like the following: { "path": "/{proxy+}", "pathPart": "{proxy+}", Integrations 423 Amazon API Gateway Developer Guide "id": "2jf6xt", "parentId": "krznpq9xpg" } You use the {proxy+} resource's id value (2jf6xt) to create a method on the /{proxy+} resource in the next step. 3. Use the following put-method to create an ANY method request of ANY /{proxy+}: aws apigateway put-method --rest-api-id te6si5ach7 \ --resource-id 2jf6xt \ --http-method ANY \ --authorization-type "NONE" The output will look like the following: { "apiKeyRequired": false, "httpMethod": "ANY", "authorizationType": "NONE" } This API method allows the client to receive or send greetings from the Lambda function at the backend. 4. Use the following put-integration command to set up the integration of the ANY /{proxy+} method with a Lambda function, named HelloWorld. This function responds to the request with a message of "Hello, {name}!", if the greeter parameter is provided, or "Hello, World!", if the query string parameter is not set. aws apigateway put-integration \ --rest-api-id te6si5ach7 \ --resource-id 2jf6xt \ --http-method ANY \ --type AWS_PROXY \ --integration-http-method POST \ --uri arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:123456789012:function:HelloWorld/invocations \ --credentials arn:aws:iam::123456789012:role/apigAwsProxyRole Integrations 424 Amazon API Gateway Developer Guide Important For Lambda integrations, you must use the HTTP method of POST for the integration request, according to the specification of the Lambda service action for function invocations. The IAM role of apigAwsProxyRole must have policies allowing the apigateway service to invoke Lambda functions. For more information about IAM permissions, see the section called “ API Gateway permissions model for invoking an API”. The output will look like the following: { "passthroughBehavior": "WHEN_NO_MATCH", "cacheKeyParameters": [], "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:1234567890:function:HelloWorld/invocations", "httpMethod": "POST", "cacheNamespace": "vvom7n", "credentials": "arn:aws:iam::1234567890:role/apigAwsProxyRole", "type": "AWS_PROXY" } Instead of supplying an IAM role for credentials, you can use the add-permission command to add resource-based permissions. This is what the API Gateway console does. 5. Use the following create-deployment command to deploy the API to a test stage: aws apigateway create-deployment \ --rest-api-id te6si5ach7 \ --stage-name test 6. Test the API using the following cURL commands in a terminal. Calling the API with the query string parameter of ?greeter=jane: curl -X GET 'https://te6si5ach7.execute-api.us-west-2.amazonaws.com/test/greeting? greeter=jane' Integrations 425 Amazon API Gateway Developer Guide Calling the API with a header parameter of greeter:jane: curl -X GET https://te6si5ach7.execute-api.us-west-2.amazonaws.com/test/hi \ -H 'content-type: application/json' \ -H 'greeter: jane' Calling the API with a body of {"greeter":"jane"}: curl -X POST https://te6si5ach7.execute-api.us-west-2.amazonaws.com/test/hi \ -H 'content-type: application/json' \ -d '{ "greeter": "jane" }' In all the cases, the output is a 200 response with the following response body: Hello, jane! Set up a proxy resource with Lambda proxy integration with an OpenAPI definition To set up a proxy resource with the Lambda proxy integration type, create an API resource with a greedy path parameter (for example, /parent/{proxy+}) and integrate this resource with a Lambda function backend (for example, arn:aws:lambda:us- west-2:123456789012:function:SimpleLambda4ProxyResource) on the ANY method. The greedy path parameter must be at the end of the API resource path. As with a non-proxy resource, you can set up the proxy resource by using the API Gateway console, importing an OpenAPI definition file, or calling the API Gateway REST API directly. The following OpenAPI API definition file shows an example of an API with a proxy resource that is integrated with a Lambda function named SimpleLambda4ProxyResource. OpenAPI 3.0 { "openapi": "3.0.0", "info": { "version": "2016-09-12T17:50:37Z", "title": "ProxyIntegrationWithLambda" }, "paths": { "/{proxy+}": { Integrations 426 Amazon API Gateway Developer Guide "x-amazon-apigateway-any-method": { "parameters": [ { "name": "proxy", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": {}, "x-amazon-apigateway-integration": { "responses": { "default": { "statusCode": "200" } }, "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/ functions/arn:aws:lambda:us-east-1:123456789012:function:SimpleLambda4ProxyResource/ invocations", "passthroughBehavior": "when_no_match", "httpMethod": "POST", "cacheNamespace": "roq9wj", "cacheKeyParameters": [ "method.request.path.proxy" ], "type": "aws_proxy" } } } }, "servers": [ { "url": "https://gy415nuibc.execute-api.us-east-1.amazonaws.com/{basePath}", "variables": { "basePath": { "default": "/testStage" } } } ] } Integrations 427 Developer Guide Amazon API Gateway OpenAPI 2.0 { "swagger": "2.0", "info": { "version": "2016-09-12T17:50:37Z", "title": "ProxyIntegrationWithLambda" }, "host": "gy415nuibc.execute-api.us-east-1.amazonaws.com", "basePath": "/testStage", "schemes": [ "https" ], "paths": { "/{proxy+}": { "x-amazon-apigateway-any-method": { "produces": [ "application/json" ], "parameters": [ {
apigateway-dg-122
apigateway-dg.pdf
122
"proxy", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": {}, "x-amazon-apigateway-integration": { "responses": { "default": { "statusCode": "200" } }, "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/ functions/arn:aws:lambda:us-east-1:123456789012:function:SimpleLambda4ProxyResource/ invocations", "passthroughBehavior": "when_no_match", "httpMethod": "POST", "cacheNamespace": "roq9wj", "cacheKeyParameters": [ "method.request.path.proxy" ], "type": "aws_proxy" } } } }, "servers": [ { "url": "https://gy415nuibc.execute-api.us-east-1.amazonaws.com/{basePath}", "variables": { "basePath": { "default": "/testStage" } } } ] } Integrations 427 Developer Guide Amazon API Gateway OpenAPI 2.0 { "swagger": "2.0", "info": { "version": "2016-09-12T17:50:37Z", "title": "ProxyIntegrationWithLambda" }, "host": "gy415nuibc.execute-api.us-east-1.amazonaws.com", "basePath": "/testStage", "schemes": [ "https" ], "paths": { "/{proxy+}": { "x-amazon-apigateway-any-method": { "produces": [ "application/json" ], "parameters": [ { "name": "proxy", "in": "path", "required": true, "type": "string" } ], "responses": {}, "x-amazon-apigateway-integration": { "responses": { "default": { "statusCode": "200" } }, "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-east-1:123456789012:function:SimpleLambda4ProxyResource/ invocations", "passthroughBehavior": "when_no_match", "httpMethod": "POST", "cacheNamespace": "roq9wj", "cacheKeyParameters": [ "method.request.path.proxy" ], "type": "aws_proxy" Integrations 428 Amazon API Gateway } } } } } Developer Guide In Lambda proxy integration, at run time, API Gateway maps an incoming request into the input event parameter of the Lambda function. The input includes the request method, path, headers, any query string parameters, any payload, associated context, and any defined stage variables. The input format is explained in Input format of a Lambda function for proxy integration. For API Gateway to map the Lambda output to HTTP responses successfully, the Lambda function must output the result in the format described in Output format of a Lambda function for proxy integration. In Lambda proxy integration of a proxy resource through the ANY method, the single backend Lambda function serves as the event handler for all requests through the proxy resource. For example, to log traffic patterns, you can have a mobile device send its location information of state, city, street, and building by submitting a request with /state/city/street/house in the URL path for the proxy resource. The backend Lambda function can then parse the URL path and insert the location tuples into a DynamoDB table. Set up Lambda custom integrations in API Gateway To show how to set up the Lambda custom, or non-proxy,integration, we create an API Gateway API to expose the GET /greeting?greeter={name} method to invoke a Lambda function. Use one of the following example Lambda functions for you API. Use one of the following example Lambda functions: Node.js 'use strict'; var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var times = ['morning', 'afternoon', 'evening', 'night', 'day']; export const handler = async(event) => { console.log(event); // Parse the input for the name, city, time and day property values Integrations 429 Amazon API Gateway Developer Guide let name = event.name === null || event.name === undefined || event.name === "" ? 'you' : event.name; let city = event.city === undefined ? 'World' : event.city; let time = times.indexOf(event.time)<0 ? 'day' : event.time; let day = days.indexOf(event.day)<0 ? null : event.day; // Generate a greeting let greeting = 'Good ' + time + ', ' + name + ' of ' + city + '. '; if (day) greeting += 'Happy ' + day + '!'; // Log the greeting to CloudWatch console.log('Hello: ', greeting); // Return a greeting to the caller return greeting; }; Python import json def lambda_handler(event, context): print(event) res = { "statusCode": 200, "headers": { "Content-Type": "*/*" } } if event['greeter'] == "": res['body'] = "Hello, World" elif (event['greeter']): res['body'] = "Hello, " + event['greeter'] + "!" else: raise Exception('Missing the required greeter parameter.') return res The function responds with a message of "Hello, {name}!" if the greeter parameter value is a non-empty string. It returns a message of "Hello, World!" if the greeter value is an Integrations 430 Amazon API Gateway Developer Guide empty string. The function returns an error message of "Missing the required greeter parameter." if the greeter parameter is not set in the incoming request. We name the function HelloWorld. You can create it in the Lambda console or by using the AWS CLI. In this section, we reference this function using the following ARN: arn:aws:lambda:us-east-1:123456789012:function:HelloWorld With the Lambda function set in the backend, proceed to set up the API. To set up the Lambda custom integration using the AWS CLI 1. Use the following create-rest-api command to create an API: aws apigateway create-rest-api --name 'HelloWorld (AWS CLI)' The output will look like the following: { "name": "HelloWorld (AWS CLI)", "id": "te6si5ach7", "rootResourceId" : "krznpq9xpg", "createdDate": 1508461860 } You use the API id ( te6si5ach7) and the rootResourceId (krznpq9xpg) throughout this example. 2. Use the following create-resource command to create an API Gateway Resource of / greeting: aws apigateway create-resource \ --rest-api-id te6si5ach7 \ --parent-id krznpq9xpg \ --path-part greeting The output will look like the following: { Integrations 431 Amazon API Gateway Developer Guide "path": "/greeting", "pathPart": "greeting", "id": "2jf6xt", "parentId": "krznpq9xpg" } You use the greeting resource's id value
apigateway-dg-123
apigateway-dg.pdf
123
API: aws apigateway create-rest-api --name 'HelloWorld (AWS CLI)' The output will look like the following: { "name": "HelloWorld (AWS CLI)", "id": "te6si5ach7", "rootResourceId" : "krznpq9xpg", "createdDate": 1508461860 } You use the API id ( te6si5ach7) and the rootResourceId (krznpq9xpg) throughout this example. 2. Use the following create-resource command to create an API Gateway Resource of / greeting: aws apigateway create-resource \ --rest-api-id te6si5ach7 \ --parent-id krznpq9xpg \ --path-part greeting The output will look like the following: { Integrations 431 Amazon API Gateway Developer Guide "path": "/greeting", "pathPart": "greeting", "id": "2jf6xt", "parentId": "krznpq9xpg" } You use the greeting resource's id value (2jf6xt) to create a method on the /greeting resource in the next step. 3. Use the following put-method command to create an API method request of GET / greeting?greeter={name}: aws apigateway put-method --rest-api-id te6si5ach7 \ --resource-id 2jf6xt \ --http-method GET \ --authorization-type "NONE" \ --request-parameters method.request.querystring.greeter=false The output will look like the following: { "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE", "requestParameters": { "method.request.querystring.greeter": false } } This API method allows the client to receive a greeting from the Lambda function at the backend. The greeter parameter is optional because the backend should handle either an anonymous caller or a self-identified caller. 4. Use the following put-method-response command to set up the 200 OK response to the method request of GET /greeting?greeter={name}: aws apigateway put-method-response \ --rest-api-id te6si5ach7 \ --resource-id 2jf6xt \ --http-method GET \ --status-code 200 Integrations 432 Amazon API Gateway Developer Guide 5. Use the following put-integration command to set up the integration of the GET /greeting? greeter={name} method with a Lambda function, named HelloWorld. The function responds to the request with a message of "Hello, {name}!", if the greeter parameter is provided, or "Hello, World!", if the query string parameter is not set. aws apigateway put-integration \ --rest-api-id te6si5ach7 \ --resource-id 2jf6xt \ --http-method GET \ --type AWS \ --integration-http-method POST \ --uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-east-1:123456789012:function:HelloWorld/invocations \ --request-templates '{"application/json":"{\"greeter\": \"$input.params('greeter')\"}"}' \ --credentials arn:aws:iam::123456789012:role/apigAwsProxyRole The mapping template supplied here translates the greeter query string parameter to the greeter property of the JSON payload. This is necessary because the input to a Lambda function must be expressed in the body. Important For Lambda integrations, you must use the HTTP method of POST for the integration request, according to the specification of the Lambda service action for function invocations. The uri parameter is the ARN of the function-invoking action. The output will look like the following: { "passthroughBehavior": "WHEN_NO_MATCH", "cacheKeyParameters": [], "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-east-1:123456789012:function:HelloWorld/invocations", "httpMethod": "POST", "requestTemplates": { "application/json": "{\"greeter\":\"$input.params('greeter')\"}" }, "cacheNamespace": "krznpq9xpg", Integrations 433 Amazon API Gateway Developer Guide "credentials": "arn:aws:iam::123456789012:role/apigAwsProxyRole", "type": "AWS" } The IAM role of apigAwsProxyRole must have policies that allow the apigateway service to invoke Lambda functions. Instead of supplying an IAM role for credentials, you can call the add-permission command to add resource-based permissions. This is how the API Gateway console adds these permissions. 6. Use the following put-integration-response command to set up the integration response to pass the Lambda function output to the client as the 200 OK method response: aws apigateway put-integration-response \ --rest-api-id te6si5ach7 \ --resource-id 2jf6xt \ --http-method GET \ --status-code 200 \ --selection-pattern "" By setting the selection-pattern to an empty string, the 200 OK response is the default. The output will look like the following: { "selectionPattern": "", "statusCode": "200" } 7. Use the following create-deployment command to deploy the API to a test stage: aws apigateway create-deployment \ --rest-api-id te6si5ach7 \ --stage-name test 8. Test the API using the following cURL command in a terminal: curl -X GET 'https://te6si5ach7.execute-api.us-west-2.amazonaws.com/test/greeting? greeter=me' \ Integrations 434 Amazon API Gateway Developer Guide -H 'authorization: AWS4-HMAC-SHA256 Credential={access_key}/20171020/us- west-2/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=f327...5751' Set up asynchronous invocation of the backend Lambda function In Lambda non-proxy (custom) integration, the backend Lambda function is invoked synchronously by default. This is the desired behavior for most REST API operations. Some applications, however, require work to be performed asynchronously (as a batch operation or a long-latency operation), typically by a separate backend component. In this case, the backend Lambda function is invoked asynchronously, and the front-end REST API method doesn't return the result. You can configure the Lambda function for a Lambda non-proxy integration to be invoked asynchronously by specifying 'Event' as the Lambda invocation type. This is done as follows: Configure Lambda asynchronous invocation in the API Gateway console For all invocations to be asynchronous: • In Integration request, add an X-Amz-Invocation-Type header with a static value of 'Event'. For clients to decide if invocations are asynchronous or synchronous: 1. 2. In Method request, add an InvocationType header. In Integration request add an X-Amz-Invocation-Type header with a mapping expression of method.request.header.InvocationType. 3. Clients can include the InvocationType: Event header in API requests for asynchronous invocations or InvocationType: RequestResponse for synchronous invocations. Configure Lambda asynchronous invocation using OpenAPI For all invocations
apigateway-dg-124
apigateway-dg.pdf
124
as the Lambda invocation type. This is done as follows: Configure Lambda asynchronous invocation in the API Gateway console For all invocations to be asynchronous: • In Integration request, add an X-Amz-Invocation-Type header with a static value of 'Event'. For clients to decide if invocations are asynchronous or synchronous: 1. 2. In Method request, add an InvocationType header. In Integration request add an X-Amz-Invocation-Type header with a mapping expression of method.request.header.InvocationType. 3. Clients can include the InvocationType: Event header in API requests for asynchronous invocations or InvocationType: RequestResponse for synchronous invocations. Configure Lambda asynchronous invocation using OpenAPI For all invocations to be asynchronous: • Add the X-Amz-Invocation-Type header to the x-amazon-apigateway-integration section. "x-amazon-apigateway-integration" : { "type" : "aws", Integrations 435 Amazon API Gateway Developer Guide "httpMethod" : "POST", "uri" : "arn:aws:apigateway:us-east-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-east-2:123456789012:function:my-function/invocations", "responses" : { "default" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.X-Amz-Invocation-Type" : "'Event'" }, "passthroughBehavior" : "when_no_match", "contentHandling" : "CONVERT_TO_TEXT" } For clients to decide if invocations are asynchronous or synchronous: 1. Add the following header on any OpenAPI Path Item Object. "parameters" : [ { "name" : "InvocationType", "in" : "header", "schema" : { "type" : "string" } } ] 2. Add the X-Amz-Invocation-Type header to x-amazon-apigateway-integration section. "x-amazon-apigateway-integration" : { "type" : "aws", "httpMethod" : "POST", "uri" : "arn:aws:apigateway:us-east-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-east-2:123456789012:function:my-function/invocations", "responses" : { "default" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.X-Amz-Invocation-Type" : "method.request.header.InvocationType" Integrations 436 Amazon API Gateway }, "passthroughBehavior" : "when_no_match", "contentHandling" : "CONVERT_TO_TEXT" } Developer Guide 3. Clients can include the InvocationType: Event header in API requests for asynchronous invocations or InvocationType: RequestResponse for synchronous invocations. Configure Lambda asynchronous invocation using AWS CloudFormation The following AWS CloudFormation templates show how to configure the AWS::ApiGateway::Method for asynchronous invocations. For all invocations to be asynchronous: AsyncMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref AsyncResource HttpMethod: GET ApiKeyRequired: false AuthorizationType: NONE Integration: Type: AWS RequestParameters: integration.request.header.X-Amz-Invocation-Type: "'Event'" IntegrationResponses: - StatusCode: '200' IntegrationHttpMethod: POST Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/ ${myfunction.Arn}$/invocations MethodResponses: - StatusCode: '200' For clients to decide if invocations are asynchronous or synchronous: AsyncMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api Integrations 437 Amazon API Gateway Developer Guide ResourceId: !Ref AsyncResource HttpMethod: GET ApiKeyRequired: false AuthorizationType: NONE RequestParameters: method.request.header.InvocationType: false Integration: Type: AWS RequestParameters: integration.request.header.X-Amz-Invocation-Type: method.request.header.InvocationType IntegrationResponses: - StatusCode: '200' IntegrationHttpMethod: POST Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/ ${myfunction.Arn}$/invocations MethodResponses: - StatusCode: '200' Clients can include the InvocationType: Event header in API requests for asynchronous invocations or InvocationType: RequestResponse for synchronous invocations. Handle Lambda errors in API Gateway For Lambda custom integrations, you must map errors returned by Lambda in the integration response to standard HTTP error responses for your clients. Otherwise, Lambda errors are returned as 200 OK responses by default and the result is not intuitive for your API users. There are two types of errors that Lambda can return: standard errors and custom errors. In your API, you must handle these differently. With the Lambda proxy integration, Lambda is required to return an output of the following format: { "isBase64Encoded" : "boolean", "statusCode": "number", "headers": { ... }, "body": "JSON string" } Integrations 438 Amazon API Gateway Developer Guide In this output, statusCode is typically 4XX for a client error and 5XX for a server error. API Gateway handles these errors by mapping the Lambda error to an HTTP error response, according to the specified statusCode. For API Gateway to pass the error type (for example, InvalidParameterException), as part of the response to the client, the Lambda function must include a header (for example, "X-Amzn-ErrorType":"InvalidParameterException") in the headers property. Topics • Handle standard Lambda errors in API Gateway • Handle custom Lambda errors in API Gateway Handle standard Lambda errors in API Gateway A standard AWS Lambda error has the following format: { "errorMessage": "<replaceable>string</replaceable>", "errorType": "<replaceable>string</replaceable>", "stackTrace": [ "<replaceable>string</replaceable>", ... ] } Here, errorMessage is a string expression of the error. The errorType is a language-dependent error or exception type. The stackTrace is a list of string expressions showing the stack trace leading to the occurrence of the error. For example, consider the following JavaScript (Node.js) Lambda function. export const handler = function(event, context, callback) { callback(new Error("Malformed input ...")); }; This function returns the following standard Lambda error, containing Malformed input ... as the error message: { "errorMessage": "Malformed input ...", "errorType": "Error", Integrations 439 Amazon API Gateway "stackTrace": [ "export const handler (/var/task/index.js:3:14)" ] } Developer Guide Similarly, consider the following Python Lambda function, which raises an Exception with the same Malformed input ... error message. def lambda_handler(event, context): raise Exception('Malformed input ...') This function returns the following standard Lambda error: { "stackTrace": [ [ "/var/task/lambda_function.py", 3, "lambda_handler", "raise Exception('Malformed input ...')" ] ], "errorType": "Exception", "errorMessage": "Malformed input ..." } Note that the errorType and stackTrace property values are language-dependent. The standard error also applies to any
apigateway-dg-125
apigateway-dg.pdf
125
Malformed input ... as the error message: { "errorMessage": "Malformed input ...", "errorType": "Error", Integrations 439 Amazon API Gateway "stackTrace": [ "export const handler (/var/task/index.js:3:14)" ] } Developer Guide Similarly, consider the following Python Lambda function, which raises an Exception with the same Malformed input ... error message. def lambda_handler(event, context): raise Exception('Malformed input ...') This function returns the following standard Lambda error: { "stackTrace": [ [ "/var/task/lambda_function.py", 3, "lambda_handler", "raise Exception('Malformed input ...')" ] ], "errorType": "Exception", "errorMessage": "Malformed input ..." } Note that the errorType and stackTrace property values are language-dependent. The standard error also applies to any error object that is an extension of the Error object or a subclass of the Exception class. To map the standard Lambda error to a method response, you must first decide on an HTTP status code for a given Lambda error. You then set a regular expression pattern on the selectionPattern property of the IntegrationResponse associated with the given HTTP status code. In the API Gateway console, this selectionPattern is denoted as Lambda error regex in the Integration response section, under each integration response. Note API Gateway uses Java pattern-style regexes for response mapping. For more information, see Pattern in the Oracle documentation. Integrations 440 Amazon API Gateway Developer Guide For example, use the following put-integration-response to set up a new selectionPattern expression: aws apigateway put-integration-response --rest-api-id z0vprf0mdh --resource-id x3o5ih --http-method GET --status-code 400 --selection-pattern "Malformed.*" --region us- west-2 Make sure that you also set up the corresponding error code (400) on the method response. Otherwise, API Gateway throws an invalid configuration error response at runtime. Note At runtime, API Gateway matches the Lambda error's errorMessage against the pattern of the regular expression on the selectionPattern property. If there is a match, API Gateway returns the Lambda error as an HTTP response of the corresponding HTTP status code. If there is no match, API Gateway returns the error as a default response or throws an invalid configuration exception if no default response is configured. Setting the selectionPattern value to .* for a given response amounts to resetting this response as the default response. This is because such a selection pattern will match all error messages, including null, i.e., any unspecified error message. The resulting mapping overrides the default mapping. If you use .+ as the selection pattern to filter responses, it might not match a response containing be aware that it may not match a response containing a newline ('\n) character. To update an existing selectionPattern value using the AWS CLI, call the update-integration- response operation to replace the /selectionPattern path value with the specified regex expression of the Malformed* pattern. To set the selectionPattern expression using the API Gateway console, enter the expression in the Lambda error regex text box when setting up or updating an integration response of a specified HTTP status code. Handle custom Lambda errors in API Gateway Instead of the standard error described in the preceding section, AWS Lambda allows you to return a custom error object as JSON string. The error can be any valid JSON object. For example, the following JavaScript (Node.js) Lambda function returns a custom error: Integrations 441 Amazon API Gateway Developer Guide export const handler = (event, context, callback) => { ... // Error caught here: var myErrorObj = { errorType : "InternalServerError", httpStatus : 500, requestId : context.awsRequestId, trace : { "function": "abc()", "line": 123, "file": "abc.js" } } callback(JSON.stringify(myErrorObj)); }; You must turn the myErrorObj object into a JSON string before calling callback to exit the function. Otherwise, the myErrorObj is returned as a string of "[object Object]". When a method of your API is integrated with the preceding Lambda function, API Gateway receives an integration response with the following payload: { "errorMessage": "{\"errorType\":\"InternalServerError\",\"httpStatus\":500, \"requestId\":\"e5849002-39a0-11e7-a419-5bb5807c9fb2\",\"trace\":{\"function\": \"abc()\",\"line\":123,\"file\":\"abc.js\"}}" } As with any integration response, you can pass through this error response as-is to the method response. Or you can have a mapping template to transform the payload into a different format. For example, consider the following body-mapping template for a method response of 500 status code: { errorMessage: $input.path('$.errorMessage'); } This template translates the integration response body that contains the custom error JSON string to the following method response body. This method response body contains the custom error JSON object: Integrations 442 Amazon API Gateway Developer Guide { "errorMessage" : { errorType : "InternalServerError", httpStatus : 500, requestId : context.awsRequestId, trace : { "function": "abc()", "line": 123, "file": "abc.js" } } }; Depending on your API requirements, you may need to pass some or all of the custom error properties as method response header parameters. You can achieve this by applying the custom error mappings from the integration response body to the method response headers. For example, the following OpenAPI extension defines a mapping from the errorMessage.errorType, errorMessage.httpStatus, errorMessage.trace.function, and
apigateway-dg-126
apigateway-dg.pdf
126
This method response body contains the custom error JSON object: Integrations 442 Amazon API Gateway Developer Guide { "errorMessage" : { errorType : "InternalServerError", httpStatus : 500, requestId : context.awsRequestId, trace : { "function": "abc()", "line": 123, "file": "abc.js" } } }; Depending on your API requirements, you may need to pass some or all of the custom error properties as method response header parameters. You can achieve this by applying the custom error mappings from the integration response body to the method response headers. For example, the following OpenAPI extension defines a mapping from the errorMessage.errorType, errorMessage.httpStatus, errorMessage.trace.function, and errorMessage.trace properties to the error_type, error_status, error_trace_function, and error_trace headers, respectively. "x-amazon-apigateway-integration": { "responses": { "default": { "statusCode": "200", "responseParameters": { "method.response.header.error_trace_function": "integration.response.body.errorMessage.trace.function", "method.response.header.error_status": "integration.response.body.errorMessage.httpStatus", "method.response.header.error_type": "integration.response.body.errorMessage.errorType", "method.response.header.error_trace": "integration.response.body.errorMessage.trace" }, ... } } } Integrations 443 Amazon API Gateway Developer Guide At runtime, API Gateway deserializes the integration.response.body parameter when performing header mappings. However, this deserialization applies only to body-to-header mappings for Lambda custom error responses and does not apply to body-to-body mappings using $input.body. With these custom-error-body-to-header mappings, the client receives the following headers as part of the method response, provided that the error_status, error_trace, error_trace_function, and error_type headers are declared in the method request. "error_status":"500", "error_trace":"{\"function\":\"abc()\",\"line\":123,\"file\":\"abc.js\"}", "error_trace_function":"abc()", "error_type":"InternalServerError" The errorMessage.trace property of the integration response body is a complex property. It is mapped to the error_trace header as a JSON string. HTTP integrations for REST APIs in API Gateway You can integrate an API method with an HTTP endpoint using the HTTP proxy integration or the HTTP custom integration. API Gateway supports the following endpoint ports: 80, 443 and 1024-65535. With proxy integration, setup is simple. You only need to set the HTTP method and the HTTP endpoint URI, according to the backend requirements, if you are not concerned with content encoding or caching. With custom integration, setup is more involved. In addition to the proxy integration setup steps, you need to specify how the incoming request data is mapped to the integration request and how the resulting integration response data is mapped to the method response. Topics • Set up HTTP proxy integrations in API Gateway • Set up HTTP custom integrations in API Gateway Set up HTTP proxy integrations in API Gateway To set up a proxy resource with the HTTP proxy integration type, create an API resource with a greedy path parameter (for example, /parent/{proxy+}) and integrate this resource with Integrations 444 Amazon API Gateway Developer Guide an HTTP backend endpoint (for example, https://petstore-demo-endpoint.execute- api.com/petstore/{proxy}) on the ANY method. The greedy path parameter must be at the end of the resource path. As with a non-proxy resource, you can set up a proxy resource with the HTTP proxy integration by using the API Gateway console, importing an OpenAPI definition file, or calling the API Gateway REST API directly. For detailed instructions about using the API Gateway console to configure a proxy resource with the HTTP integration, see Tutorial: Create a REST API with an HTTP proxy integration. The following OpenAPI definition file shows an example of an API with a proxy resource that is integrated with the PetStore website. OpenAPI 3.0 { "openapi": "3.0.0", "info": { "version": "2016-09-12T23:19:28Z", "title": "PetStoreWithProxyResource" }, "paths": { "/{proxy+}": { "x-amazon-apigateway-any-method": { "parameters": [ { "name": "proxy", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": {}, "x-amazon-apigateway-integration": { "responses": { "default": { "statusCode": "200" } }, "requestParameters": { Integrations 445 Amazon API Gateway Developer Guide "integration.request.path.proxy": "method.request.path.proxy" }, "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/ {proxy}", "passthroughBehavior": "when_no_match", "httpMethod": "ANY", "cacheNamespace": "rbftud", "cacheKeyParameters": [ "method.request.path.proxy" ], "type": "http_proxy" } } } }, "servers": [ { "url": "https://4z9giyi2c1.execute-api.us-east-1.amazonaws.com/{basePath}", "variables": { "basePath": { "default": "/test" } } } ] } OpenAPI 2.0 { "swagger": "2.0", "info": { "version": "2016-09-12T23:19:28Z", "title": "PetStoreWithProxyResource" }, "host": "4z9giyi2c1.execute-api.us-east-1.amazonaws.com", "basePath": "/test", "schemes": [ "https" ], "paths": { "/{proxy+}": { "x-amazon-apigateway-any-method": { Integrations 446 Amazon API Gateway Developer Guide "produces": [ "application/json" ], "parameters": [ { "name": "proxy", "in": "path", "required": true, "type": "string" } ], "responses": {}, "x-amazon-apigateway-integration": { "responses": { "default": { "statusCode": "200" } }, "requestParameters": { "integration.request.path.proxy": "method.request.path.proxy" }, "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/{proxy}", "passthroughBehavior": "when_no_match", "httpMethod": "ANY", "cacheNamespace": "rbftud", "cacheKeyParameters": [ "method.request.path.proxy" ], "type": "http_proxy" } } } } } In this example, a cache key is declared on the method.request.path.proxy path parameter of the proxy resource. This is the default setting when you create the API using the API Gateway console. The API's base path (/test, corresponding to a stage) is mapped to the website's PetStore page (/petstore). The single integration request mirrors the entire PetStore website using the API's greedy path variable and the catch-all ANY method. The following examples illustrate this mirroring. Integrations 447 Amazon API Gateway Developer Guide • Set ANY as GET and {proxy+} as pets Method request initiated from the frontend:
apigateway-dg-127
apigateway-dg.pdf
127
} } } In this example, a cache key is declared on the method.request.path.proxy path parameter of the proxy resource. This is the default setting when you create the API using the API Gateway console. The API's base path (/test, corresponding to a stage) is mapped to the website's PetStore page (/petstore). The single integration request mirrors the entire PetStore website using the API's greedy path variable and the catch-all ANY method. The following examples illustrate this mirroring. Integrations 447 Amazon API Gateway Developer Guide • Set ANY as GET and {proxy+} as pets Method request initiated from the frontend: GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets HTTP/1.1 Integration request sent to the backend: GET http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP/1.1 The run-time instances of the ANY method and proxy resource are both valid. The call returns a 200 OK response with the payload containing the first batch of pets, as returned from the backend. • Set ANY as GET and {proxy+} as pets?type=dog GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets?type=dog HTTP/1.1 Integration request sent to the backend: GET http://petstore-demo-endpoint.execute-api.com/petstore/pets?type=dog HTTP/1.1 The run-time instances of the ANY method and proxy resource are both valid. The call returns a 200 OK response with the payload containing the first batch of specified dogs, as returned from the backend. • Set ANY as GET and {proxy+} as pets/{petId} Method request initiated from the frontend: GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets/1 HTTP/1.1 Integration request sent to the backend: GET http://petstore-demo-endpoint.execute-api.com/petstore/pets/1 HTTP/1.1 The run-time instances of the ANY method and proxy resource are both valid. The call returns a 200 OK response with the payload containing the specified pet, as returned from the backend. Integrations 448 Amazon API Gateway Developer Guide • Set ANY as POST and {proxy+} as pets Method request initiated from the frontend: POST https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets HTTP/1.1 Content-Type: application/json Content-Length: ... { "type" : "dog", "price" : 1001.00 } Integration request sent to the backend: POST http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP/1.1 Content-Type: application/json Content-Length: ... { "type" : "dog", "price" : 1001.00 } The run-time instances of the ANY method and proxy resource are both valid. The call returns a 200 OK response with the payload containing the newly created pet, as returned from the backend. • Set ANY as GET and {proxy+} as pets/cat Method request initiated from the frontend: GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test/pets/cat Integration request sent to the backend: GET http://petstore-demo-endpoint.execute-api.com/petstore/pets/cat Integrations 449 Amazon API Gateway Developer Guide The run-time instance of the proxy resource path does not correspond to a backend endpoint and the resulting request is invalid. As a result, a 400 Bad Request response is returned with the following error message. { "errors": [ { "key": "Pet2.type", "message": "Missing required field" }, { "key": "Pet2.price", "message": "Missing required field" } ] } • Set ANY as GET and {proxy+} as null Method request initiated from the frontend: GET https://4z9giyi2c1.execute-api.us-west-2.amazonaws.com/test Integration request sent to the backend: GET http://petstore-demo-endpoint.execute-api.com/petstore/pets The targeted resource is the parent of the proxy resource, but the run-time instance of the ANY method is not defined in the API on that resource. As a result, this GET request returns a 403 Forbidden response with the Missing Authentication Token error message as returned by API Gateway. If the API exposes the ANY or GET method on the parent resource (/), the call returns a 404 Not Found response with the Cannot GET /petstore message as returned from the backend. For any client request, if the targeted endpoint URL is invalid or the HTTP verb is valid but not supported, the backend returns a 404 Not Found response. For an unsupported HTTP method, a 403 Forbidden response is returned. Integrations 450 Amazon API Gateway Developer Guide Set up HTTP custom integrations in API Gateway With the HTTP custom integration, also known as the non-proxy integration, you have more control of which data to pass between an API method and an API integration and how to pass the data. You do this using data mappings. As part of the method request setup, you set the requestParameters property on a Method resource. This declares which method request parameters, which are provisioned from the client, are to be mapped to integration request parameters or applicable body properties before being dispatched to the backend. Then, as part of the integration request setup, you set the requestParameters property on the corresponding Integration resource to specify the parameter- to-parameter mappings. You also set the requestTemplates property to specify mapping templates, one for each supported content type. The mapping templates map method request parameters, or body, to the integration request body. Similarly, as part of the method response setup, you set the responseParameters property on the MethodResponse resource. This declares which method response parameters, to be dispatched to the client, are to be mapped from integration response parameters or certain applicable body properties that were returned from the backend. You then set up the selectionPattern to choose an
apigateway-dg-128
apigateway-dg.pdf
128
requestParameters property on the corresponding Integration resource to specify the parameter- to-parameter mappings. You also set the requestTemplates property to specify mapping templates, one for each supported content type. The mapping templates map method request parameters, or body, to the integration request body. Similarly, as part of the method response setup, you set the responseParameters property on the MethodResponse resource. This declares which method response parameters, to be dispatched to the client, are to be mapped from integration response parameters or certain applicable body properties that were returned from the backend. You then set up the selectionPattern to choose an integration response based on the response from the backend. For a non-proxy HTTP integration, this is a regular expression. For example, to map all 2xx HTTP response status codes from an HTTP endpoint to this output mapping, use 2\d{2}. Note API Gateway uses Java pattern-style regexes for response mapping. For more information, see Pattern in the Oracle documentation. Then, as part of the integration response setup, you set the responseParameters property on the corresponding IntegrationResponse resource to specify the parameter-to-parameter mappings. You also set the responseTemplates map to specify mapping templates, one for each supported content type. The mapping templates map integration response parameters, or integration response body properties, to the method response body. For more information about setting up mapping templates, see Data transformations for REST APIs in API Gateway. Integrations 451 Amazon API Gateway Developer Guide Private integrations for REST APIs in API Gateway The API Gateway private integration makes it simple to expose your HTTP/HTTPS resources within an Amazon VPC for access by clients outside of the VPC. To extend access to your private VPC resources beyond the VPC boundaries, you can create an API with private integration. You can control access to your API by using any of the authorization methods that API Gateway supports. To create a private integration, you must first create a Network Load Balancer. Your Network Load Balancer must have a listener that routes requests to resources in your VPC. To improve the availability of your API, ensure that your Network Load Balancer routes traffic to resources in more than one Availability Zone in the AWS Region. Then, you create a VPC link that you use to connect your API and your Network Load Balancer. After you create a VPC link, you create private integrations to route traffic from your API to resources in your VPC through your VPC link and Network Load Balancer. Note The Network Load Balancer and API must be owned by the same AWS account. With the API Gateway private integration, you can enable access to HTTP/HTTPS resources within a VPC without detailed knowledge of private network configurations or technology-specific appliances. Topics • Set up a Network Load Balancer for API Gateway private integrations • Grant permissions for API Gateway to create a VPC link • Set up an API Gateway API with private integrations using the AWS CLI • Set up API with private integrations using OpenAPI • API Gateway accounts used for private integrations Set up a Network Load Balancer for API Gateway private integrations The following procedure outlines the steps to set up a Network Load Balancer (NLB) for API Gateway private integrations using the Amazon EC2 console and provides references for detailed instructions for each step. Integrations 452 Amazon API Gateway Developer Guide For each VPC you have resources in, you only need to configure one NLB and one VPCLink. The NLB supports multiple listeners and target groups per NLB. You can configure each service as a specific listener on the NLB and use a single VPCLink to connect to the NLB. When creating the private integration in API Gateway you then define each service using the specific port that is assigned for each service. For more information, see the section called “Tutorial: Create a REST API with a private integration”. Note The Network Load Balancer and API must be owned by the same AWS account. To create a Network Load Balancer for private integration using the API Gateway console 1. Sign in to the AWS Management Console and open the Amazon EC2 console at https:// console.aws.amazon.com/ec2/. 2. Set up a web server on an Amazon EC2 instance. For an example setup, see Installing a LAMP Web Server on Amazon Linux 2. 3. Create a Network Load Balancer, register the EC2 instance with a target group, and add the target group to a listener of the Network Load Balancer. For details, follow the instructions in Getting Started with Network Load Balancers. 4. After the Network Load Balancer is created, do the following: a. Note the ARN of the Network Load Balancer. You will need it to create a VPC link in API Gateway for integrating the API with the VPC resources behind the Network
apigateway-dg-129
apigateway-dg.pdf
129
an Amazon EC2 instance. For an example setup, see Installing a LAMP Web Server on Amazon Linux 2. 3. Create a Network Load Balancer, register the EC2 instance with a target group, and add the target group to a listener of the Network Load Balancer. For details, follow the instructions in Getting Started with Network Load Balancers. 4. After the Network Load Balancer is created, do the following: a. Note the ARN of the Network Load Balancer. You will need it to create a VPC link in API Gateway for integrating the API with the VPC resources behind the Network Load Balancer. b. Turn off security group evaluation for PrivateLink. • • To turn off security group evaluation for PrivateLink traffic using the console, you can choose the Security tab, and then Edit. In the Security settings, clear Enforce inbound rules on PrivateLink traffic. Use the following set-security-groups command to turn off security group evaluation for PrivateLink traffic: aws elbv2 set-security-groups --load-balancer- arn arn:aws:elasticloadbalancing:us-east-2:111122223333:loadbalancer/net/ my-loadbalancer/abc12345 \ Integrations 453 Amazon API Gateway Developer Guide --security-groups sg-123345a --enforce-security-group-inbound-rules-on- private-link-traffic off Note Do not add any dependencies to API Gateway CIDRs as they are bound to change without notice. Grant permissions for API Gateway to create a VPC link For you or a user in your account to create and maintain a VPC link, you or the user must have permissions to create, delete, and view VPC endpoint service configurations, change VPC endpoint service permissions, and examine load balancers. To grant such permissions, use the following steps. To grant permissions to create, update, and delete a VPC link 1. Create an IAM policy similar to the following: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "apigateway:POST", "apigateway:GET", "apigateway:PATCH", "apigateway:DELETE" ], "Resource": [ "arn:aws:apigateway:us-east-1::/vpclinks", "arn:aws:apigateway:us-east-1::/vpclinks/*" ] }, { "Effect": "Allow", "Action": [ "elasticloadbalancing:DescribeLoadBalancers" ], Integrations 454 Amazon API Gateway Developer Guide "Resource": "*" }, { "Effect": "Allow", "Action": [ "ec2:CreateVpcEndpointServiceConfiguration", "ec2:DeleteVpcEndpointServiceConfigurations", "ec2:DescribeVpcEndpointServiceConfigurations", "ec2:ModifyVpcEndpointServicePermissions" ], "Resource": "*" } ] } If you want to enable tagging for your VPC link, make sure to allow tagging operations. For more information, see the section called “Allow tagging operations”. 2. Create or choose an IAM role and attach the preceding policy to the role. 3. Assign the IAM role to you or a user in your account who is creating VPC links. Set up an API Gateway API with private integrations using the AWS CLI The following tutorial shows how to use the AWS CLI to create a VPC link and a private integration. The following prerequisites are required: • You need an Network Load Balancer created and configured with your VPC source as the target. For more information, see Set up a Network Load Balancer for API Gateway private integrations. This must be in the same AWS account as your API. You need the Network Load Balancer ARN to create your VPC link. • To create and manage a VpcLink, you need the permissions to create a VpcLink in your API. You don't need the permissions to use the VpcLink. For more information, see Grant permissions for API Gateway to create a VPC link. To set up an API with the private integration using AWS CLI 1. Use the following create-vpc-link command to create a VpcLink targeting the specified Network Load Balancer: aws apigateway create-vpc-link \ Integrations 455 Amazon API Gateway Developer Guide --name my-test-vpc-link \ --target-arns arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/ net/my-vpclink-test-nlb/1234567890abcdef The output of this command acknowledges the receipt of the request and shows the PENDING status for the VpcLink being created. { "status": "PENDING", "targetArns": [ "arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/net/my- vpclink-test-nlb/1234567890abcdef" ], "id": "gim7c3", "name": "my-test-vpc-link" } It takes 2-4 minutes for API Gateway to finish creating the VpcLink. When the operation finishes successfully, the status is AVAILABLE. You can verify this by using the following get- vpc-link command: aws apigateway get-vpc-link --vpc-link-id gim7c3 If the operation fails, you get a FAILED status, with the statusMessage containing the error message. For example, if you attempt to create a VpcLink with a Network Load Balancer that is already associated with a VPC endpoint, you get the following on the statusMessage property: "NLB is already associated with another VPC Endpoint Service" After the VpcLink is created successfully, you can create an API and integrate it with the VPC resource through the VpcLink. Note the id value of the newly created VpcLink. In this example output, it's gim7c3. You need it to set up the private integration. 2. Use the following create-rest-api command to create an API Gateway RestApi resource: aws apigateway create-rest-api --name 'My VPC Link Test' Integrations 456 Amazon API Gateway Developer Guide Note the RestApi's id value and the RestApi's rootResourceId value in the returned result. You need this value to perform further operations on the API. Next, you create an API with only a GET method on the
apigateway-dg-130
apigateway-dg.pdf
130
API and integrate it with the VPC resource through the VpcLink. Note the id value of the newly created VpcLink. In this example output, it's gim7c3. You need it to set up the private integration. 2. Use the following create-rest-api command to create an API Gateway RestApi resource: aws apigateway create-rest-api --name 'My VPC Link Test' Integrations 456 Amazon API Gateway Developer Guide Note the RestApi's id value and the RestApi's rootResourceId value in the returned result. You need this value to perform further operations on the API. Next, you create an API with only a GET method on the root resource (/) and integrate the method with the VpcLink. 3. Use the following put-method command to create the GET / method: aws apigateway put-method \ --rest-api-id abcdef123 \ --resource-id skpp60rab7 \ --http-method GET \ --authorization-type "NONE" If you don't use the proxy integration with the VpcLink, you must also set up at least a method response of the 200 status code. You use the proxy integration here. 4. After you create the GET / method, you set up the integration. For a private integration, you use the connection-id parameter to provide the VpcLink ID. You can use either a stage variable or directly enter the VpcLink ID. The uri parameter is not used for routing requests to your endpoint, but is used for setting the Host header and for certificate validation. Use the VPC link ID Use the following put-integration command to use the VpcLink ID directly in the integration: aws apigateway put-integration \ --rest-api-id abcdef123 \ --resource-id skpp60rab7 \ --uri 'http://my-vpclink-test-nlb-1234567890abcdef.us-east-2.amazonaws.com' \ --http-method GET \ --type HTTP_PROXY \ --integration-http-method GET \ --connection-type VPC_LINK \ --connection-id gim7c3 Integrations 457 Amazon API Gateway Use a stage variable Developer Guide Use the following put-integration command to use a stage variable to reference the VPC link ID. When you deploy your API to a stage, you set the VPC link ID. aws apigateway put-integration \ --rest-api-id abcdef123 \ --resource-id skpp60rab7 \ --uri 'http://my-vpclink-test-nlb-1234567890abcdef.us-east-2.amazonaws.com' \ --http-method GET \ --type HTTP_PROXY \ --integration-http-method GET \ --connection-type VPC_LINK \ --connection-id "\${stageVariables.vpcLinkId}" Make sure to double-quote the stage variable expression (${stageVariables.vpcLinkId}) and escape the $ character. At any point, you can also update the integration to change the connection-id. Use the following update-integration command to update your integration: aws apigateway update-integration \ --rest-api-id abcdef123 \ --resource-id skpp60rab7 \ --http-method GET \ --patch-operations '[{"op":"replace","path":"/ connectionId","value":"${stageVariables.vpcLinkId}"}]' Make sure to use a stringified JSON list as the patch-operations parameter value. Because you used the private proxy integration, your API is now ready for deployment and for test runs. 5. If you used the stage variable to define your connection-id, you need to deploy your API to test it. Use the following create-deployment command to deploy your API with a stage variable: aws apigateway create-deployment \ --rest-api-id abcdef123 \ Integrations 458 Amazon API Gateway Developer Guide --stage-name test \ --variables vpcLinkId=gim7c3 To update the stage variable with a different VpcLink ID, such as asf9d7, use the following update-stage command: aws apigateway update-stage \ --rest-api-id abcdef123 \ --stage-name test \ --patch-operations op=replace,path='/variables/vpcLinkId',value='asf9d7' When you hardcode the connection-id property with the VpcLink ID literal, you don't need to deploy your API to test it. Use the test-invoke-method command to test your API before it is deployed. 6. Use the following command to invoke your API: curl -X GET https://abcdef123.execute-api.us-east-2.amazonaws.com/test Alternatively, you can enter your API's invoke-URL in a web browser to view the result. Set up API with private integrations using OpenAPI You can set up an API with the private integration by importing the API's OpenAPI file. The settings are similar to the OpenAPI definitions of an API with HTTP integrations, with the following exceptions: • You must explicitly set connectionType to VPC_LINK. • You must explicitly set connectionId to the ID of a VpcLink or to a stage variable referencing the ID of a VpcLink. • The uri parameter in the private integration points to an HTTP/HTTPS endpoint in the VPC, but is used instead to set up the integration request's Host header. • The uri parameter in the private integration with an HTTPS endpoint in the VPC is used to verify the stated domain name against the one in the certificate installed on the VPC endpoint. You can use a stage variable to reference the VpcLink ID. Or you can assign the ID value directly to connectionId. Integrations 459 Amazon API Gateway Developer Guide The following JSON-formatted OpenAPI file shows an example of an API with a VPC link as referenced by a stage variable (${stageVariables.vpcLinkId}): OpenAPI 2.0 { "swagger": "2.0", "info": { "version": "2017-11-17T04:40:23Z", "title": "MyApiWithVpcLink" }, "host": "p3wocvip9a.execute-api.us-west-2.amazonaws.com", "basePath": "/test", "schemes": [ "https" ], "paths": { "/": { "get": { "produces": [ "application/json" ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } }
apigateway-dg-131
apigateway-dg.pdf
131
the certificate installed on the VPC endpoint. You can use a stage variable to reference the VpcLink ID. Or you can assign the ID value directly to connectionId. Integrations 459 Amazon API Gateway Developer Guide The following JSON-formatted OpenAPI file shows an example of an API with a VPC link as referenced by a stage variable (${stageVariables.vpcLinkId}): OpenAPI 2.0 { "swagger": "2.0", "info": { "version": "2017-11-17T04:40:23Z", "title": "MyApiWithVpcLink" }, "host": "p3wocvip9a.execute-api.us-west-2.amazonaws.com", "basePath": "/test", "schemes": [ "https" ], "paths": { "/": { "get": { "produces": [ "application/json" ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } }, "x-amazon-apigateway-integration": { "responses": { "default": { "statusCode": "200" } }, "uri": "http://my-vpclink-test-nlb-1234567890abcdef.us- east-2.amazonaws.com", "passthroughBehavior": "when_no_match", "connectionType": "VPC_LINK", "connectionId": "${stageVariables.vpcLinkId}", "httpMethod": "GET", "type": "http_proxy" Integrations 460 Developer Guide Amazon API Gateway } } } }, "definitions": { "Empty": { "type": "object", "title": "Empty Schema" } } } API Gateway accounts used for private integrations The following region-specific API Gateway account IDs are automatically added to your VPC endpoint service as AllowedPrincipals when you create a VpcLink. Region us-east-1 us-east-2 us-west-1 us-west-2 ca-central-1 eu-west-1 eu-west-2 eu-west-3 eu-central-1 eu-central-2 eu-north-1 Account ID 392220576650 718770453195 968246515281 109351309407 796887884028 631144002099 544388816663 061510835048 474240146802 166639821150 394634713161 Integrations 461 Amazon API Gateway Region eu-south-1 eu-south-2 ap-northeast-1 ap-northeast-2 ap-northeast-3 ap-southeast-1 ap-southeast-2 ap-southeast-3 ap-southeast-4 ap-south-1 ap-south-2 ap-east-1 sa-east-1 me-south-1 me-central-1 Developer Guide Account ID 753362059629 359345898052 969236854626 020402002396 360671645888 195145609632 798376113853 652364314486 849137399833 507069717855 644042651268 174803364771 287228555773 855739686837 614065512851 Mock integrations for REST APIs in API Gateway Amazon API Gateway supports mock integrations for API methods. This feature enables API developers to generate API responses from API Gateway directly, without the need for an integration backend. As an API developer, you can use this feature to unblock dependent teams that need to work with an API before the project development is complete. You can also use this feature to provision a landing page for your API, which can provide an overview of and navigation to your API. For an example of such a landing page, see the integration request and response of the Integrations 462 Amazon API Gateway Developer Guide GET method on the root resource of the example API discussed in Tutorial: Create a REST API by importing an example. As an API developer, you decide how API Gateway responds to a mock integration request. For this, you configure the method's integration request and integration response to associate a response with a given status code. For a method with the mock integration to return a 200 response, configure the integration request body mapping template to return the following. {"statusCode": 200} Configure a 200 integration response to have the following body mapping template, for example: { "statusCode": 200, "message": "Go ahead without me." } Similarly, for the method to return, for example, a 500 error response, set up the integration request body mapping template to return the following. {"statusCode": 500} Set up a 500 integration response with, for example, the following mapping template: { "statusCode": 500, "message": "The invoked method is not supported on the API resource." } Alternatively, you can have a method of the mock integration return the default integration response without defining the integration request mapping template. The default integration response is the one with an undefined HTTP status regex. Make sure appropriate passthrough behaviors are set. Note Mock integrations aren't intended to support large response templates. If you need them for your use case, you should consider using a Lambda integration instead. Integrations 463 Amazon API Gateway Developer Guide Using an integration request mapping template, you can inject application logic to decide which mock integration response to return based on certain conditions. For example, you could use a scope query parameter on the incoming request to determine whether to return a successful response or an error response: { #if( $input.params('scope') == "internal" ) "statusCode": 200 #else "statusCode": 500 #end } This way, the method of the mock integration lets internal calls to go through while rejecting other types of calls with an error response. In this section, we describe how to use the API Gateway console to enable the mock integration for an API method. Topics • Enable mock integration using the API Gateway console Enable mock integration using the API Gateway console You must have a method available in API Gateway. Follow the instructions in Tutorial: Create a REST API with an HTTP non-proxy integration. 1. Choose an API resource and choose Create method. To create the method, do the following: a. b. c. For Method type, select a method. For Integration type, select Mock. Choose Create method. d. On the Method request tab, for Method request settings, choose Edit. e. Choose URL query string parameters. Choose Add query string and for Name, enter scope. This query parameter determines if the caller is
apigateway-dg-132
apigateway-dg.pdf
132
console Enable mock integration using the API Gateway console You must have a method available in API Gateway. Follow the instructions in Tutorial: Create a REST API with an HTTP non-proxy integration. 1. Choose an API resource and choose Create method. To create the method, do the following: a. b. c. For Method type, select a method. For Integration type, select Mock. Choose Create method. d. On the Method request tab, for Method request settings, choose Edit. e. Choose URL query string parameters. Choose Add query string and for Name, enter scope. This query parameter determines if the caller is internal or otherwise. f. Choose Save. Integrations 464 Amazon API Gateway Developer Guide 2. On the Method response tab, choose Create response, and then do the following: a. For HTTP Status, enter 500. b. Choose Save. 3. On the Integration request tab, for Integration request settings, choose Edit. 4. Choose Mapping templates, and then do the following: a. b. c. Choose Add mapping template. For Content type, enter application/json. For Template body, enter the following: { #if( $input.params('scope') == "internal" ) "statusCode": 200 #else "statusCode": 500 #end } d. Choose Save. 5. On the Integration response tab, for the Default - Response choose Edit. 6. Choose Mapping templates, and then do the following: a. b. For Content type, enter application/json. For Template body, enter the following: { "statusCode": 200, "message": "Go ahead without me" } c. Choose Save. 7. Choose Create response. To create a 500 response, do the following: a. b. Integrations For HTTP status regex, enter 5\d{2}. For Method response status, select 500. 465 Amazon API Gateway Developer Guide c. d. e. f. g. Choose Save. For 5\d{2} - Response, choose Edit. Choose Mapping templates, and then choose Add mapping template. For Content type, enter application/json. For Template body, enter the following: { "statusCode": 500, "message": "The invoked method is not supported on the API resource." } h. Choose Save. 8. Choose the Test tab. You might need to choose the right arrow button to show the tab. To test your mock integration, do the following: a. Enter scope=internal under Query strings. Choose Test. The test result shows: Request: /?scope=internal Status: 200 Latency: 26 ms Response Body { "statusCode": 200, "message": "Go ahead without me" } Response Headers {"Content-Type":"application/json"} b. Enter scope=public under Query strings or leave it blank. Choose Test. The test result shows: Request: / Status: 500 Latency: 16 ms Integrations 466 Amazon API Gateway Response Body { "statusCode": 500, Developer Guide "message": "The invoked method is not supported on the API resource." } Response Headers {"Content-Type":"application/json"} You can also return headers in a mock integration response by first adding a header to the method response and then setting up a header mapping in the integration response. In fact, this is how the API Gateway console enables CORS support by returning CORS required headers. Request validation for REST APIs in API Gateway You can configure API Gateway to perform basic validation of an API request before proceeding with the integration request. When the validation fails, API Gateway immediately fails the request, returns a 400 error response to the caller, and publishes the validation results in CloudWatch Logs. This reduces unnecessary calls to the backend. More importantly, it lets you focus on the validation efforts specific to your application. You can validate a request body by verifying that required request parameters are valid and non-null or by specifying a model schema for more complicated data validation. Topics • Overview of basic request validation in API Gateway • Data models for REST APIs • Set up basic request validation in API Gateway • AWS CloudFormation template of a sample API with basic request validation Overview of basic request validation in API Gateway API Gateway can perform the basic request validation, so that you can focus on app-specific validation in the backend. For validation, API Gateway verifies either or both of the following conditions: Request validation 467 Amazon API Gateway Developer Guide • The required request parameters in the URI, query string, and headers of an incoming request are included and not blank. • The applicable request payload adheres to the configured JSON schema request of the method for a given content type. If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, set the content type for your data model to $default. To turn on validation, you specify validation rules in a request validator, add the validator to the API's map of request validators, and assign the validator to individual API methods. Note Request body validation and Method request behavior for payloads without mapping templates for REST APIs in API Gateway are two separate topics. When a request payload does not have a matching model schema,
apigateway-dg-133
apigateway-dg.pdf
133
a given content type. If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, set the content type for your data model to $default. To turn on validation, you specify validation rules in a request validator, add the validator to the API's map of request validators, and assign the validator to individual API methods. Note Request body validation and Method request behavior for payloads without mapping templates for REST APIs in API Gateway are two separate topics. When a request payload does not have a matching model schema, you can choose to passthrough or block the original payload. For more information, see Method request behavior for payloads without mapping templates for REST APIs in API Gateway. Data models for REST APIs In API Gateway, a model defines the data structure of a payload. In API Gateway, models are defined using the JSON schema draft 4. The following JSON object is sample data in the Pet Store example. { "id": 1, "type": "dog", "price": 249.99 } The data contains the id, type, and price of the pet. A model of this data allows you to: • Use basic request validation. • Create mapping templates for data transformation. • Create a user-defined data type (UDT) when you generate an SDK. Request validation 468 Amazon API Gateway Developer Guide In this model: 1. The $schema object represents a valid JSON Schema version identifier. This schema is the JSON Schema draft v4. 2. The title object is a human-readable identifier for the model. This title is PetStoreModel. 3. The required validation keyword requires type, and price for basic request validation. 4. The properties of the model are id, type, and price. Each object has properties that are described in the model. 5. The object type can have only the values dog, cat, or fish. 6. The object price is a number and is constrained with a minimum of 25 and a maximum of 500. Request validation 469 Amazon API Gateway PetStore model 1 { 2 "$schema": "http://json-schema.org/draft-04/schema#", Developer Guide 3 "title": "PetStoreModel", 4 "type" : "object", 5 "required" : [ "price", "type" ], 6 "properties" : { 7 "id" : { 8 "type" : "integer" 9 }, 10 "type" : { 11 "type" : "string", 12 "enum" : [ "dog", "cat", "fish" ] 13 }, 14 "price" : { 15 "type" : "number", 16 "minimum" : 25.0, 17 "maximum" : 500.0 18 } 19 } 20 } In this model: 1. On line 2, the $schema object represents a valid JSON Schema version identifier. This schema is the JSON Schema draft v4. 2. On line 3, the title object is a human-readable identifier for the model. This title is PetStoreModel. 3. On line 5, the required validation keyword requires type, and price for basic request validation. 4. On lines 6 -- 17, the properties of the model are id, type, and price. Each object has properties that are described in the model. 5. On line 12, the object type can have only the values dog, cat, or fish. 6. On lines 14 -- 17, the object price is a number and is constrained with a minimum of 25 and a maximum of 500. Request validation 470 Amazon API Gateway Creating more complex models Developer Guide You can use the $ref primitive to create reusable definitions for longer models. For example, you can create a definition called Price in the definitions section describing the price object. The value of $ref is the Price definition. { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "PetStoreModelReUsableRef", "required" : ["price", "type" ], "type" : "object", "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "price" : { "$ref": "#/definitions/Price" } }, "definitions" : { "Price": { "type" : "number", "minimum" : 25.0, "maximum" : 500.0 } } } You can also reference another model schema defined in an external model file. Set the value of the $ref property to the location of the model. In the following example, the Price model is defined in the PetStorePrice model in API a1234. { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "PetStorePrice", "type": "number", "minimum": 25, "maximum": 500 Request validation 471 Amazon API Gateway } Developer Guide The longer model can reference the PetStorePrice model. { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "PetStoreModelReusableRefAPI", "required" : [ "price", "type" ], "type" : "object", "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "price" : { "$ref": "https://apigateway.amazonaws.com/restapis/a1234/models/PetStorePrice" } } } Using output data models If you transform your data, you can define a payload model in the integration response. A payload model can be used when
apigateway-dg-134
apigateway-dg.pdf
134
"title" : "PetStorePrice", "type": "number", "minimum": 25, "maximum": 500 Request validation 471 Amazon API Gateway } Developer Guide The longer model can reference the PetStorePrice model. { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "PetStoreModelReusableRefAPI", "required" : [ "price", "type" ], "type" : "object", "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "price" : { "$ref": "https://apigateway.amazonaws.com/restapis/a1234/models/PetStorePrice" } } } Using output data models If you transform your data, you can define a payload model in the integration response. A payload model can be used when you generate an SDK. For strongly typed languages, such as Java, Objective-C, or Swift, the object corresponds to a user-defined data type (UDT). API Gateway creates a UDT if you provide it with a data model when you generate an SDK. For more information about data transformations, see Mapping template transformations for REST APIs in API Gateway. The following example is output data from an integration response. { [ { "description" : "Item 1 is a dog.", "askingPrice" : 249.99 }, { "description" : "Item 2 is a cat.", "askingPrice" : 124.99 Request validation 472 Developer Guide Amazon API Gateway }, { "description" : "Item 3 is a fish.", "askingPrice" : 0.99 } ] } The following example is a payload model that describes the output data. { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PetStoreOutputModel", "type" : "object", "required" : [ "description", "askingPrice" ], "properties" : { "description" : { "type" : "string" }, "askingPrice" : { "type" : "number", "minimum" : 25.0, "maximum" : 500.0 } } } With this model, you can call an SDK to retrieve the description and askingPrice property values by reading the PetStoreOutputModel[i].description and PetStoreOutputModel[i].askingPrice properties. If no model is provided, API Gateway uses the empty model to create a default UDT. Next steps • This section provides resources that you can use to gain more knowledge about the concepts presented in this topic. You can follow the request validation tutorials: • Set up request validation using the API Gateway console • Set up basic request validation using the AWS CLI • Set up basic request validation using an OpenAPI definition Request validation 473 Amazon API Gateway Developer Guide • For more information about data transformation and mapping templates, Mapping template transformations for REST APIs in API Gateway. Set up basic request validation in API Gateway This section shows how to set up request validation for API Gateway using the console, AWS CLI, and an OpenAPI definition. Topics • Set up request validation using the API Gateway console • Set up basic request validation using the AWS CLI • Set up basic request validation using an OpenAPI definition Set up request validation using the API Gateway console You can use the API Gateway console to validate a request by selecting one of three validators for an API request: • Validate body. • Validate query string parameters and headers. • Validate body, query string parameters, and headers. When you apply one of the validators on an API method, the API Gateway console adds the validator to the API's RequestValidators map. To follow this tutorial, you'll use an AWS CloudFormation template to create an incomplete API Gateway API. This API has a /validator resource with GET and POST methods. Both methods are integrated with the http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP endpoint. You will configure two kinds of request validation: • In the GET method, you will configure request validation for URL query string parameters. • In the POST method, you will configure request validation for the request body. This will allow only certain API calls to pass through to the API. Download and unzip the app creation template for AWS CloudFormation. You'll use this template to create an incomplete API. You will finish the rest of the steps in the API Gateway console. Request validation 474 Amazon API Gateway Developer Guide To create an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Choose Create stack and then choose With new resources (standard). 3. 4. For Specify template, choose Upload a template file. Select the template that you downloaded. 5. Choose Next. 6. 7. 8. For Stack name, enter request-validation-tutorial-console and then choose Next. For Configure stack options, choose Next. For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account. 9. Choose Submit. AWS CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. When the status of your AWS CloudFormation stack is CREATE_COMPLETE, you're ready to move on to the next step. To select your newly created API 1. Select the newly created request-validation-tutorial-console stack. 2. Choose Resources. 3. Under Physical ID, choose your API. This link will direct you to the API Gateway console. Before
apigateway-dg-135
apigateway-dg.pdf
135
request-validation-tutorial-console and then choose Next. For Configure stack options, choose Next. For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account. 9. Choose Submit. AWS CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. When the status of your AWS CloudFormation stack is CREATE_COMPLETE, you're ready to move on to the next step. To select your newly created API 1. Select the newly created request-validation-tutorial-console stack. 2. Choose Resources. 3. Under Physical ID, choose your API. This link will direct you to the API Gateway console. Before you modify the GET and POST methods, you must create a model. To create a model 1. A model is required to use request validation on the body of an incoming request. To create a model, in the main navigation pane, choose Models. 2. Choose Create model. 3. 4. For Name, enter PetStoreModel. For Content Type, enter application/json. If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, enter $default. Request validation 475 Amazon API Gateway Developer Guide 5. 6. For Description, enter My PetStore Model as the model description. For Model schema, paste the following model into the code editor, and choose Create. { "type" : "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" }, "price" : { "type" : "number", "minimum" : 25.0, "maximum" : 500.0 } } } For more information about the model, see Data models for REST APIs. To configure request validation for a GET method 1. In the main navigation pane, choose Resources, and then select the GET method. 2. On the Method request tab, under Method request settings, choose Edit. 3. For Request validator, select Validate query string parameters and headers. 4. Under URL query string parameters, do the following: a. b. c. Choose Add query string. For Name, enter petType. Turn on Required. d. Keep Caching turned off. 5. Choose Save. Request validation 476 Amazon API Gateway Developer Guide 6. On the Integration request tab, under Integration request settings, choose Edit. 7. Under URL query string parameters, do the following: a. b. c. Choose Add query string. For Name, enter petType. For Mapped from, enter method.request.querystring.petType. This maps the petType to the pet's type. For more information about data mapping, see the data mapping tutorial. d. Keep Caching turned off. 8. Choose Save. To test request validation for the GET method 1. Choose the Test tab. You might need to choose the right arrow button to show the tab. 2. 3. For Query strings, enter petType=dog, and then choose Test. The method test will return 200 OK and a list of dogs. For information about how to transform this output data, see the data mapping tutorial. 4. Remove petType=dog and choose Test. 5. The method test will return a 400 error with the following error message: { "message": "Missing required request parameters: [petType]" } To configure request validation for the POST method 1. In the main navigation pane, choose Resources, and then select the POST method. 2. On the Method request tab, under Method request settings, choose Edit. 3. For Request validator, select Validate body. 4. Under Request body, choose Add model. 5. For Content type, enter application/json. If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, enter $default. Request validation 477 Amazon API Gateway Developer Guide For Model, select PetStoreModel. 6. Choose Save. To test request validation for a POST method 1. Choose the Test tab. You might need to choose the right arrow button to show the tab. 2. For Request body paste the following into the code editor: { "id": 2, "name": "Bella", "type": "dog", "price": 400 } Choose Test. 3. 4. The method test will return 200 OK and a success message. For Request body paste the following into the code editor: { "id": 2, "name": "Bella", "type": "dog", "price": 4000 } Choose Test. 5. The method test will return a 400 error with the following error message: { "message": "Invalid request body" } At the bottom of the test logs, the reason for the invalid request body is returned. In this case, the price of the pet was outside the maximum specified in the model. Request validation 478 Amazon API Gateway Developer Guide To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack. 3. Choose Delete and then confirm your choice. Next steps • For information about how to transform output data
apigateway-dg-136
apigateway-dg.pdf
136
Test. 5. The method test will return a 400 error with the following error message: { "message": "Invalid request body" } At the bottom of the test logs, the reason for the invalid request body is returned. In this case, the price of the pet was outside the maximum specified in the model. Request validation 478 Amazon API Gateway Developer Guide To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack. 3. Choose Delete and then confirm your choice. Next steps • For information about how to transform output data and perform more data mapping, see the data mapping tutorial. • Follow the Set up basic request validation using the AWS CLI tutorial, to do similar steps using the AWS CLI. Set up basic request validation using the AWS CLI You can create a validator to set up request validation using the AWS CLI. To follow this tutorial, you'll use an AWS CloudFormation template to create an incomplete API Gateway API. Note This is not the same AWS CloudFormation template as the console tutorial. Using a pre-exposed /validatorresource, you will create GET and POST methods. Both methods will be integrated with the http://petstore-demo-endpoint.execute-api.com/ petstore/pets HTTP endpoint. You will configure the following two request validations: • On the GET method, you will create a params-only validator to validate URL query string parameters. • On the POST method, you will create a body-only validator to validate the request body. This will allow only certain API calls to pass through to the API. To create an AWS CloudFormation stack Download and unzip the app creation template for AWS CloudFormation. To complete the following tutorial, you need the AWS Command Line Interface (AWS CLI) version 2. Request validation 479 Amazon API Gateway Developer Guide For long commands, an escape character (\) is used to split a command over multiple lines. Note In Windows, some Bash CLI commands that you commonly use (such as zip) are not supported by the operating system's built-in terminals. To get a Windows-integrated version of Ubuntu and Bash, install the Windows Subsystem for Linux. Example CLI commands in this guide use Linux formatting. Commands which include inline JSON documents must be reformatted if you are using the Windows CLI. 1. Use the following command to create the AWS CloudFormation stack. aws cloudformation create-stack --stack-name request-validation-tutorial-cli --template-body file://request-validation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM 2. AWS CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. Use the following command to see the status of your AWS CloudFormation stack. aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli 3. When the status of your AWS CloudFormation stack is StackStatus: "CREATE_COMPLETE", use the following command to retrieve relevant output values for future steps. aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}" The output values are the following: • ApiId, which is the ID for the API. For this tutorial, the API ID is abc123. • ResourceId, which is the ID for the validator resource where the GET and POST methods are exposed. For this tutorial, the Resource ID is efg456 Request validation 480 Amazon API Gateway Developer Guide To create the request validators and import a model 1. A validator is required to use request validation with the AWS CLI. Use the following command to create a validator that validates only request parameters. aws apigateway create-request-validator --rest-api-id abc123 \ --no-validate-request-body \ --validate-request-parameters \ --name params-only Note the ID of the params-only validator. 2. Use the following command to create a validator that validates only the request body. aws apigateway create-request-validator --rest-api-id abc123 \ --validate-request-body \ --no-validate-request-parameters \ --name body-only Note the ID of the body-only validator. 3. A model is required to use request validation on the body of an incoming request. Use the following command to import a model. aws apigateway create-model --rest-api-id abc123 --name PetStoreModel --description 'My PetStore Model' --content-type 'application/json' --schema '{"type": "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : {"type" : "integer"},"type" : {"type" : "string", "enum" : [ "dog", "cat", "fish" ]},"name" : { "type" : "string"},"price" : {"type" : "number","minimum" : 25.0, "maximum" : 500.0}}}}' If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, specify $default as the key. To create the GET and POST methods 1. Use the following command to add the GET HTTP method on the /validate resource. This command creates the GETmethod, adds the params-only validator, and sets the query string petType as required. Request validation 481 Amazon API Gateway Developer Guide aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --authorization-type "NONE" \ --request-validator-id aaa111 \ --request-parameters "method.request.querystring.petType=true" Use the following command to add the
apigateway-dg-137
apigateway-dg.pdf
137
no matching content type is found, request validation is not performed. To use the same model regardless of the content type, specify $default as the key. To create the GET and POST methods 1. Use the following command to add the GET HTTP method on the /validate resource. This command creates the GETmethod, adds the params-only validator, and sets the query string petType as required. Request validation 481 Amazon API Gateway Developer Guide aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --authorization-type "NONE" \ --request-validator-id aaa111 \ --request-parameters "method.request.querystring.petType=true" Use the following command to add the POST HTTP method on the /validate resource. This command creates the POSTmethod, adds the body-only validator, and attaches the model to the body-only validator. aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --authorization-type "NONE" \ --request-validator-id bbb222 \ --request-models 'application/json'=PetStoreModel 2. Use the following command to set up the 200 OK response of the GET /validate method. aws apigateway put-method-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --status-code 200 Use the following command to set up the 200 OK response of the POST /validate method. aws apigateway put-method-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200 3. Use the following command to set up an Integration with a specified HTTP endpoint for the GET /validation method. aws apigateway put-integration --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --type HTTP \ --integration-http-method GET \ Request validation 482 Amazon API Gateway Developer Guide --request-parameters '{"integration.request.querystring.type" : "method.request.querystring.petType"}' \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets' Use the following command to set up an Integration with a specified HTTP endpoint for the POST /validation method. aws apigateway put-integration --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --type HTTP \ --integration-http-method GET \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets' 4. Use the following command to set up an integration response for the GET /validation method. aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456\ --http-method GET \ --status-code 200 \ --selection-pattern "" Use the following command to set up an integration response for the POST /validation method. aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200 \ --selection-pattern "" To test the API 1. To test the GET method, which will perform request validation for the query strings, use the following command: aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ Request validation 483 Amazon API Gateway Developer Guide --path-with-query-string '/validate?petType=dog' The result will return a 200 OK and list of dogs. 2. Use the following command to test without including the query string petType aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET The result will return a 400 error. 3. To test the POST method, which will perform request validation for the request body, use the following command: aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --body '{"id": 1, "name": "bella", "type": "dog", "price" : 400 }' The result will return a 200 OK and a success message. 4. Use the following command to test using an invalid body. aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --body '{"id": 1, "name": "bella", "type": "dog", "price" : 1000 }' The result will return a 400 error, as the price of the dog is over the maximum price defined by the model. To delete an AWS CloudFormation stack • Use the following command to delete your AWS CloudFormation resources. aws cloudformation delete-stack --stack-name request-validation-tutorial-cli Request validation 484 Amazon API Gateway Developer Guide Set up basic request validation using an OpenAPI definition You can declare a request validator at the API level by specifying a set of the x-amazon- apigateway-request-validators.requestValidator object objects in the x-amazon-apigateway- request-validators object map to select what part of the request will be validated. In the example OpenAPI definition, there are two validators: • all validator which validates both the body, using the RequestBodyModel data model, and the parameters. The RequestBodyModel data model requires that the input JSON object contains the name, type, and price properties. The name property can be any string, type must be one of the specified enumeration fields (["dog", "cat", "fish"]), and price must range between 25 and 500. The id parameter is not required. • param-only which validates only the parameters. To turn a request validator on all methods of an API, specify an x-amazon-apigateway-request- validator property property at the API level of the OpenAPI definition. In the example OpenAPI definition, the all validator is used on all API methods, unless otherwise overridden. When using a model to validate the body, if no matching content type is found, request validation is not performed. To use the same model regardless of the content type, specify $default as the key. To turn on a request validator on an individual
apigateway-dg-138
apigateway-dg.pdf
138
500. The id parameter is not required. • param-only which validates only the parameters. To turn a request validator on all methods of an API, specify an x-amazon-apigateway-request- validator property property at the API level of the OpenAPI definition. In the example OpenAPI definition, the all validator is used on all API methods, unless otherwise overridden. When using a model to validate the body, if no matching content type is found, request validation is not performed. To use the same model regardless of the content type, specify $default as the key. To turn on a request validator on an individual method, specify the x-amazon-apigateway- request-validator property at the method level. In the example, OpenAPI definition, the param-only validator overwrites the all validator on the GET method. To import the OpenAPI example into API Gateway, see the following instructions to Import a Regional API into API Gateway or to Import an edge-optimized API into API Gateway. OpenAPI 3.0 { "openapi" : "3.0.1", "info" : { "title" : "ReqValidators Sample", "version" : "1.0.0" }, "servers" : [ { "url" : "/{basePath}", Request validation 485 Amazon API Gateway Developer Guide "variables" : { "basePath" : { "default" : "/v1" } } } ], "paths" : { "/validation" : { "get" : { "parameters" : [ { "name" : "q1", "in" : "query", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response", "headers" : { "test-method-response-header" : { "schema" : { "type" : "string" } } }, "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/ArrayOfError" } } } } }, "x-amazon-apigateway-request-validator" : "params-only", "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { Request validation 486 Amazon API Gateway Developer Guide "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.querystring.type" : "method.request.querystring.q1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } }, "post" : { "parameters" : [ { "name" : "h1", "in" : "header", "required" : true, "schema" : { "type" : "string" } } ], "requestBody" : { "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/RequestBodyModel" } } }, "required" : true }, "responses" : { "200" : { "description" : "200 response", "headers" : { "test-method-response-header" : { "schema" : { Request validation 487 Amazon API Gateway Developer Guide "type" : "string" } } }, "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/ArrayOfError" } } } } }, "x-amazon-apigateway-request-validator" : "all", "x-amazon-apigateway-integration" : { "httpMethod" : "POST", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.custom_h1" : "method.request.header.h1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } }, "components" : { "schemas" : { Request validation 488 Amazon API Gateway Developer Guide "RequestBodyModel" : { "required" : [ "name", "price", "type" ], "type" : "object", "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" }, "price" : { "maximum" : 500.0, "minimum" : 25.0, "type" : "number" } } }, "ArrayOfError" : { "type" : "array", "items" : { "$ref" : "#/components/schemas/Error" } }, "Error" : { "type" : "object" } } }, "x-amazon-apigateway-request-validators" : { "all" : { "validateRequestParameters" : true, "validateRequestBody" : true }, "params-only" : { "validateRequestParameters" : true, "validateRequestBody" : false } } } Request validation 489 Amazon API Gateway OpenAPI 2.0 Developer Guide { "swagger" : "2.0", "info" : { "version" : "1.0.0", "title" : "ReqValidators Sample" }, "basePath" : "/v1", "schemes" : [ "https" ], "paths" : { "/validation" : { "get" : { "produces" : [ "application/json", "application/xml" ], "parameters" : [ { "name" : "q1", "in" : "query", "required" : true, "type" : "string" } ], "responses" : { "200" : { "description" : "200 response", "schema" : { "$ref" : "#/definitions/ArrayOfError" }, "headers" : { "test-method-response-header" : { "type" : "string" } } } }, "x-amazon-apigateway-request-validator" : "params-only", "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, Request validation 490 Amazon API Gateway Developer Guide "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : {
apigateway-dg-139
apigateway-dg.pdf
139
"type" : "string" } ], "responses" : { "200" : { "description" : "200 response", "schema" : { "$ref" : "#/definitions/ArrayOfError" }, "headers" : { "test-method-response-header" : { "type" : "string" } } } }, "x-amazon-apigateway-request-validator" : "params-only", "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, Request validation 490 Amazon API Gateway Developer Guide "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.querystring.type" : "method.request.querystring.q1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } }, "post" : { "consumes" : [ "application/json" ], "produces" : [ "application/json", "application/xml" ], "parameters" : [ { "name" : "h1", "in" : "header", "required" : true, "type" : "string" }, { "in" : "body", "name" : "RequestBodyModel", "required" : true, "schema" : { "$ref" : "#/definitions/RequestBodyModel" } } ], "responses" : { "200" : { "description" : "200 response", "schema" : { "$ref" : "#/definitions/ArrayOfError" }, "headers" : { "test-method-response-header" : { "type" : "string" } } } Request validation 491 Amazon API Gateway }, Developer Guide "x-amazon-apigateway-request-validator" : "all", "x-amazon-apigateway-integration" : { "httpMethod" : "POST", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.custom_h1" : "method.request.header.h1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } }, "definitions" : { "RequestBodyModel" : { "type" : "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" Request validation 492 Developer Guide Amazon API Gateway }, "price" : { "type" : "number", "minimum" : 25.0, "maximum" : 500.0 } } }, "ArrayOfError" : { "type" : "array", "items" : { "$ref" : "#/definitions/Error" } }, "Error" : { "type" : "object" } }, "x-amazon-apigateway-request-validators" : { "all" : { "validateRequestParameters" : true, "validateRequestBody" : true }, "params-only" : { "validateRequestParameters" : true, "validateRequestBody" : false } } } AWS CloudFormation template of a sample API with basic request validation The following AWS CloudFormation example template definition defines a sample API with request validation enabled. The API is a subset of the PetStore API. It exposes a POST method to add a pet to the pets collection and a GET method to query pets by a specified type. There are two request validators declared: GETValidator This validator is enabled on the GET method. It allows API Gateway to verify that the required query parameter (q1) is included and not blank in the incoming request. Request validation 493 Amazon API Gateway POSTValidator Developer Guide This validator is enabled on the POST method. It allows API Gateway to verify that payload request format adheres to the specified RequestBodyModel when the content type is application/json if no matching content type is found, request validation is not performed. To use the same model regardless of the content type, specify $default. RequestBodyModel contains an additional model, RequestBodyModelId, to define the pet ID. AWSTemplateFormatVersion: 2010-09-09 Parameters: StageName: Type: String Default: v1 Description: Name of API stage. Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Name: ReqValidatorsSample RequestBodyModelId: Type: 'AWS::ApiGateway::Model' Properties: RestApiId: !Ref Api ContentType: application/json Description: Request body model for Pet ID. Schema: $schema: 'http://json-schema.org/draft-04/schema#' title: RequestBodyModelId properties: id: type: integer RequestBodyModel: Type: 'AWS::ApiGateway::Model' Properties: RestApiId: !Ref Api ContentType: application/json Description: Request body model for Pet type, name, price, and ID. Schema: $schema: 'http://json-schema.org/draft-04/schema#' title: RequestBodyModel required: - price Request validation 494 Amazon API Gateway - name - type type: object properties: id: "$ref": !Sub - 'https://apigateway.amazonaws.com/restapis/${Api}/models/ ${RequestBodyModelId}' - Api: !Ref Api RequestBodyModelId: !Ref RequestBodyModelId Developer Guide price: type: number minimum: 25 maximum: 500 name: type: string type: type: string enum: - "dog" - "cat" - "fish" GETValidator: Type: AWS::ApiGateway::RequestValidator Properties: Name: params-only RestApiId: !Ref Api ValidateRequestBody: False ValidateRequestParameters: True POSTValidator: Type: AWS::ApiGateway::RequestValidator Properties: Name: body-only RestApiId: !Ref Api ValidateRequestBody: True ValidateRequestParameters: False ValidationResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'validation' ValidationMethodGet: Type: 'AWS::ApiGateway::Method' Request validation 495 Developer Guide Amazon API Gateway Properties: RestApiId: !Ref Api ResourceId: !Ref ValidationResource HttpMethod: GET AuthorizationType: NONE RequestValidatorId: !Ref GETValidator RequestParameters: method.request.querystring.q1: true Integration: Type: HTTP_PROXY IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ ValidationMethodPost: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref ValidationResource HttpMethod: POST AuthorizationType: NONE RequestValidatorId: !Ref POSTValidator RequestModels: application/json : !Ref RequestBodyModel Integration: Type: HTTP_PROXY IntegrationHttpMethod: POST Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ ApiDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: - ValidationMethodGet - RequestBodyModel Properties: RestApiId: !Ref Api StageName: !Sub '${StageName}' Outputs: ApiRootUrl: Description: Root Url of
apigateway-dg-140
apigateway-dg.pdf
140
True ValidateRequestParameters: False ValidationResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'validation' ValidationMethodGet: Type: 'AWS::ApiGateway::Method' Request validation 495 Developer Guide Amazon API Gateway Properties: RestApiId: !Ref Api ResourceId: !Ref ValidationResource HttpMethod: GET AuthorizationType: NONE RequestValidatorId: !Ref GETValidator RequestParameters: method.request.querystring.q1: true Integration: Type: HTTP_PROXY IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ ValidationMethodPost: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref ValidationResource HttpMethod: POST AuthorizationType: NONE RequestValidatorId: !Ref POSTValidator RequestModels: application/json : !Ref RequestBodyModel Integration: Type: HTTP_PROXY IntegrationHttpMethod: POST Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ ApiDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: - ValidationMethodGet - RequestBodyModel Properties: RestApiId: !Ref Api StageName: !Sub '${StageName}' Outputs: ApiRootUrl: Description: Root Url of the API Value: !Sub 'https://${Api}.execute-api.${AWS::Region}.amazonaws.com/${StageName}' Request validation 496 Amazon API Gateway Developer Guide Data transformations for REST APIs in API Gateway Note This section explains features that you use with a non-proxy integration. However, we recommend that when possible, you use a proxy integration for your REST API. A proxy integration has a streamlined integration setup and can evolve with the backend without having to tear down the existing setup. For more information, see the section called “Choose an API integration type”. If you use a non-proxy integration, you can use two features of API Gateway to transform your method request and your integration response. You might transform your method request if it takes a different payload format than the integration request payload. You might transform your integration response if it returns a different payload format than the format you need to return in the method response. For more information about the request lifecycle, see the section called “Example resource for a REST API”. The following example shows a data transformation where for the header "x-version:beta", the x-version header parameter is transformed into the app-version header parameter. The data transformation from x-version to app-version occurs in the integration request. That way, the integration endpoint receives the transformed header parameter value. When the integration endpoint returns a status code, the status code is transformed from 200 to 204 before the method response. Data transformations 497 Amazon API Gateway Developer Guide To create a data transformation, you can use the following features: Parameter mapping In parameter mapping, you can modify integration request URL path parameters, URL query string parameters, or HTTP header values, but you can't modify the integration request payload. You can also modify HTTP response header values. Use parameter mapping to create static header values for cross origin resource sharing (CORS). You can use parameter mapping in your integration request for proxy and non-proxy integrations, but to use parameter mapping for an integration response, you need a non-proxy integration. Parameter mapping doesn't require any scripting in Velocity Template Language (VTL). For more information, see the section called “Parameter mapping”. Mapping template transformations In mapping template transformations, you use a mapping template to map URL path parameters, URL query string parameters, HTTP headers, and the integration request or integration response body. A mapping template is a script expressed in Velocity Template Language (VTL) using JSONPath expressions and applied to the payload based on the Content-type header. Data transformations 498 Amazon API Gateway Developer Guide With a mapping template, you can do the following: • Select which data to send using integration with AWS services, such as Amazon DynamoDB or Lambda functions, or HTTP endpoints. For more information, see the section called “Tutorial: Modify the integration request and response for integrations to AWS services”. • Conditionally override an API's integration request and integration response parameters, create new header values, and override status codes. For more information, see the section called “Override your API's request and response parameters and status codes”. You can also specify the behavior of your API when an integration request body has Content- type header with no matching mapping templates. This is called integration passthrough behavior. For more information, see the section called “Method request behavior for payloads without mapping templates”. Choose between parameter mapping and mapping template transformations We recommend that you use parameter mapping to transform your data when possible. If your API requires you to change the body, or requires you to perform conditional overrides and modifications based on the incoming integration request or integration response, and you can't use a proxy integration, use mapping template transformations. Parameter mapping for REST APIs in API Gateway Note If you are using an HTTP API, see the section called “Parameter mapping”. In parameter mapping, you map request or response parameters. You can map parameters using parameter mapping expressions or static values. For a list of mapping expressions, see the section called “Parameter mapping source reference”. You can use parameter mapping in your integration request for proxy and non-proxy integrations, but to use parameter mapping for an integration response, you need a non-proxy integration. For example, you can map the method request header parameter puppies to the integration request
apigateway-dg-141
apigateway-dg.pdf
141
transformations. Parameter mapping for REST APIs in API Gateway Note If you are using an HTTP API, see the section called “Parameter mapping”. In parameter mapping, you map request or response parameters. You can map parameters using parameter mapping expressions or static values. For a list of mapping expressions, see the section called “Parameter mapping source reference”. You can use parameter mapping in your integration request for proxy and non-proxy integrations, but to use parameter mapping for an integration response, you need a non-proxy integration. For example, you can map the method request header parameter puppies to the integration request header parameter DogsAge0. Then, if a client sends the header puppies:true to your API, the integration request sends the request header DogsAge0:true to the integration endpoint. The following diagram shows the request lifecycle of this example. Data transformations 499 Amazon API Gateway Developer Guide To create this example using API Gateway, see the section called “Example 1: Map a method request parameter to an integration request parameter”. As another example, you can also map the integration response header parameter kittens to the method response header parameter CatsAge0. Then, if the integration endpoint returns kittens:false, the client receives the header CatsAge0:false. The following diagram shows the request lifecycle of this example. Data transformations 500 Amazon API Gateway Developer Guide Topics • Parameter mapping examples for REST APIs in API Gateway • Parameter mapping source reference for REST APIs in API Gateway Parameter mapping examples for REST APIs in API Gateway The following examples show how to create parameter mapping expressions using the API Gateway console, OpenAPI, and AWS CloudFormation templates. For an example of how to use parameter mapping to create the required CORS headers, see the section called “CORS”. Example 1: Map a method request parameter to an integration request parameter The following example maps the method request header parameter puppies to the integration request header parameter DogsAge0. AWS Management Console To map the method request parameter 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Data transformations 501 Developer Guide Amazon API Gateway 2. Choose a REST API. 3. Choose a method. Your method must have a non-proxy integration. 4. For Method request settings, choose Edit. 5. Choose HTTP request headers. 6. Choose Add header. 7. For Name, enter puppies. 8. Choose Save. 9. Choose the Integration request tab, and then for Integration request settings, choose Edit. The AWS Management Console automatically adds a parameter mapping from method.request.header.puppies to puppies for you, but you need to change the Name to match the request header parameter that is expected by your integration endpoint. 10. For Name, enter DogsAge0. 11. Choose Save. 12. Redeploy your API for the changes to take effect. The following steps show you how to verify that your parameter mapping was successful. (Optional) Test your parameter mapping 1. Choose the Test tab. You might need to choose the right arrow button to show the tab. 2. For headers, enter puppies:true. 3. Choose Test. 4. In the Logs, the result should look like the following: Tue Feb 04 00:28:36 UTC 2025 : Method request headers: {puppies=true} Tue Feb 04 00:28:36 UTC 2025 : Method request body before transformations: Tue Feb 04 00:28:36 UTC 2025 : Endpoint request URI: http://petstore-demo- endpoint.execute-api.com/petstore/pets Tue Feb 04 00:28:36 UTC 2025 : Endpoint request headers: {DogsAge0=true, x-amzn-apigateway-api-id=abcd1234, Accept=application/json, User- Agent=AmazonAPIGateway_aaaaaaa, X-Amzn-Trace-Id=Root=1-abcd-12344} Data transformations 502 Amazon API Gateway Developer Guide The request header parameter has changed from puppies to DogsAge0. AWS CloudFormation In this example, you use the body property to import an OpenAPI definition file into API Gateway. AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Body: openapi: 3.0.1 info: title: ParameterMappingExample version: "2025-02-04T00:30:41Z" paths: /pets: get: parameters: - name: puppies in: header schema: type: string responses: "200": description: 200 response x-amazon-apigateway-integration: httpMethod: GET uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets responses: default: statusCode: "200" requestParameters: integration.request.header.DogsAge0: method.request.header.puppies passthroughBehavior: when_no_match type: http ApiGatewayDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: Data transformations 503 Amazon API Gateway Developer Guide RestApiId: !Ref Api ApiGatewayDeployment20250219: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api Stage: Type: 'AWS::ApiGateway::Stage' Properties: DeploymentId: !Ref ApiGatewayDeployment20250219 RestApiId: !Ref Api StageName: prod OpenAPI { "openapi" : "3.0.1", "info" : { "title" : "ParameterMappingExample", "version" : "2025-02-04T00:30:41Z" }, "paths" : { "/pets" : { "get" : { "parameters" : [ { "name" : "puppies", "in" : "header", "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response" } }, "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "200" } Data transformations 504 Amazon API Gateway }, Developer Guide "requestParameters" : { "integration.request.header.DogsAge0" : "method.request.header.puppies" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } } } Example 2: Map multiple method request parameters to different integration request parameters The following example maps the
apigateway-dg-142
apigateway-dg.pdf
142
"/pets" : { "get" : { "parameters" : [ { "name" : "puppies", "in" : "header", "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response" } }, "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "200" } Data transformations 504 Amazon API Gateway }, Developer Guide "requestParameters" : { "integration.request.header.DogsAge0" : "method.request.header.puppies" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } } } Example 2: Map multiple method request parameters to different integration request parameters The following example maps the multi-value method request query string parameter methodRequestQueryParam to the integration request query string parameter integrationQueryParam and maps the method request header parameter methodRequestHeaderParam to the integration request path parameter integrationPathParam. AWS Management Console To map the method request parameters 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose a method. Your method must have a non-proxy integration. 4. For Method request settings, choose Edit. 5. Choose URL query string parameters. 6. Choose Add query string. 7. For Name, enter methodRequestQueryParam. 8. Choose HTTP request headers. 9. Choose Add header. 10. For Name, enter methodRequestHeaderParam. Data transformations 505 Amazon API Gateway 11. Choose Save. Developer Guide 12. Choose the Integration request tab, and then for Integration request settings, choose Edit. 13. Choose URL path parameters. 14. Choose Add path parameter. 15. For Name, enter integrationPathParam. 16. For Mapped from, enter method.request.header.methodRequestHeaderParam. This maps the method request header you specified in the method request to a new integration request path parameter. 17. Choose URL query string parameters. 18. Choose Add query string. 19. For Name, enter integrationQueryParam. 20. For Mapped from, enter method.request.multivaluequerystring.methodRequestQueryParam. This maps the multivalue query string parameter to a new single valued integration request query string parameter. 21. Choose Save. 22. Redeploy your API for the changes to take effect. AWS CloudFormation In this example, you use the body property to import an OpenAPI definition file into API Gateway. The following OpenAPI definition creates the following parameter mappings for an HTTP integration: • The method request's header, named methodRequestHeaderParam, into the integration request path parameter, named integrationPathParam • The multi-value method request query string, named methodRequestQueryParam, into the integration request query string, named integrationQueryParam AWSTemplateFormatVersion: 2010-09-09 Data transformations 506 Amazon API Gateway Resources: Developer Guide Api: Type: 'AWS::ApiGateway::RestApi' Properties: Body: openapi: 3.0.1 info: title: Parameter mapping example 2 version: "2025-01-15T19:12:31Z" paths: /: post: parameters: - name: methodRequestQueryParam in: query schema: type: string - name: methodRequestHeaderParam in: header schema: type: string responses: "200": description: 200 response x-amazon-apigateway-integration: httpMethod: GET uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets responses: default: statusCode: "200" requestParameters: integration.request.querystring.integrationQueryParam: method.request.multivaluequerystring.methodRequestQueryParam integration.request.path.integrationPathParam: method.request.header.methodRequestHeaderParam requestTemplates: application/json: '{"statusCode": 200}' passthroughBehavior: when_no_templates timeoutInMillis: 29000 type: http ApiGatewayDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: Data transformations 507 Amazon API Gateway Developer Guide RestApiId: !Ref Api ApiGatewayDeployment20250219: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api Stage: Type: 'AWS::ApiGateway::Stage' Properties: DeploymentId: !Ref ApiGatewayDeployment20250219 RestApiId: !Ref Api StageName: prod OpenAPI The following OpenAPI definition creates the following parameter mappings for an HTTP integration: • The method request's header, named methodRequestHeaderParam, into the integration request path parameter, named integrationPathParam • The multi-value method request query string, named methodRequestQueryParam, into the integration request query string, named integrationQueryParam { "openapi" : "3.0.1", "info" : { "title" : "Parameter mapping example 2", "version" : "2025-01-15T19:12:31Z" }, "paths" : { "/" : { "post" : { "parameters" : [ { "name" : "methodRequestQueryParam", "in" : "query", "schema" : { "type" : "string" } }, { "name" : "methodRequestHeaderParam", "in" : "header", Data transformations 508 Amazon API Gateway Developer Guide "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response" } }, "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.querystring.integrationQueryParam" : "method.request.multivaluequerystring.methodRequestQueryParam", "integration.request.path.integrationPathParam" : "method.request.header.methodRequestHeaderParam" }, "requestTemplates" : { "application/json" : "{\"statusCode\": 200}" }, "passthroughBehavior" : "when_no_templates", "timeoutInMillis" : 29000, "type" : "http" } } } } } Example 3: Map fields from the JSON request body to integration request parameters You can also map integration request parameters from fields in the JSON request body using a JSONPath expression. The following example maps the method request body to an integration request header named body-header and maps part of the request body, as expressed by a JSON expression to an integration request header named pet-price. Data transformations 509 Amazon API Gateway Developer Guide To test this example, provide an input that contains a price category, such as the following: [ { "id": 1, "type": "dog", "price": 249.99 } ] AWS Management Console To map the method request parameters 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose
apigateway-dg-143
apigateway-dg.pdf
143
body using a JSONPath expression. The following example maps the method request body to an integration request header named body-header and maps part of the request body, as expressed by a JSON expression to an integration request header named pet-price. Data transformations 509 Amazon API Gateway Developer Guide To test this example, provide an input that contains a price category, such as the following: [ { "id": 1, "type": "dog", "price": 249.99 } ] AWS Management Console To map the method request parameters 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose a POST, PUT, PATCH, or ANY method. Your method must have a non-proxy integration. 4. For Integration request settings, choose Edit. 5. Choose URL request headers parameters. 6. Choose Add request header parameter. 7. 8. For Name, enter body-header. For Mapped from, enter method.request.body. This maps the method request body to a new integration request header parameter. 9. Choose Add request header parameter. 10. For Name, enter pet-price. 11. For Mapped from, enter method.request.body[0].price. This maps a part of the method request body to a new integration request header parameter. 12. Choose Save. 13. Redeploy your API for the changes to take effect. Data transformations 510 Amazon API Gateway AWS CloudFormation Developer Guide In this example, you use the body property to import an OpenAPI definition file into API Gateway. AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Body: openapi: 3.0.1 info: title: Parameter mapping example 3 version: "2025-01-15T19:19:14Z" paths: /: post: responses: "200": description: 200 response x-amazon-apigateway-integration: httpMethod: GET uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets responses: default: statusCode: "200" requestParameters: integration.request.header.pet-price: method.request.body[0].price integration.request.header.body-header: method.request.body requestTemplates: application/json: '{"statusCode": 200}' passthroughBehavior: when_no_templates timeoutInMillis: 29000 type: http ApiGatewayDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api ApiGatewayDeployment20250219: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: Data transformations 511 Amazon API Gateway Developer Guide RestApiId: !Ref Api Stage: Type: 'AWS::ApiGateway::Stage' Properties: DeploymentId: !Ref ApiGatewayDeployment20250219 RestApiId: !Ref Api StageName: prod OpenAPI The following OpenAPI definition map integration request parameters from fields in the JSON request body. { "openapi" : "3.0.1", "info" : { "title" : "Parameter mapping example 3", "version" : "2025-01-15T19:19:14Z" }, "paths" : { "/" : { "post" : { "responses" : { "200" : { "description" : "200 response" } }, "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.pet-price" : "method.request.body[0].price", "integration.request.header.body-header" : "method.request.body" }, "requestTemplates" : { "application/json" : "{\"statusCode\": 200}" }, "passthroughBehavior" : "when_no_templates", Data transformations 512 Amazon API Gateway Developer Guide "timeoutInMillis" : 29000, "type" : "http" } } } } } Example 4: Map the integration response to the method response You can also map the integration response to the method response. The following example maps the integration response body to a method response header named location, maps the integration response header x-app-id to the method response header id, and maps the multi- valued integration response header item to the method response header items. AWS Management Console To map the integration response 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose a method. Your method must have a non-proxy integration. 4. Choose the Method response tab, and then for Response 200, choose Edit. 5. For Header name, choose Add header. 6. Create three headers named id, item, and location. 7. Choose Save. 8. Choose the Integration response tab, and then for Default - Response, choose Edit. 9. Under Header mappings, enter the following. a. b. c. For id, enter integration.response.header.x-app-id For item, enter integration.response.multivalueheader.item For location, enter integration.response.body.redirect.url 10. Choose Save. 11. Redeploy your API for the changes to take effect. Data transformations 513 Amazon API Gateway AWS CloudFormation Developer Guide In this example, you use the body property to import an OpenAPI definition file into API Gateway. AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Body: openapi: 3.0.1 info: title: Parameter mapping example version: "2025-01-15T19:21:35Z" paths: /: post: responses: "200": description: 200 response headers: item: schema: type: string location: schema: type: string id: schema: type: string x-amazon-apigateway-integration: type: http httpMethod: GET uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets responses: default: statusCode: "200" responseParameters: method.response.header.id: integration.response.header.x-app- id method.response.header.location: integration.response.body.redirect.url Data transformations 514 Amazon API Gateway Developer Guide method.response.header.item: integration.response.multivalueheader.item requestTemplates: application/json: '{"statusCode": 200}' passthroughBehavior: when_no_templates timeoutInMillis: 29000 ApiGatewayDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api ApiGatewayDeployment20250219: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api Stage: Type: 'AWS::ApiGateway::Stage' Properties: DeploymentId: !Ref ApiGatewayDeployment20250219 RestApiId: !Ref Api StageName: prod OpenAPI The following OpenAPI definition maps the integration response to the method response. { "openapi" : "3.0.1", "info" : { "title" : "Parameter mapping example", "version" : "2025-01-15T19:21:35Z" }, "paths" : { "/" : { "post" : { "responses" : { "200" : { "description" : "200 response", "headers" : { "item" : { "schema" : { "type" : "string"
apigateway-dg-144
apigateway-dg.pdf
144
method.response.header.item: integration.response.multivalueheader.item requestTemplates: application/json: '{"statusCode": 200}' passthroughBehavior: when_no_templates timeoutInMillis: 29000 ApiGatewayDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api ApiGatewayDeployment20250219: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api Stage: Type: 'AWS::ApiGateway::Stage' Properties: DeploymentId: !Ref ApiGatewayDeployment20250219 RestApiId: !Ref Api StageName: prod OpenAPI The following OpenAPI definition maps the integration response to the method response. { "openapi" : "3.0.1", "info" : { "title" : "Parameter mapping example", "version" : "2025-01-15T19:21:35Z" }, "paths" : { "/" : { "post" : { "responses" : { "200" : { "description" : "200 response", "headers" : { "item" : { "schema" : { "type" : "string" } Data transformations 515 Amazon API Gateway Developer Guide }, "location" : { "schema" : { "type" : "string" } }, "id" : { "schema" : { "type" : "string" } } } } }, "x-amazon-apigateway-integration" : { "type" : "http", "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "200", "responseParameters" : { "method.response.header.id" : "integration.response.header.x-app- id", "method.response.header.location" : "integration.response.body.redirect.url", "method.response.header.item" : "integration.response.multivalueheader.item" } } }, "requestTemplates" : { "application/json" : "{\"statusCode\": 200}" }, "passthroughBehavior" : "when_no_templates", "timeoutInMillis" : 29000 } } } } } Data transformations 516 Amazon API Gateway Developer Guide Parameter mapping source reference for REST APIs in API Gateway When you create a parameter mapping, you specify the method request or integration response parameters to modify and you specify how to modify those parameters. The following table shows the method request parameters that you can map, and the expression to create the mapping. In these expressions, name is the name of a method request parameter. For example, to map the request header parameter puppies, use the expression method.request.header.puppies. Your expression must match the regular expression '^[a- zA-Z0-9._$-]+$]'. You can use parameter mapping in your integration request for proxy and non-proxy integrations. Mapped data source Mapping expression Method request path method.request.path. name Method request query string method.request.querystring. name Multi-value method request query string method.request.multivaluequ erystring. name Method request header method.request.header. name Multi-value method request header method.request.multivaluehe ader. name Method request body method.request.body Method request body (JsonPath) method.request.body. JSONPath_ EXPRESSION . JSONPath_EXPRESSION is a JSONPath expression for a JSON field of the body of a request. For more information, see JSONPath expression. Stage variables Context variables stageVariables. name context.name Data transformations 517 Amazon API Gateway Developer Guide Mapped data source Mapping expression Static value The name must be one of the supported context variables. 'static_value' . The static_value is a string literal and must be enclosed within a pair of single quotes. For example, 'https://www.examp le.com' . The following table shows the integration response parameters that you can map and the expression to create the mapping. In these expressions, name is the name of an integration response parameter. You can map method response headers from any integration response header or integration response body, $context variables, or static values. To use parameter mapping for an integration response, you need a non-proxy integration. Mapped data source Mapping expression Integration response header integration.response.header. name Integration response header integration.response.multiv alueheader. name Integration response body integration.response.body Integration response body (JsonPath) integration.respon se.body. JSONPath_EXPRESSION JSONPath_EXPRESSION is a JSONPath expression for a JSON field of the body of a response. For more information, see JSONPath expression. Stage variable Context variable stageVariables. name context.name Data transformations 518 Amazon API Gateway Developer Guide Mapped data source Mapping expression Static value The name must be one of the supported context variables. 'static_value' The static_value is a string literal and must be enclosed within a pair of single quotes. For example, 'https://www.examp le.com' . Mapping template transformations for REST APIs in API Gateway A mapping template transformation uses a mapping template to modify your integration request or integration response. A mapping template is a script expressed in Velocity Template Language (VTL) and applied to a payload using JSONPath based on the Content-type header. You use mapping templates when you use mapping template transformations. This section describes conceptual information related to mapping templates. The following diagram shows the request lifecycle for a POST /pets resource that has an integration with a PetStore integration endpoint. In this API, a user sends data about a pet and the integration endpoint returns the adoption fee associated with a pet. In this request lifecycle, mapping template transformations filter the request body to the integration endpoint and filter the response body from the integration endpoint. Data transformations 519 Amazon API Gateway Developer Guide The following sections explain the request and response lifecycle. Method request and integration request In the previous example, if this is the request body sent to the method request: POST /pets HTTP/1.1 Host:abcd1234.us-west-2.amazonaws.com Content-type: application/json { "id": 1, "type": "dog", "Age": 11, } This request body is not in the correct format to be used by the integration endpoint, so API Gateway performs a mapping template
apigateway-dg-145
apigateway-dg.pdf
145
a pet. In this request lifecycle, mapping template transformations filter the request body to the integration endpoint and filter the response body from the integration endpoint. Data transformations 519 Amazon API Gateway Developer Guide The following sections explain the request and response lifecycle. Method request and integration request In the previous example, if this is the request body sent to the method request: POST /pets HTTP/1.1 Host:abcd1234.us-west-2.amazonaws.com Content-type: application/json { "id": 1, "type": "dog", "Age": 11, } This request body is not in the correct format to be used by the integration endpoint, so API Gateway performs a mapping template transformation. API Gateway only performs a mapping template transformation because there is a mapping template defined for the Content-Type application/json. If you don't define a mapping template for the Content-Type, by default, API Data transformations 520 Amazon API Gateway Developer Guide Gateway passes the body through the integration request to the integration endpoint. To modify this behavior, see the section called “Method request behavior for payloads without mapping templates”. The following mapping template transforms the method request data in the integration request before it's sent to the integration endpoint: #set($inputRoot = $input.path('$')) { "dogId" : "dog_"$elem.id, "Age": $inputRoot.Age } 1. The $inputRoot variable represents the root object in the original JSON data from the previous section. Directives begin with the # symbol. 2. The dog is a concatenation of the user's id and a string value. 3. Age is from the method request body. Then, the following output is forwarded to the integration endpoint: { "dogId" : "dog_1", "Age": 11 } Integration response and method response After the successful request to the integration endpoint, the endpoint sends a response to API Gateway's integration response. The following is the example output data from the integration endpoint: { "dogId" : "dog_1", "adoptionFee": 19.95, } The method response expects a different payload than what is returned by the integration response. API Gateway performs a mapping template transformation. API Gateway only performs Data transformations 521 Amazon API Gateway Developer Guide a mapping template transformation because there is a mapping template defined for the Content- Type application/json. If you don't define a mapping template for the Content-Type, by default, API Gateway passes the body through the integration response to the method response. To modify this behavior, see the section called “Method request behavior for payloads without mapping templates”. #set($inputRoot = $input.path('$')) { "adoptionFee" : $inputRoot.adoptionFee, } The following output is sent to the method response: {"adoptionFee": 19.95} This completes the example mapping template transformation. We recommend that when possible, instead of using mapping template transformations, you use a proxy integration to transform your data. For more information, see the section called “Choose an API integration type”. Method request behavior for payloads without mapping templates for REST APIs in API Gateway If your method request has a payload and you don't have a mapping template defined for the Content-Type header, you can choose to pass the client-supplied request payload through the integration request to the backend without transformation. The process is known as integration passthrough. The actual passthrough behavior of an incoming request is determined by this setting. There are three options: When no template matches the request Content-Type header Choose this option if you want the method request body to pass through the integration request to the backend without transformation when the method request content type does not match any content types associated with the mapping templates. When calling the API Gateway API, you choose this option by setting WHEN_NO_MATCH as the passthroughBehavior property value on the Integration. Data transformations 522 Amazon API Gateway Developer Guide When there are no templates defined (recommended) Choose this option if you want the method request body to pass through the integration request to the backend without transformation when no mapping template is defined in the integration request. If a template is defined when this option is selected, the method request with a payload and content type that doesn't match any defined mapping template will be rejected with an HTTP 415 Unsupported Media Type response. When calling the API Gateway API, you choose this option by setting WHEN_NO_TEMPLATES as the passthroughBehavior property value on the Integration. Never Choose this option if you do not want the method request body to pass through the integration request to the backend without transformation when no mapping template is defined in the integration request. If a template is defined when this option is selected, the method request of an unmapped content type will be rejected with an HTTP 415 Unsupported Media Type response. When calling the API Gateway API, you choose this option by setting NEVER as the passthroughBehavior property value on the Integration. The following examples show the possible passthrough behaviors. Example 1: One mapping template is defined in the integration request
apigateway-dg-146
apigateway-dg.pdf
146
option if you do not want the method request body to pass through the integration request to the backend without transformation when no mapping template is defined in the integration request. If a template is defined when this option is selected, the method request of an unmapped content type will be rejected with an HTTP 415 Unsupported Media Type response. When calling the API Gateway API, you choose this option by setting NEVER as the passthroughBehavior property value on the Integration. The following examples show the possible passthrough behaviors. Example 1: One mapping template is defined in the integration request for the application/ json content type. Content-type Passthrough option Behavior None WHEN_NO_MATCH API Gateway defaults to application/json None WHEN_NO_TEMPLATES API Gateway defaults to application/json The request payload is transformed using the template. The request payload is transformed using the template. Data transformations 523 Amazon API Gateway Developer Guide Content-type Passthrough option Behavior None NEVER API Gateway defaults to application/json application/json WHEN_NO_MATCH application/json WHEN_NO_TEMPLATES application/json NEVER application/xml WHEN_NO_MATCH The request payload is transformed using the template. The request payload is transformed using the template. The request payload is transformed using the template. The request payload is transformed using the template. The request payload is not transformed and is sent to the backend as-is. application/xml WHEN_NO_TEMPLATES The request is rejected with application/xml NEVER an HTTP 415 Unsupport ed Media Type response. The request is rejected with an HTTP 415 Unsupport ed Media Type response. Example 2: One mapping template is defined in the integration request for the application/xml content type. Data transformations 524 Amazon API Gateway Developer Guide Content-type Passthrough option Behavior None WHEN_NO_MATCH API Gateway defaults to application/json The request payload is not transformed and is sent to the backend as-is. None WHEN_NO_TEMPLATES The request is rejected with API Gateway defaults to application/json None NEVER API Gateway defaults to application/json application/json WHEN_NO_MATCH an HTTP 415 Unsupport ed Media Type response. The request is rejected with an HTTP 415 Unsupport ed Media Type response. The request payload is not transformed and is sent to the backend as-is. application/json WHEN_NO_TEMPLATES The request is rejected with application/json NEVER application/xml WHEN_NO_MATCH application/xml WHEN_NO_TEMPLATES an HTTP 415 Unsupport ed Media Type response. The request is rejected with an HTTP 415 Unsupport ed Media Type response. The request payload is transformed using the template. The request payload is transformed using the template. Data transformations 525 Amazon API Gateway Developer Guide Content-type Passthrough option Behavior application/xml NEVER The request payload is transformed using the template. Example 3: No mapping templates are defined in the integration request. Content-type Passthrough option Behavior None WHEN_NO_MATCH API Gateway defaults to application/json None WHEN_NO_TEMPLATES API Gateway defaults to application/json None NEVER API Gateway defaults to application/json application/json WHEN_NO_MATCH application/json WHEN_NO_TEMPLATES application/json NEVER The request payload is not transformed and is sent to the backend as-is. The request payload is not transformed and is sent to the backend as-is. The request is rejected with an HTTP 415 Unsupport ed Media Type response. The request payload is not transformed and is sent to the backend as-is. The request payload is not transformed and is sent to the backend as-is. The request is rejected with an HTTP 415 Unsupport ed Media Type response. Data transformations 526 Amazon API Gateway Developer Guide Content-type Passthrough option Behavior application/xml WHEN_NO_MATCH application/xml WHEN_NO_TEMPLATES application/xml NEVER The request payload is not transformed and is sent to the backend as-is. The request payload is not transformed and is sent to the backend as-is. The request is rejected with an HTTP 415 Unsupport ed Media Type response. Additional mapping template example for REST APIs in API Gateway The following example shows a photo album API in API Gateway that uses mapping templates to transform integration request and integration response data. It also uses data models to define method request and integration response payloads. For more information about data models, see Data models for REST APIs. Method request and integration request The following is a model that defines the method request body. This input model requires that the caller upload one photo page, and requires a minimum of 10 photos for each page. You can use this input model to generate an SDK or to use request validation for your API. While using request validation, if the method request body doesn't adhere to the data structure of the model, API Gateway fails the request. { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PhotosInputModel", "type": "object", "properties": { "photos": { "type": "object", "required" : [ "photo" ], "properties": { Data transformations 527 Amazon API Gateway Developer Guide "page": { "type": "integer" }, "pages": { "type": "string" }, "perpage": { "type": "integer", "minimum" : 10 }, "total": { "type": "string" }, "photo": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "owner": { "type": "string"
apigateway-dg-147
apigateway-dg.pdf
147
to use request validation for your API. While using request validation, if the method request body doesn't adhere to the data structure of the model, API Gateway fails the request. { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PhotosInputModel", "type": "object", "properties": { "photos": { "type": "object", "required" : [ "photo" ], "properties": { Data transformations 527 Amazon API Gateway Developer Guide "page": { "type": "integer" }, "pages": { "type": "string" }, "perpage": { "type": "integer", "minimum" : 10 }, "total": { "type": "string" }, "photo": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "owner": { "type": "string" }, "photographer_first_name" : {"type" : "string"}, "photographer_last_name" : {"type" : "string"}, "secret": { "type": "string" }, "server": { "type": "string" }, "farm": { "type": "integer" }, "title": { "type": "string" }, "ispublic": { "type": "boolean" }, "isfriend": { "type": "boolean" }, "isfamily": { "type": "boolean" } } } } } } } } The following is an example method request body that adheres to the data structure of the previous data model. { "photos": { "page": 1, "pages": "1234", "perpage": 100, "total": "123398", "photo": [ { "id": "12345678901", "owner": "23456789@A12", "photographer_first_name" : "Saanvi", "photographer_last_name" : "Sarkar", Data transformations 528 Amazon API Gateway Developer Guide "secret": "abc123d456", "server": "1234", "farm": 1, "title": "Sample photo 1", "ispublic": true, "isfriend": false, "isfamily": false }, { "id": "23456789012", "owner": "34567890@B23", "photographer_first_name" : "Richard", "photographer_last_name" : "Roe", "secret": "bcd234e567", "server": "2345", "farm": 2, "title": "Sample photo 2", "ispublic": true, "isfriend": false, "isfamily": false } ] } } In this example, if the previous method request body was submitted by the client, then this mapping template transforms the payload to match the format required by the integration endpoint. #set($inputRoot = $input.path('$')) { "photos": [ #foreach($elem in $inputRoot.photos.photo) { "id": "$elem.id", "photographedBy": "$elem.photographer_first_name $elem.photographer_last_name", "title": "$elem.title", "ispublic": $elem.ispublic, "isfriend": $elem.isfriend, "isfamily": $elem.isfamily }#if($foreach.hasNext),#end #end Data transformations 529 Amazon API Gateway ] } The following example is output data from the transformation: Developer Guide { "photos": [ { "id": "12345678901", "photographedBy": "Saanvi Sarkar", "title": "Sample photo 1", "ispublic": true, "isfriend": false, "isfamily": false }, { "id": "23456789012", "photographedBy": "Richard Roe", "title": "Sample photo 2", "ispublic": true, "isfriend": false, "isfamily": false } ] } This data is sent to the integration request, and then to the integration endpoint. Integration response and method response The following is an example output model for the photo data from the integration endpoint. You can use this model for a method response model, which is necessary when you generate a strongly typed SDK for the API. This causes the output to be cast into an appropriate class in Java or Objective-C. { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PhotosOutputModel", "type": "object", "properties": { "photos": { "type": "array", "items": { Data transformations 530 Amazon API Gateway Developer Guide "type": "object", "properties": { "id": { "type": "string" }, "photographedBy": { "type": "string" }, "title": { "type": "string" }, "ispublic": { "type": "boolean" }, "isfriend": { "type": "boolean" }, "isfamily": { "type": "boolean" } } } } } } The integration endpoint might not respond with a response that adheres to the data structure of this model. For instance, the integration response might look like the following: "photos": [ { "id": "12345678901", "photographedBy": "Saanvi Sarkar", "title": "Sample photo 1", "description": "My sample photo 1", "public": true, "friend": false, "family": false }, { "id": "23456789012", "photographedBy": "Richard Roe", "title": "Sample photo 2", "description": "My sample photo 1", "public": true, "friend": false, "family": false } ] } The following example mapping template transforms the integration response data into the format expected by the method response: Data transformations 531 Amazon API Gateway Developer Guide #set($inputRoot = $input.path('$')) { "photos": [ #foreach($elem in $inputRoot.photos.photo) { "id": "$elem.id", "photographedBy": "$elem.photographer_first_name $elem.photographer_last_name", "title": "$elem.title", "ispublic": $elem.public, "isfriend": $elem.friend, "isfamily": $elem.family }#if($foreach.hasNext),#end #end ] } The following example is output data from the transformation: { "photos": [ { "id": "12345678901", "photographedBy": "Saanvi Sarkar", "title": "Sample photo 1", "ispublic": true, "isfriend": false, "isfamily": false }, { "id": "23456789012", "photographedBy": "Richard Roe", "title": "Sample photo 2", "ispublic": true, "isfriend": false, "isfamily": false } ] } This data is sent to the method response and then back to the client. Data transformations 532 Amazon API Gateway Developer Guide Override your API's request and response parameters and status codes for REST APIs in API Gateway You can use mapping template transformations to override any type of request parameter, response header, or response status code. You use a mapping template to do the following: • Perform many-to-one parameter mappings • Override parameters after standard API Gateway mappings have been applied • Conditionally map parameters based on body content or other parameter values • Programmatically create new parameters • Override status codes returned by your integration endpoint Overrides are final. An override may only be applied to each parameter once. If you try
apigateway-dg-148
apigateway-dg.pdf
148
API's request and response parameters and status codes for REST APIs in API Gateway You can use mapping template transformations to override any type of request parameter, response header, or response status code. You use a mapping template to do the following: • Perform many-to-one parameter mappings • Override parameters after standard API Gateway mappings have been applied • Conditionally map parameters based on body content or other parameter values • Programmatically create new parameters • Override status codes returned by your integration endpoint Overrides are final. An override may only be applied to each parameter once. If you try to override the same parameter multiple times, API Gateway returns a 5XX response. If you must override the same parameter multiple times throughout the template, we recommend creating a variable and applying the override at the end of the template. The template is applied only after the entire template is parsed. Example 1: Override the status code based on the integration body The following example use the example API to override the status code based on the integration response body. AWS Management Console To override a status code based on the integration response body 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API. 3. 4. For REST API, choose Build. For API details, choose Example API. 5. Choose Create API. API Gateway creates an example pet store API. To retrieve information about a pet, you use the API method request of GET /pets/{petId}, where {petId} is a path parameter corresponding to an ID number for a pet. Data transformations 533 Amazon API Gateway Developer Guide In this example, you override the GET method's response code to 400 when an error condition is detected. 6. 7. In the Resources tree, choose the GET method under /{petId}. First, you test the current implementation of the API. Choose the Test tab. You might need to choose the right arrow button to show the tab. 8. For petId, enter -1, and then choose Test. The Response body indicates an out-of-range error: { "errors": [ { "key": "GetPetRequest.petId", "message": "The value is out of range." } ] } In addition, the last line under Logs ends with: Method completed with status: 200. The integration was completed successfully, but there was an error. Now you'll override the status code based on the integration response. 9. On the Integration response tab, for the Default - Response, choose Edit. 10. Choose Mapping templates. 11. Choose Add mapping template. 12. For Content type, enter application/json. 13. For Template body, enter the following: #set($inputRoot = $input.path('$')) $input.json("$") #if($inputRoot.toString().contains("error")) #set($context.responseOverride.status = 400) #end This mapping template uses the $context.responseOverride.status variable to override the status code to 400 if the integration response contains the string error. Data transformations 534 Amazon API Gateway Developer Guide 14. Choose Save. 15. Choose the Test tab. 16. For petId, enter -1. 17. In the results, the Response Body indicates an out-of-range error: { "errors": [ { "key": "GetPetRequest.petId", "message": "The value is out of range." } ] } However, the last line under Logs now ends with: Method completed with status: 400. AWS CloudFormation In this example, you use the body property to import an OpenAPI definition file into API Gateway. AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Body: openapi: 3.0.1 info: title: PetStore Example 1 description: Example pet store API. version: "2025-01-14T00:13:18Z" paths: /pets/{petId}: get: parameters: - name: petId in: path required: true Data transformations 535 Amazon API Gateway Developer Guide schema: type: string responses: "200": description: 200 response x-amazon-apigateway-integration: httpMethod: GET uri: http://petstore.execute-api.us-east-1.amazonaws.com/petstore/ pets/{petId} responses: default: statusCode: "200" responseTemplates: application/json: |- #set($inputRoot = $input.path('$')) $input.json("$") #if($inputRoot.toString().contains("error")) #set($context.responseOverride.status = 400) #end requestParameters: integration.request.path.petId: method.request.path.petId passthroughBehavior: when_no_match type: http components: schemas: Pet: type: object properties: id: type: integer type: type: string price: type: number ApiGatewayDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api ApiGatewayDeployment20250219: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api Data transformations 536 Amazon API Gateway Stage: Type: 'AWS::ApiGateway::Stage' Properties: DeploymentId: !Ref ApiGatewayDeployment20250219 RestApiId: !Ref Api StageName: prod OpenAPI Developer Guide The following OpenAPI definition creates the GET pets/{petId} resource and overrides the status code based on the integration body. { "openapi" : "3.0.1", "info" : { "title" : "PetStore Example 1", "description" : "Example pet store API.", "version" : "2025-01-14T00:13:18Z" }, "paths" : { "/pets/{petId}" : { "get" : { "parameters" : [ { "name" : "petId", "in" : "path", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response" } }, "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/ pets/{petId}", "responses" : { "default" : { "statusCode" : "200", "responseTemplates" : { Data transformations 537 Amazon API Gateway Developer Guide "application/json" : "#set($inputRoot = $input.path('$'))\n $input.json(\"$\")\n#if($inputRoot.toString().contains(\"error \"))\n#set($context.responseOverride.status = 400)\n#end" } } }, "requestParameters" :
apigateway-dg-149
apigateway-dg.pdf
149
"PetStore Example 1", "description" : "Example pet store API.", "version" : "2025-01-14T00:13:18Z" }, "paths" : { "/pets/{petId}" : { "get" : { "parameters" : [ { "name" : "petId", "in" : "path", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response" } }, "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/ pets/{petId}", "responses" : { "default" : { "statusCode" : "200", "responseTemplates" : { Data transformations 537 Amazon API Gateway Developer Guide "application/json" : "#set($inputRoot = $input.path('$'))\n $input.json(\"$\")\n#if($inputRoot.toString().contains(\"error \"))\n#set($context.responseOverride.status = 400)\n#end" } } }, "requestParameters" : { "integration.request.path.petId" : "method.request.path.petId" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } }, "components" : { "schemas" : { "Pet" : { "type" : "object", "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string" }, "price" : { "type" : "number" } } } } } } Example 2: Override the request header and create new headers The following example uses the example API to override the request header and create new headers. Data transformations 538 Amazon API Gateway AWS Management Console Developer Guide To override a method's request header by creating a new header 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose the example API you created in the previous tutorial. The name of the API should be PetStore. 3. In the Resources tree, choose the GET method under /pet. 4. On the Method request tab, for Method request settings, choose Edit. 5. Choose HTTP request headers, and then choose Add header. 6. For Name, enter header1. 7. Choose Add header, and then create a second header called header2. 8. Choose Save. Now, you combine these headers into one header value using a mapping template. 9. On the Integration request tab, for Integration request settings, choose Edit. 10. For Request body passthrough, select When there are no templates defined (recommended). 11. Choose Mapping templates, and then do the following: a. b. c. Choose Add mapping template. For Content type, enter application/json. For Template body, enter the following: #set($header1Override = "pets") #set($header3Value = "$input.params('header1')$input.params('header2')") $input.json("$") #set($context.requestOverride.header.header3 = $header3Value) #set($context.requestOverride.header.header1 = $header1Override) #set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value]) This mapping template overrides header1 with the string pets and creates a multi- value header called $header3Value that combines header1 and header2. 12. Choose Save. 13. Choose the Test tab. Data transformations 539 Amazon API Gateway Developer Guide 14. Under Headers, copy the following code: header1:header1Val header2:header2Val 15. Choose Test. In the Logs, you should see an entry that includes this text: Endpoint request headers: {header3=header1Valheader2Val, header2=header2Val, header1=pets, x-amzn-apigateway-api-id=api-id, Accept=application/json, multivalueheader=pets,header1Valheader2Val} AWS CloudFormation In this example, you use the body property to import an OpenAPI definition file into API Gateway. AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Body: openapi: 3.0.1 info: title: PetStore Example 2 description: Example pet store API. version: "2025-01-14T00:36:18Z" paths: /pets: get: parameters: - name: header2 in: header schema: type: string - name: page in: query schema: type: string - name: type Data transformations 540 Amazon API Gateway Developer Guide in: query schema: type: string - name: header1 in: header schema: type: string responses: "200": description: 200 response x-amazon-apigateway-integration: httpMethod: GET uri: http://petstore.execute-api.us-east-1.amazonaws.com/petstore/ pets responses: default: statusCode: "200" requestParameters: integration.request.header.header1: method.request.header.header1 integration.request.header.header2: method.request.header.header2 integration.request.querystring.page: method.request.querystring.page integration.request.querystring.type: method.request.querystring.type requestTemplates: application/json: |- #set($header1Override = "pets") #set($header3Value = "$input.params('header1')$input.params('header2')") $input.json("$") #set($context.requestOverride.header.header3 = $header3Value) #set($context.requestOverride.header.header1 = $header1Override) #set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value]) passthroughBehavior: when_no_match type: http components: schemas: Pet: type: object properties: id: type: integer Data transformations 541 Amazon API Gateway Developer Guide type: type: string price: type: number ApiGatewayDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api ApiGatewayDeployment20250219: Type: 'AWS::ApiGateway::Deployment' DependsOn: Api Properties: RestApiId: !Ref Api Stage: Type: 'AWS::ApiGateway::Stage' Properties: DeploymentId: !Ref ApiGatewayDeployment20250219 RestApiId: !Ref Api StageName: prod OpenAPI The following OpenAPI definition creates the GET pets resource and overrides the request header and create new headers. { "openapi" : "3.0.1", "info" : { "title" : "PetStore Example 2", "description" : "Example pet store API.", "version" : "2025-01-14T00:36:18Z" }, "paths" : { "/pets" : { "get" : { "parameters" : [ { "name" : "header2", "in" : "header", "schema" : { "type" : "string" } }, { Data transformations 542 Amazon API Gateway Developer Guide "name" : "page", "in" : "query", "schema" : { "type" : "string" } }, { "name" : "type", "in" : "query", "schema" : { "type" : "string" } }, { "name" : "header1", "in" : "header", "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response" } }, "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/ pets", "responses" : { "default" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.header1" : "method.request.header.header1", "integration.request.header.header2" : "method.request.header.header2", "integration.request.querystring.page" : "method.request.querystring.page", "integration.request.querystring.type" : "method.request.querystring.type" }, "requestTemplates" : { "application/json" : "#set($header1Override = \"pets
apigateway-dg-150
apigateway-dg.pdf
150
"page", "in" : "query", "schema" : { "type" : "string" } }, { "name" : "type", "in" : "query", "schema" : { "type" : "string" } }, { "name" : "header1", "in" : "header", "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response" } }, "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/ pets", "responses" : { "default" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.header1" : "method.request.header.header1", "integration.request.header.header2" : "method.request.header.header2", "integration.request.querystring.page" : "method.request.querystring.page", "integration.request.querystring.type" : "method.request.querystring.type" }, "requestTemplates" : { "application/json" : "#set($header1Override = \"pets \")\n#set($header3Value = \"$input.params('header1')$input.params('header2')\")\n $input.json(\"$\")\n#set($context.requestOverride.header.header3 Data transformations 543 Amazon API Gateway Developer Guide = $header3Value)\n#set($context.requestOverride.header.header1 = $header1Override)\n#set($context.requestOverride.header.multivalueheader=[$header1Override, $header3Value])" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } } } To use a mapping template override, add one or more of the following $context variables. For a list of $context variables, see the section called “Context variables for data transformations”. Tutorial: Modify the integration request and response for integrations to AWS services The following tutorial shows how to use mapping template transformations to set up mapping templates to transform integration requests and responses using the console and AWS CLI. Topics • Set up data transformation using the API Gateway console • Set up data transformation using the AWS CLI • Completed data transformation AWS CloudFormation template Set up data transformation using the API Gateway console In this tutorial, you will create an incomplete API and DynamoDB table using the following .zip file data-transformation-tutorial-console.zip. This incomplete API has a /pets resource with GET and POST methods. • The GET method will get data from the http://petstore-demo-endpoint.execute- api.com/petstore/pets HTTP endpoint. The output data will be transformed according to the mapping template in the section called “Mapping template transformations”. • The POST method will allow the user to POST pet information to a Amazon DynamoDB table using a mapping template. Data transformations 544 Amazon API Gateway Developer Guide Download and unzip the app creation template for AWS CloudFormation. You'll use this template to create a DynamoDB table to post pet information and an incomplete API. You will finish the rest of the steps in the API Gateway console. To create an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Choose Create stack and then choose With new resources (standard). 3. 4. For Specify template, choose Upload a template file. Select the template that you downloaded. 5. Choose Next. 6. 7. 8. For Stack name, enter data-transformation-tutorial-console and then choose Next. For Configure stack options, choose Next. For Capabilities, acknowledge that AWS CloudFormation can create IAM resources in your account. 9. Choose Submit. AWS CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. When the status of your AWS CloudFormation stack is CREATE_COMPLETE, you're ready to move on to the next step. To test the GET integration response 1. On the Resources tab of the AWS CloudFormation stack for data-transformation- tutorial-console, select the physical ID of your API. 2. In the main navigation pane, choose Resources, and then select the GET method. 3. Choose the Test tab. You might need to choose the right arrow button to show the tab. The output of the test will show the following: [ { "id": 1, "type": "dog", "price": 249.99 }, { Data transformations 545 Amazon API Gateway Developer Guide "id": 2, "type": "cat", "price": 124.99 }, { "id": 3, "type": "fish", "price": 0.99 } ] You will transform this output according to the mapping template in the section called “Mapping template transformations”. To transform the GET integration response 1. Choose the Integration response tab. Currently, there are no mapping templates defined, so the integration response will not be transformed. 2. For Default - Response, choose Edit. 3. Choose Mapping templates, and then do the following: a. b. c. Choose Add mapping template. For Content type, enter application/json. For Template body, enter the following: #set($inputRoot = $input.path('$')) [ #foreach($elem in $inputRoot) { "description" : "Item $elem.id is a $elem.type.", "askingPrice" : $elem.price }#if($foreach.hasNext),#end #end ] Choose Save. Data transformations 546 Amazon API Gateway Developer Guide To test the GET integration response • Choose the Test tab, and then choose Test. The output of the test will show the transformed response. [ { "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 transform input data from the POST method 1. Choose the POST method. 2. Choose the Integration request tab, and then for Integration request settings, choose Edit. The AWS CloudFormation template has populated some of the integration request fields. • The integration type is AWS service.
apigateway-dg-151
apigateway-dg.pdf
151
Test tab, and then choose Test. The output of the test will show the transformed response. [ { "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 transform input data from the POST method 1. Choose the POST method. 2. Choose the Integration request tab, and then for Integration request settings, choose Edit. The AWS CloudFormation template has populated some of the integration request fields. • The integration type is AWS service. • The AWS service is DynamoDB. • The HTTP method is POST. • The Action is PutItem. • The Execution role allowing API Gateway to put an item into the DynamoDB table is data-transformation-tutorial-console-APIGatewayRole. AWS CloudFormation created this role to allow API Gateway to have the minimal permissions for interacting with DynamoDB. Data transformations 547 Amazon API Gateway Developer Guide The name of the DynamoDB table has not been specified. You will specify the name in the following steps. 3. For Request body passthrough, select Never. This means that the API will reject data with Content-Types that do not have a mapping template. 4. Choose Mapping templates. 5. The Content type is set to application/json. This means a content types that are not application/json will be rejected by the API. For more information about the integration passthrough behaviors, see Method request behavior for payloads without mapping templates for REST APIs in API Gateway 6. Enter the following code into the text editor. { "TableName":"data-transformation-tutorial-console-ddb", "Item": { "id": { "N": $input.json("$.id") }, "type": { "S": $input.json("$.type") }, "price": { "N": $input.json("$.price") } } } This template specifies the table as data-transformation-tutorial-console-ddb and sets the items as id, type, and price. The items will come from the body of the POST method. You also can use a data model to help create a mapping template. For more information, see Request validation for REST APIs in API Gateway. 7. Choose Save to save your mapping template. Data transformations 548 Amazon API Gateway Developer Guide To add a method and integration response from the POST method The AWS CloudFormation created a blank method and integration response. You will edit this response to provide more information. For more information about how to edit responses, see Parameter mapping examples for REST APIs in API Gateway. 1. On the Integration response tab, for Default - Response, choose Edit. 2. Choose Mapping templates, and then choose Add mapping template. 3. 4. For Content-type, enter application/json. In the code editor, enter the following output mapping template to send an output message: { "message" : "Your response was recorded at $context.requestTime" } For more information about context variables, see Context variables for data transformations. 5. Choose Save to save your mapping template. Test the POST method Choose the Test tab. You might need to choose the right arrow button to show the tab. 1. In the request body, enter the following example. { "id": "4", "type" : "dog", "price": "321" } 2. Choose Test. The output should show your success message. You can open the DynamoDB console at https://console.aws.amazon.com/dynamodb/ to verify that the example item is in your table. To delete an AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select your AWS CloudFormation stack. Data transformations 549 Amazon API Gateway Developer Guide 3. Choose Delete and then confirm your choice. Set up data transformation using the AWS CLI In this tutorial, you will create an incomplete API and DynamoDB table using the following .zip file data-transformation-tutorial-cli.zip. This incomplete API has a /pets resource with a GET method integrated with the http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP endpoint. You will create a POST method to connect to a DynamoDB table and use mapping templates to input data into a DynamoDB table. • You will transform the output data according to the mapping template in the section called “Mapping template transformations”. • You will create a POST method to allow the user to POST pet information to a Amazon DynamoDB table using a mapping template. To create an AWS CloudFormation stack Download and unzip the app creation template for AWS CloudFormation. To complete the following tutorial, you need the AWS Command Line Interface (AWS CLI) version 2. For long commands, an escape character (\) is used to split a command over multiple lines. Note In Windows, some Bash CLI commands that you commonly use (such as zip) are not supported by the operating system's built-in terminals. To get a Windows-integrated version of Ubuntu and Bash, install the Windows Subsystem for Linux. Example CLI commands in this guide use Linux formatting. Commands which include inline JSON documents must be reformatted if you are using the Windows CLI. 1. Use the following command