id
stringlengths 8
78
| source
stringclasses 743
values | chunk_id
int64 1
5.05k
| text
stringlengths 593
49.7k
|
---|---|---|---|
apigateway-dg-152
|
apigateway-dg.pdf
| 152 |
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 to create the AWS CloudFormation stack. aws cloudformation create-stack --stack-name data-transformation-tutorial-cli --template-body file://data-transformation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM Data transformations 550 Amazon API Gateway Developer Guide 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 data-transformation-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 data-transformation-tutorial-cli --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}" The output values are the following: • ApiRole, which is the role name that allows API Gateway to put items in the DynamoDB table. For this tutorial, the role name is data-transformation-tutorial-cli- APIGatewayRole-ABCDEFG. • DDBTableName, which is the name of the DynamoDB table. For this tutorial, the table name is data-transformation-tutorial-cli-ddb • ResourceId, which is the ID for the pets resource where the GET and POST methods are exposed. For this tutorial, the Resource ID is efg456 • ApiId, which is the ID for the API. For this tutorial, the API ID is abc123. To test the GET method before data transformation • Use the following command to test the GET method. aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET The output of the test will show the following. [ { "id": 1, "type": "dog", Data transformations 551 Amazon API Gateway Developer Guide "price": 249.99 }, { "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 • Use the following command to update the integration response for the GET method. Replace the rest-api-id and resource-id with your values. Use the following command to create the integration response. aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --status-code 200 \ --selection-pattern "" \ --response-templates '{"application/json": "#set($inputRoot = $input.path(\"$ \"))\n[\n#foreach($elem in $inputRoot)\n {\n \"description\": \"Item $elem.id is a $elem.type\",\n \"askingPrice\": \"$elem.price\"\n }#if($foreach.hasNext),#end\n \n#end\n]"}' To test the GET method • Use the following command to test the GET method. aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ Data transformations 552 Amazon API Gateway --http-method GET \ Developer Guide 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 create a POST method 1. Use the following command to create a new method on the /pets resource. aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --authorization-type "NONE" \ This method will allow you to send pet information to the DynamoDB table that your created in the AWS CloudFormation stack. 2. Use the following command to create an AWS service integration on the POST method. aws apigateway put-integration --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --type AWS \ --integration-http-method POST \ --uri "arn:aws:apigateway:us-east-2:dynamodb:action/PutItem" \ --credentials arn:aws:iam::111122223333:role/data-transformation-tutorial-cli- APIGatewayRole-ABCDEFG \ Data transformations 553 Amazon API Gateway Developer Guide --request-templates '{"application/json":"{\"TableName\":\"data-transformation- tutorial-cli-ddb\",\"Item\":{\"id\":{\"N\":$input.json(\"$.id\")},\"type\":{\"S\": $input.json(\"$.type\")},\"price\":{\"N\":$input.json(\"$.price\")} }}"}' 3. Use the following command to create a method response for a successful call of the POST method. aws apigateway put-method-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200 4. Use the following command to create an integration response for the successful call of the POST method. aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200 \ --selection-pattern "" \ --response-templates '{"application/json": "{\"message\": \"Your response was recorded at $context.requestTime\"}"}' To test the POST method • Use the following command to test the POST method. aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --body '{\"id\": \"4\", \"type\": \"dog\", \"price\": \"321\"}' The output will show the successful message. To delete an AWS CloudFormation stack • Use the following command to delete your AWS CloudFormation resources. aws cloudformation delete-stack --stack-name data-transformation-tutorial-cli Data transformations 554 Amazon API Gateway Developer Guide Completed data transformation AWS CloudFormation template
|
apigateway-dg-153
|
apigateway-dg.pdf
| 153 |
abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200 \ --selection-pattern "" \ --response-templates '{"application/json": "{\"message\": \"Your response was recorded at $context.requestTime\"}"}' To test the POST method • Use the following command to test the POST method. aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --body '{\"id\": \"4\", \"type\": \"dog\", \"price\": \"321\"}' The output will show the successful message. To delete an AWS CloudFormation stack • Use the following command to delete your AWS CloudFormation resources. aws cloudformation delete-stack --stack-name data-transformation-tutorial-cli Data transformations 554 Amazon API Gateway Developer Guide Completed data transformation AWS CloudFormation template The following example is a completed AWS CloudFormation template, which creates an API and a DynamoDB table with 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 DynamoDB table using a mapping template. Example AWS CloudFormation template AWSTemplateFormatVersion: 2010-09-09 Description: A completed Amazon API Gateway REST API that uses non-proxy integration to POST to an Amazon DynamoDB table and non-proxy integration to GET transformed pets data. Parameters: StageName: Type: String Default: v1 Description: Name of API stage. Resources: DynamoDBTable: Type: 'AWS::DynamoDB::Table' Properties: TableName: !Sub data-transformation-tutorial-complete AttributeDefinitions: - AttributeName: id AttributeType: N KeySchema: - AttributeName: id KeyType: HASH ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 APIGatewayRole: Type: 'AWS::IAM::Role' Properties: AssumeRolePolicyDocument: Version: 2012-10-17 Statement: Data transformations 555 Amazon API Gateway Developer Guide - Action: - 'sts:AssumeRole' Effect: Allow Principal: Service: - apigateway.amazonaws.com Policies: - PolicyName: APIGatewayDynamoDBPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - 'dynamodb:PutItem' Resource: !GetAtt DynamoDBTable.Arn Api: Type: 'AWS::ApiGateway::RestApi' Properties: Name: data-transformation-complete-api ApiKeySourceType: HEADER PetsResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'pets' PetsMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref PetsResource HttpMethod: GET ApiKeyRequired: false AuthorizationType: NONE Integration: Type: HTTP Credentials: !GetAtt APIGatewayRole.Arn IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ PassthroughBehavior: WHEN_NO_TEMPLATES IntegrationResponses: - StatusCode: '200' ResponseTemplates: Data transformations 556 Amazon API Gateway Developer Guide application/json: "#set($inputRoot = $input.path(\"$ \"))\n[\n#foreach($elem in $inputRoot)\n {\n \"description\": \"Item $elem.id is a $elem.type\",\n \"askingPrice\": \"$elem.price\"\n }#if($foreach.hasNext),#end\n \n#end\n]" MethodResponses: - StatusCode: '200' PetsMethodPost: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref PetsResource HttpMethod: POST ApiKeyRequired: false AuthorizationType: NONE Integration: Type: AWS Credentials: !GetAtt APIGatewayRole.Arn IntegrationHttpMethod: POST Uri: arn:aws:apigateway:us-west-1:dynamodb:action/PutItem PassthroughBehavior: NEVER RequestTemplates: application/json: "{\"TableName\":\"data-transformation-tutorial-complete \",\"Item\":{\"id\":{\"N\":$input.json(\"$.id\")},\"type\":{\"S\":$input.json(\"$.type \")},\"price\":{\"N\":$input.json(\"$.price\")} }}" IntegrationResponses: - StatusCode: 200 ResponseTemplates: application/json: "{\"message\": \"Your response was recorded at $context.requestTime\"}" MethodResponses: - StatusCode: '200' ApiDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: - PetsMethodGet Properties: RestApiId: !Ref Api StageName: !Sub '${StageName}' Outputs: ApiId: Description: API ID for CLI commands Value: !Ref Api ResourceId: Data transformations 557 Amazon API Gateway Developer Guide Description: /pets resource ID for CLI commands Value: !Ref PetsResource ApiRole: Description: Role ID to allow API Gateway to put and scan items in DynamoDB table Value: !Ref APIGatewayRole DDBTableName: Description: DynamoDB table name Value: !Ref DynamoDBTable Examples using variables for mapping template transformations for API Gateway The following examples show how to use $context, input, and util variables in mapping templates. You can use a mock integration or a Lambda non-proxy integration that returns the input event back to API Gateway. For a list of all supported variables for data transformations, see the section called “Variables for data transformations”. Example 1: Pass multiple $context variables to the integration endpoint The following example shows a mapping template that maps incoming $context variables to backend variables with slightly different names in an integration request payload: { "stage" : "$context.stage", "request_id" : "$context.requestId", "api_id" : "$context.apiId", "resource_path" : "$context.resourcePath", "resource_id" : "$context.resourceId", "http_method" : "$context.httpMethod", "source_ip" : "$context.identity.sourceIp", "user-agent" : "$context.identity.userAgent", "account_id" : "$context.identity.accountId", "api_key" : "$context.identity.apiKey", "caller" : "$context.identity.caller", "user" : "$context.identity.user", "user_arn" : "$context.identity.userArn" } The output of this mapping template should look like the following: { stage: 'prod', request_id: 'abcdefg-000-000-0000-abcdefg', Data transformations 558 Amazon API Gateway Developer Guide api_id: 'abcd1234', resource_path: '/', resource_id: 'efg567', http_method: 'GET', source_ip: '192.0.2.1', user-agent: 'curl/7.84.0', account_id: '111122223333', api_key: 'MyTestKey', caller: 'ABCD-0000-12345', user: 'ABCD-0000-12345', user_arn: 'arn:aws:sts::111122223333:assumed-role/Admin/carlos-salazar' } One of the variables is an API key. This example assumes that the method requires an API key. Example 2: Pass all request parameters to the integration endpoint via a JSON payload The following example passes all request parameters, including path, querystring, and header parameters, through to the integration endpoint via a JSON payload: #set($allParams = $input.params()) { "params" : { #foreach($type in $allParams.keySet()) #set($params = $allParams.get($type)) "$type" : { #foreach($paramName in $params.keySet()) "$paramName" : "$util.escapeJavaScript($params.get($paramName))" #if($foreach.hasNext),#end #end } #if($foreach.hasNext),#end #end } } If a request has the following input parameters: • A path parameter named myparam • Query string parameters querystring1=value1,value2 • Headers "header1" : "value1". Data transformations 559 Amazon API Gateway Developer Guide The output of this mapping template should
|
apigateway-dg-154
|
apigateway-dg.pdf
| 154 |
request parameters to the integration endpoint via a JSON payload The following example passes all request parameters, including path, querystring, and header parameters, through to the integration endpoint via a JSON payload: #set($allParams = $input.params()) { "params" : { #foreach($type in $allParams.keySet()) #set($params = $allParams.get($type)) "$type" : { #foreach($paramName in $params.keySet()) "$paramName" : "$util.escapeJavaScript($params.get($paramName))" #if($foreach.hasNext),#end #end } #if($foreach.hasNext),#end #end } } If a request has the following input parameters: • A path parameter named myparam • Query string parameters querystring1=value1,value2 • Headers "header1" : "value1". Data transformations 559 Amazon API Gateway Developer Guide The output of this mapping template should look like the following: {"params":{"path":{"example2":"myparamm"},"querystring": {"querystring1":"value1,value2"},"header":{"header1":"value1"}}} Example 3: Pass a subsection of a method request to the integration endpoint The following example uses the input parameter name to retrieve only the name parameter and the input parameter input.json('$') to retrieve the entire body of the method request: { "name" : "$input.params('name')", "body" : $input.json('$') } For a request that includes the query string parameters name=Bella&type=dog and the following body: { "Price" : "249.99", "Age": "6" } The output of this mapping template should look like the following: { "name" : "Bella", "body" : {"Price":"249.99","Age":"6"} } This mapping template removes the query string parameter type=dog. If the JSON input contains unescaped characters that cannot be parsed by JavaScript, API Gateway might return a 400 response. Apply $util.escapeJavaScript($input.json('$')) to ensure the JSON input can be parsed properly. The previous example with $util.escapeJavaScript($input.json('$')) applied is as follows: { Data transformations 560 Amazon API Gateway Developer Guide "name" : "$input.params('name')", "body" : "$util.escapeJavaScript($input.json('$'))" } In this case, the output of this mapping template should look like the following: { "name" : "Bella", "body": {"Price":"249.99","Age":"6"} } Example 4: Use JSONPath expression to pass a subsection of a method request to the integration endpoint The following example uses the JSONPath expressions to retrieve only the input parameter name and the Age from the request body: { "name" : "$input.params('name')", "body" : $input.json('$.Age') } For a request that includes the query string parameters name=Bella&type=dog and the following body: { "Price" : "249.99", "Age": "6" } The output of this mapping template should look like the following: { "name" : "Bella", "body" : "6" } This mapping template removes the query string parameter type=dog and the Price field from the body. Data transformations 561 Amazon API Gateway Developer Guide If a method request payload contains unescaped characters that cannot be parsed by JavaScript, API Gateway might return a 400 response. Apply $util.escapeJavaScript() to ensure the JSON input can be parsed properly. The previous example with $util.escapeJavaScript($input.json('$.Age')) applied is as follows: { "name" : "$input.params('name')", "body" : "$util.escapeJavaScript($input.json('$.Age'))" } In this case, the output of this mapping template should look like the following: { "name" : "Bella", "body": "\"6\"" } Example 5: Use a JSONPath expression to pass information about a method request to the integration endpoint The following example uses $input.params(), $input.path(), and $input.json() to send information about a method request to the integration endpoint. This mapping template uses the size() method to provide the number of elements in a list. { "id" : "$input.params('id')", "count" : "$input.path('$.things').size()", "things" : $input.json('$.things') } For a request that includes the path parameter 123 and the following body: { "things": { "1": {}, "2": {}, "3": {} } } Data transformations 562 Amazon API Gateway Developer Guide The output of this mapping template should look like the following: {"id":"123","count":"3","things":{"1":{},"2":{},"3":{}}} If a method request payload contains unescaped characters that cannot be parsed by JavaScript, API Gateway might return a 400 response. Apply $util.escapeJavaScript() to ensure the JSON input can be parsed properly. The previous example with $util.escapeJavaScript($input.json('$.things')) applied is as follows: { "id" : "$input.params('id')", "count" : "$input.path('$.things').size()", "things" : "$util.escapeJavaScript($input.json('$.things'))" } The output of this mapping template should look like the following: {"id":"123","count":"3","things":"{\"1\":{},\"2\":{},\"3\":{}}"} Variables for data transformations for API Gateway When you create a parameter mapping, you can use context variables as your data source. When you create mapping template transformations, you can use context variables, input, and util variables in scripts you write in Velocity Template Language (VTL). For example mapping templates that use these reference variables, see the section called “Examples using variables for mapping template transformations”. For a list of reference variables for access logging, see the section called “Variables for access logging for API Gateway”. Context variables for data transformations You can use the following case-sensitive $context variables for data transformations. Parameter Description $context.accountId The API owner's AWS account ID. Data transformations 563 Amazon API Gateway Parameter Description Developer Guide $context.apiId The identifier API Gateway assigns to your API. $context.authorizer.claims. property $context.authorizer.principalId A property of the claims returned from the Amazon Cognito user pool after the method caller is successfully authenticated. For more information, see the section called “Use Amazon Cognito user pool as authorizer for a
|
apigateway-dg-155
|
apigateway-dg.pdf
| 155 |
list of reference variables for access logging, see the section called “Variables for access logging for API Gateway”. Context variables for data transformations You can use the following case-sensitive $context variables for data transformations. Parameter Description $context.accountId The API owner's AWS account ID. Data transformations 563 Amazon API Gateway Parameter Description Developer Guide $context.apiId The identifier API Gateway assigns to your API. $context.authorizer.claims. property $context.authorizer.principalId A property of the claims returned from the Amazon Cognito user pool after the method caller is successfully authenticated. For more information, see the section called “Use Amazon Cognito user pool as authorizer for a REST API”. Note Calling $context.authorize r.claims returns null. The principal user identification associated with the token sent by the client and returned from an API Gateway Lambda authorizer (formerly known as a custom authorizer). For more information, see the section called “Use Lambda authorizers”. Data transformations 564 Amazon API Gateway Parameter Description Developer Guide $context.authorizer. property The stringified value of the specified key-value pair of the context map returned from an API Gateway Lambda authorizer function. For example, if the authorizer returns the following context map: "context" : { "key": "value", "numKey": 1, "boolKey": true } Calling $context.authorizer.key returns the "value" string, calling $context.authorizer.numKey the "1" string, and calling $context. returns the authorizer.boolKey "true" string. returns For property, the only supported special character is the underscore (_) character. For more information, see the section called “Use Lambda authorizers”. $context.awsEndpointRequestId The AWS endpoint's request ID. $context.deploymentId The ID of the API deployment. $context.domainName $context.domainPrefix The full domain name used to invoke the API. This should be the same as the incoming Host header. The first label of the $context.domainNam e . Data transformations 565 Amazon API Gateway Parameter $context.error.message $context.error.messageString $context.error.responseType Developer Guide Description A string containing an API Gateway error message. This variable can only be used for simple variable substitution in a GatewayRe sponse body-mapping template, which is not processed by the Velocity Template Language engine, and in access logging. For more information, see the section called “Metrics” and the section called “Setting up gateway responses to customize error responses”. The quoted value of $context.error.mes sage , namely "$context.error.me ssage" . A type of GatewayResponse. This variable can only be used for simple variable substitut ion in a GatewayResponse body-mapping template, which is not processed by the Velocity Template Language engine, and in access logging. For more information, see the section called “Metrics” and the section called “Setting up gateway responses to customize error responses”. $context.error.validationEr rorString A string containing a detailed validation error message. $context.extendedRequestId $context.httpMethod The extended ID that API Gateway generates and assigns to the API request. The extended request ID contains useful information for debugging and troubleshooting. The HTTP method used. Valid values include: DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT. Data transformations 566 Amazon API Gateway Parameter $context.identity.accountId $context.identity.apiKey $context.identity.apiKeyId $context.identity.caller $context.identity.cognitoAu thenticationProvider Developer Guide Description The AWS account ID associated with the request. For API methods that require an API key, this variable is the API key associated with the method request. For methods that don't require an API key, this variable is null. For more information, see the section called “Usage plans”. The API key ID associated with an API request that requires an API key. The principal identifier of the caller that signed the request. Supported for resources that use IAM authorization. A comma-separated list of all the Amazon Cognito authentication providers used by the caller making the request. Available only if the request was signed with Amazon Cognito credentials. For example, for an identity from an Amazon Cognito user pool, cognito-idp. region.amazonaws.com/ user_pool _id ,cognito-idp. region.amazonaw s.com/ user_pool_id :CognitoS ignIn: token subject claim For information about the available Amazon Cognito authentication providers, see Using Federated Identities in the Amazon Cognito Developer Guide. Data transformations 567 Amazon API Gateway Parameter $context.identity.cognitoAu thenticationType $context.identity.cognitoId entityId $context.identity.cognitoId entityPoolId Developer Guide Description The Amazon Cognito authentication type of the caller making the request. Available only if the request was signed with Amazon Cognito credentials. Possible values include authenticated for authenticated identities and unauthenticated for unauthenticated identities. The Amazon Cognito identity ID of the caller making the request. Available only if the request was signed with Amazon Cognito credentials. The Amazon Cognito identity pool ID of the caller making the request. Available only if the request was signed with Amazon Cognito credentials. $context.identity.principalOrgId The AWS organization ID. $context.identity.sourceIp $context.identity.clientCer t.clientCertPem The source IP address of the immediate TCP connection making the request to the API Gateway endpoint. The PEM-encoded client certificate that the client presented during mutual TLS authentic ation. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. Data transformations 568 Amazon API Gateway
|
apigateway-dg-156
|
apigateway-dg.pdf
| 156 |
signed with Amazon Cognito credentials. The Amazon Cognito identity pool ID of the caller making the request. Available only if the request was signed with Amazon Cognito credentials. $context.identity.principalOrgId The AWS organization ID. $context.identity.sourceIp $context.identity.clientCer t.clientCertPem The source IP address of the immediate TCP connection making the request to the API Gateway endpoint. The PEM-encoded client certificate that the client presented during mutual TLS authentic ation. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. Data transformations 568 Amazon API Gateway Parameter $context.identity.clientCer t.subjectDN $context.identity.clientCer t.issuerDN $context.identity.clientCer t.serialNumber $context.identity.clientCer t.validity.notBefore $context.identity.clientCer t.validity.notAfter $context.identity.vpcId Developer Guide Description The distinguished name of the subject of the certificate that a client presents. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. The distinguished name of the issuer of the certificate that a client presents. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. The serial number of the certificate. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. The date before which the certificate is invalid. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. The date after which the certificate is invalid. Present when a client accesses an API by using a custom domain name that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails. The VPC ID of the VPC making the request to the API Gateway endpoint. Data transformations 569 Amazon API Gateway Parameter $context.identity.vpceId $context.identity.user Developer Guide Description The VPC endpoint ID of the VPC endpoint making the request to the API Gateway endpoint. Present only when you have a private API. The principal identifier of the user that will be authorized against resource access. Supported for resources that use IAM authorization. $context.identity.userAgent The User-Agent header of the API caller. $context.identity.userArn $context.isCanaryRequest $context.path The Amazon Resource Name (ARN) of the effective user identified after authentication. For more information, see https://docs.aws. amazon.com/IAM/latest/UserGuide/id_users. html. Returns true if the request was directed to the canary and false if the request was not directed to the canary. Present only when you have a canary enabled. The request path. For example, for a non- proxy request URL of https://{rest- api-id}.execute-api.{region}.am azonaws.com/{stage}/root/child the $context.path value is /{stage}/ , root/child . Data transformations 570 Amazon API Gateway Parameter Description Developer Guide $context.protocol The request protocol, for example, HTTP/1.1. $context.requestId $context.requestOverride.he ader. header_name $context.requestOverride.pa th. path_name Note API Gateway APIs can accept HTTP/2 requests, but API Gateway sends requests to backend integrations using HTTP/1.1. As a result, the request protocol is logged as HTTP/1.1 even if a client sends a request that uses HTTP/2. An ID for the request. Clients can override this request ID. Use $context.extendedR equestId for a unique request ID that API Gateway generates. The request header override. If this parameter is defined, it contains the headers to be used instead of the HTTP Headers that are defined in the Integration Request pane. For more information, see Override your API's request and response parameters and status codes for REST APIs in API Gateway. The request path override. If this parameter is defined, it contains the request path to be used instead of the URL Path Parameters that are defined in the Integration Request pane. For more information, see Override your API's request and response parameters and status codes for REST APIs in API Gateway. Data transformations 571 Amazon API Gateway Parameter $context.requestOverride.qu erystring. querystring_name $context.responseOverride.h eader. header_name $context.responseOverride.status Developer Guide Description The request query string override. If this parameter is defined, it contains the request query strings to be used instead of the URL Query String Parameters that are defined in the Integration Request pane. For more information, see Override your API's request and response parameters and status codes for REST APIs in API Gateway. The response header override. If this parameter is defined, it contains the header to be returned instead of the Response header that is defined as the Default mapping in the Integration Response pane. For more information, see Override your API's request and response parameters and status codes for REST APIs in API Gateway. The response status code override. If this parameter is defined, it contains the status code to be returned instead of the Method response status that is defined as the Default mapping in the Integration Response pane.
|
apigateway-dg-157
|
apigateway-dg.pdf
| 157 |
response parameters and status codes for REST APIs in API Gateway. The response header override. If this parameter is defined, it contains the header to be returned instead of the Response header that is defined as the Default mapping in the Integration Response pane. For more information, see Override your API's request and response parameters and status codes for REST APIs in API Gateway. The response status code override. If this parameter is defined, it contains the status code to be returned instead of the Method response status that is defined as the Default mapping in the Integration Response pane. For more information, see Override your API's request and response parameters and status codes for REST APIs in API Gateway. $context.requestTime The CLF-formatted request time (dd/MMM/yy $context.requestTimeEpoch yy:HH:mm:ss +-hhmm ). The Epoch-formatted request time, in milliseconds. $context.resourceId The identifier that API Gateway assigns to your resource. Data transformations 572 Amazon API Gateway Parameter Description Developer Guide $context.resourcePath The path to your resource. For example, for the non-proxy request URI of https:// {rest-api-id}.execute-api.{r egion}.amazonaws.com/{stage}/ root/child , The $context.resourceP ath value is /root/child . For more information, see Tutorial: Create a REST API with an HTTP non-proxy integration. $context.stage The deployment stage of the API request (for example, Beta or Prod). $context.wafResponseCode The response received from AWS WAF: WAF_ALLOW or WAF_BLOCK . Will not be set if the stage is not associated with a web ACL. For more information, see the section called “AWS WAF”. The complete ARN of the web ACL that is used to decide whether to allow or block the request. Will not be set if the stage is not associated with a web ACL. For more informati on, see the section called “AWS WAF”. $context.webaclArn Input variables You can use the following case-sensitive $input variables to refer to the method request payload and method request parameters. The following functions are available: Variable and function Description $input.body Returns the raw request payload as a string. You can use $input.body to preserve entire floating point numbers, such as 10.00. Data transformations 573 Amazon API Gateway Developer Guide Variable and function Description $input.json(x) This function evaluates a JSONPath expression and returns the results as a JSON string. $input.params() $input.params(x) For example, $input.json('$.pets') returns a JSON string representing the pets structure. For more information about JSONPath, see JSONPath or JSONPath for Java. Returns a map of all the request parameter s. We recommend that you use $util.esc to sanitize the result to apeJavaScript avoid a potential injection attack. For full control of request sanitization, use a proxy integration without a template and handle request sanitization in your integration. Returns the value of a method request parameter from the path, query string, or header value (searched in that order), given a parameter name string x. We recommend that you use $util.escapeJavaScript to sanitize the parameter to avoid a potential injection attack. For full control of parameter sanitization, use a proxy integration without a template and handle request sanitization in your integration. Data transformations 574 Amazon API Gateway Developer Guide Variable and function Description $input.path(x) Takes a JSONPath expression string (x) and returns a JSON object representation of the result. This allows you to access and manipulat e elements of the payload natively in Apache Velocity Template Language (VTL). For example, if the expression $input.pa th('$.pets') returns an object like this: [ { "id": 1, "type": "dog", "price": 249.99 }, { "id": 2, "type": "cat", "price": 124.99 }, { "id": 3, "type": "fish", "price": 0.99 } ] $input.path('$.pets').size() would return "3". For more information about JSONPath, see JSONPath or JSONPath for Java. Stage variables You can use the following stage variables as placeholders for ARNs and URLs in method integrations. For more information, see the section called “Use stage variables”. Data transformations 575 Amazon API Gateway Syntax Developer Guide Description $stageVariables. variable_name , $stageVariables[' variable_name '], or ${stageVariables[' variable_ variable_name represents a stage variable name. name ']} Util variables You can use the following case-sensitive $util variables to use utility functions for mapping templates. Unless otherwise specified, the default character set is UTF-8. Function Description $util.escapeJavaScript() Escapes the characters in a string using JavaScript string rules. Note This function will turn any regular single quotes (') into escaped ones (\'). However, the escaped single quotes are not valid in JSON. Thus, when the output from this function is used in a JSON property, you must turn any escaped single quotes (\') back to regular single quotes ('). This is shown in the following example: "input" : "$util.escapeJavaS cript( data).replaceAll("\\'" ,"'")" $util.parseJson() Takes "stringified" JSON and returns an object representation of the result. You can use the result from this function to access and Data transformations 576 Amazon API Gateway Function $util.urlEncode() $util.urlDecode() $util.base64Encode() $util.base64Decode() Developer Guide Description manipulate elements of the payload natively in
|
apigateway-dg-158
|
apigateway-dg.pdf
| 158 |
quotes (') into escaped ones (\'). However, the escaped single quotes are not valid in JSON. Thus, when the output from this function is used in a JSON property, you must turn any escaped single quotes (\') back to regular single quotes ('). This is shown in the following example: "input" : "$util.escapeJavaS cript( data).replaceAll("\\'" ,"'")" $util.parseJson() Takes "stringified" JSON and returns an object representation of the result. You can use the result from this function to access and Data transformations 576 Amazon API Gateway Function $util.urlEncode() $util.urlDecode() $util.base64Encode() $util.base64Decode() Developer Guide Description manipulate elements of the payload natively in Apache Velocity Template Language (VTL). For example, if you have the following payload: {"errorMessage":"{\"key1\":\"var1\", \"key2\":{\"arr\":[1,2,3]}}"} and use the following mapping template #set ($errorMessageObj = $util.par seJson($input.path('$.error Message'))) { "errorMessageObjKey2ArrVal" : $errorMessageObj.key2.arr[0] } You will get the following output: { "errorMessageObjKey2ArrVal" : 1 } Converts a string into "application/x-www- form-urlencoded" format. Decodes an "application/x-www-form-url encoded" string. Encodes the data into a base64-encoded string. Decodes the data from a base64-encoded string. Data transformations 577 Amazon API Gateway Developer Guide Gateway responses for REST APIs in API Gateway A gateway response is identified by a response type that is defined by API Gateway. The response consists of an HTTP status code, a set of additional headers that are specified by parameter mappings, and a payload that is generated by a non-VTL mapping template. In the API Gateway REST API, a gateway response is represented by the GatewayResponse. In OpenAPI, a GatewayResponse instance is described by the x-amazon-apigateway-gateway- responses.gatewayResponse extension. To enable a gateway response, you set up a gateway response for a supported response type at the API level. Whenever API Gateway returns a response of this type, the header mappings and payload mapping templates defined in the gateway response are applied to return the mapped results to the API caller. In the following section, we show how to set up gateway responses by using the API Gateway console and the API Gateway REST API. Setting up gateway responses to customize error responses If API Gateway fails to process an incoming request, it returns to the client an error response without forwarding the request to the integration backend. By default, the error response contains a short descriptive error message. For example, if you attempt to call an operation on an undefined API resource, you receive an error response with the { "message": "Missing Authentication Token" } message. If you are new to API Gateway, you may find it difficult to understand what actually went wrong. For some of the error responses, API Gateway allows customization by API developers to return the responses in different formats. For the Missing Authentication Token example, you can add a hint to the original response payload with the possible cause, as in this example: {"message":"Missing Authentication Token", "hint":"The HTTP method or resources may not be supported."}. When your API mediates between an external exchange and the AWS Cloud, you use VTL mapping templates for integration request or integration response to map the payload from one format to another. However, the VTL mapping templates work only for valid requests with successful responses. For invalid requests, API Gateway bypasses the integration altogether and returns an error response. You must use the customization to render the error responses in an exchange-compliant Gateway responses 578 Amazon API Gateway Developer Guide format. Here, the customization is rendered in a non-VTL mapping template supporting only simple variable substitutions. Generalizing the API Gateway-generated error response to any responses generated by API Gateway, we refer to them as gateway responses. This distinguishes API Gateway-generated responses from the integration responses. A gateway response mapping template can access $context variable values and $stageVariables property values, as well as method request parameters, in the form of method.request.param-position.param-name. For more information about $context variables, see Context variables for data transformations. For more information about $stageVariables, see Stage variables. For more information about method request parameters, see the section called “Input variables”. Topics • Set up a gateway response for a REST API using the API Gateway console • Set up a gateway response using the API Gateway REST API • Set up gateway response customization in OpenAPI • Gateway response types for API Gateway Set up a gateway response for a REST API using the API Gateway console The following example shows how to set up a gateway response for a REST API using the API Gateway console To customize a gateway response using the API Gateway console 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 Gateway responses. 4. Choose a response type, and then choose Edit. In this walkthrough, we use Missing authentication token as an example. 5. You can change the API Gateway-generated Status
|
apigateway-dg-159
|
apigateway-dg.pdf
| 159 |
types for API Gateway Set up a gateway response for a REST API using the API Gateway console The following example shows how to set up a gateway response for a REST API using the API Gateway console To customize a gateway response using the API Gateway console 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 Gateway responses. 4. Choose a response type, and then choose Edit. In this walkthrough, we use Missing authentication token as an example. 5. You can change the API Gateway-generated Status code to return a different status code that meets your API's requirements. In this example, the customization changes the status code from the default (403) to 404 because this error message occurs when a client calls an unsupported or invalid resource that can be thought of as not found. 6. To return custom headers, choose Add response header under Response headers. For illustration purposes, we add the following custom headers: Gateway responses 579 Amazon API Gateway Developer Guide Access-Control-Allow-Origin:'a.b.c' x-request-id:method.request.header.x-amzn-RequestId x-request-path:method.request.path.petId x-request-query:method.request.querystring.q In the preceding header mappings, a static domain name ('a.b.c') is mapped to the Allow- Control-Allow-Origin header to allow CORS access to the API; the input request header of x-amzn-RequestId is mapped to request-id in the response; the petId path variable of the incoming request is mapped to the request-path header in the response; and the q query parameter of the original request is mapped to the request-query header of the response. 7. Under Response templates, keep application/json for Content Type and enter the following body mapping template in the Template body editor: { "message":"$context.error.messageString", "type": "$context.error.responseType", "statusCode": "'404'", "stage": "$context.stage", "resourcePath": "$context.resourcePath", "stageVariables.a": "$stageVariables.a" } This example shows how to map $context and $stageVariables properties to properties of the gateway response body. 8. Choose Save changes. 9. Deploy the API to a new or existing stage. Test your gateway response by calling the following CURL command, assuming the corresponding API method's invoke URL is https://o81lxisefl.execute-api.us- east-1.amazonaws.com/custErr/pets/{petId}: curl -v -H 'x-amzn-RequestId:123344566' https://o81lxisefl.execute-api.us- east-1.amazonaws.com/custErr/pets/5/type?q=1 Because the extra query string parameter q=1 isn't compatible with the API, an error is returned from the specified gateway response. You should get a gateway response similar to the following: Gateway responses 580 Amazon API Gateway Developer Guide > GET /custErr/pets/5?q=1 HTTP/1.1 Host: o81lxisefl.execute-api.us-east-1.amazonaws.com User-Agent: curl/7.51.0 Accept: */* HTTP/1.1 404 Not Found Content-Type: application/json Content-Length: 334 Connection: keep-alive Date: Tue, 02 May 2017 03:15:47 GMT x-amzn-RequestId: 123344566 Access-Control-Allow-Origin: a.b.c x-amzn-ErrorType: MissingAuthenticationTokenException header-1: static x-request-query: 1 x-request-path: 5 X-Cache: Error from cloudfront Via: 1.1 441811a054e8d055b893175754efd0c3.cloudfront.net (CloudFront) X-Amz-Cf-Id: nNDR-fX4csbRoAgtQJ16u0rTDz9FZWT-Mk93KgoxnfzDlTUh3flmzA== { "message":"Missing Authentication Token", "type": MISSING_AUTHENTICATION_TOKEN, "statusCode": '404', "stage": custErr, "resourcePath": /pets/{petId}, "stageVariables.a": a } The preceding example assumes that the API backend is Pet Store and the API has a stage variable, a, defined. Set up a gateway response using the API Gateway REST API Before customizing a gateway response using the API Gateway REST API, you must have already created an API and have obtained its identifier. To retrieve the API identifier, you can follow restapi:gateway-responses link relation and examine the result. Gateway responses 581 Amazon API Gateway Developer Guide To customize a gateway response using the API Gateway REST API 1. To overwrite an entire GatewayResponse instance, call the gatewayresponse:put action. Specify a desired responseType in the URL path parameter, and supply in the request payload the statusCode, responseParameters, and responseTemplates mappings. 2. To update part of a GatewayResponse instance, call the gatewayresponse:update action. Specify a desired responseType in the URL path parameter, and supply in the request payload the individual GatewayResponse properties you want—for example, the responseParameters or the responseTemplates mapping. Set up gateway response customization in OpenAPI You can use the x-amazon-apigateway-gateway-responses extension at the API root level to customize gateway responses in OpenAPI. The following OpenAPI definition shows an example for customizing the GatewayResponse of the MISSING_AUTHENTICATION_TOKEN type. "x-amazon-apigateway-gateway-responses": { "MISSING_AUTHENTICATION_TOKEN": { "statusCode": 404, "responseParameters": { "gatewayresponse.header.x-request-path": "method.input.params.petId", "gatewayresponse.header.x-request-query": "method.input.params.q", "gatewayresponse.header.Access-Control-Allow-Origin": "'a.b.c'", "gatewayresponse.header.x-request-header": "method.input.params.Accept" }, "responseTemplates": { "application/json": "{\n \"message\": $context.error.messageString,\n \"type\": \"$context.error.responseType\",\n \"stage\": \"$context.stage \",\n \"resourcePath\": \"$context.resourcePath\",\n \"stageVariables.a\": \"$stageVariables.a\",\n \"statusCode\": \"'404'\"\n}" } } In this example, the customization changes the status code from the default (403) to 404. It also adds to the gateway response four header parameters and one body mapping template for the application/json media type. Gateway response types for API Gateway API Gateway exposes the following gateway responses for customization by API developers. Gateway responses 582 Amazon API Gateway Developer Guide Gateway response type Default status code Description ACCESS_DENIED 403 API_CONFIGURATION_ 500 ERROR AUTHORIZER_CONFIGU 500 RATION_ERROR AUTHORIZER_FAILURE 500 The gateway response for authorization failure—f or example, when access is denied by a custom or Amazon Cognito authorizer. If the response type is unspecifi ed, this response defaults to the DEFAULT_4XX type. The gateway response for an invalid
|
apigateway-dg-160
|
apigateway-dg.pdf
| 160 |
adds to the gateway response four header parameters and one body mapping template for the application/json media type. Gateway response types for API Gateway API Gateway exposes the following gateway responses for customization by API developers. Gateway responses 582 Amazon API Gateway Developer Guide Gateway response type Default status code Description ACCESS_DENIED 403 API_CONFIGURATION_ 500 ERROR AUTHORIZER_CONFIGU 500 RATION_ERROR AUTHORIZER_FAILURE 500 The gateway response for authorization failure—f or example, when access is denied by a custom or Amazon Cognito authorizer. If the response type is unspecifi ed, this response defaults to the DEFAULT_4XX type. The gateway response for an invalid API configuration —including when an invalid endpoint address is submitted , when base64 decoding fails on binary data when binary support is enacted, or when integration response mapping can't match any template and no default template is configured. If the response type is unspecified, this response defaults to the DEFAULT_5XX type. The gateway response for failing to connect to a custom or Amazon Cognito authorize r. If the response type is unspecified, this response defaults to the DEFAULT_5 XX type. The gateway response when a custom or Amazon Cognito authorizer failed to authentic Gateway responses 583 Amazon API Gateway Developer Guide Gateway response type Default status code Description BAD_REQUEST_PARAME 400 TERS BAD_REQUEST_BODY 400 ate the caller. If the response type is unspecified, this response defaults to the DEFAULT_5XX type. The gateway response when the request parameter cannot be validated according to an enabled request validator. If the response type is unspecifi ed, this response defaults to the DEFAULT_4XX type. The gateway response when the request body cannot be validated according to an enabled request validator. If the response type is unspecifi ed, this response defaults to the DEFAULT_4XX type. Gateway responses 584 Amazon API Gateway Developer Guide Gateway response type Default status code Description DEFAULT_4XX Null DEFAULT_5XX Null The default gateway response for an unspecified response type with the status code of 4XX. Changing the status code of this fallback gateway response changes the status codes of all other 4XX responses to the new value. Resetting this status code to null reverts the status codes of all other 4XX responses to their original values. Note AWS WAF custom responses take precedence over custom gateway responses. The default gateway response for an unspecified response type with a status code of 5XX. Changing the status code of this fallback gateway response changes the status codes of all other 5XX responses to the new value. Resetting this status code to null reverts the status codes of all other 5XX responses to their original values. Gateway responses 585 Amazon API Gateway Developer Guide Gateway response type Default status code Description EXPIRED_TOKEN 403 INTEGRATION_FAILURE 504 INTEGRATION_TIMEOUT 504 INVALID_API_KEY 403 INVALID_SIGNATURE 403 The gateway response for an AWS authentication token expired error. If the response type is unspecified, this response defaults to the DEFAULT_4XX type. The gateway response for an integration failed error. If the response type is unspecified, this response defaults to the DEFAULT_5XX type. The gateway response for an integration timed out error. If the response type is unspecifi ed, this response defaults to the DEFAULT_5XX type. The gateway response for an invalid API key submitted for a method requiring an API key. If the response type is unspecified, this response defaults to the DEFAULT_4 XX type. The gateway response for an invalid AWS signature error. If the response type is unspecifi ed, this response defaults to the DEFAULT_4XX type. Gateway responses 586 Amazon API Gateway Developer Guide Gateway response type Default status code Description MISSING_AUTHENTICA 403 TION_TOKEN QUOTA_EXCEEDED 429 REQUEST_TOO_LARGE 413 RESOURCE_NOT_FOUND 404 The gateway response for a missing authentication token error, including the cases when the client attempts to invoke an unsupported API method or resource. If the response type is unspecified, this response defaults to the DEFAULT_4XX type. The gateway response for the usage plan quota exceeded error. If the response type is unspecified, this response defaults to the DEFAULT_4 XX type. The gateway response for the request too large error. If the response type is unspecifi ed, this response defaults to: HTTP content length exceeded 10485760 bytes. The gateway response when API Gateway cannot find the specified resource after an API request passes authentic ation and authorization, except for API key authentic ation and authorization. If the response type is unspecified, this response defaults to the DEFAULT_4XX type. Gateway responses 587 Amazon API Gateway Developer Guide Gateway response type Default status code Description THROTTLED 429 UNAUTHORIZED 401 UNSUPPORTED_MEDIA_ 415 TYPE WAF_FILTERED 403 The gateway response when usage plan-, method-, stage-, or account-level throttlin g limits exceeded. If the response type is unspecified, this response defaults to the DEFAULT_4XX type. The gateway response when the custom or Amazon Cognito authorizer failed to authenticate the caller. The gateway response when a payload
|
apigateway-dg-161
|
apigateway-dg.pdf
| 161 |
API request passes authentic ation and authorization, except for API key authentic ation and authorization. If the response type is unspecified, this response defaults to the DEFAULT_4XX type. Gateway responses 587 Amazon API Gateway Developer Guide Gateway response type Default status code Description THROTTLED 429 UNAUTHORIZED 401 UNSUPPORTED_MEDIA_ 415 TYPE WAF_FILTERED 403 The gateway response when usage plan-, method-, stage-, or account-level throttlin g limits exceeded. If the response type is unspecified, this response defaults to the DEFAULT_4XX type. The gateway response when the custom or Amazon Cognito authorizer failed to authenticate the caller. The gateway response when a payload is of an unsupported media type, if strict passthrou gh behavior is enabled. If the response type is unspecified, this response defaults to the DEFAULT_4XX type. The gateway response when a request is blocked by AWS WAF. If the response type is unspecified, this response defaults to the DEFAULT_4 XX type. Note AWS WAF custom responses take precedence over custom gateway responses. Gateway responses 588 Amazon API Gateway Developer Guide CORS for REST APIs in API Gateway Cross-origin resource sharing (CORS) is a browser security feature that restricts cross-origin HTTP requests that are initiated from scripts running in the browser. For more information, see What is CORS?. Determining whether to enable CORS support A cross-origin HTTP request is one that is made to: • A different domain (for example, from example.com to amazondomains.com) • A different subdomain (for example, from example.com to petstore.example.com) • A different port (for example, from example.com to example.com:10777) • A different protocol (for example, from https://example.com to http://example.com) If you cannot access your API and receive an error message that contains Cross-Origin Request Blocked, you might need to enable CORS. Cross-origin HTTP requests can be divided into two types: simple requests and non-simple requests. Enabling CORS for a simple request An HTTP request is simple if all of the following conditions are true: • It is issued against an API resource that allows only GET, HEAD, and POST requests. • If it is a POST method request, it must include an Origin header. • The request payload content type is text/plain, multipart/form-data, or application/ x-www-form-urlencoded. • The request does not contain custom headers. • Any additional requirements that are listed in the Mozilla CORS documentation for simple requests. For simple cross-origin POST method requests, the response from your resource needs to include the header Access-Control-Allow-Origin: '*' or Access-Control-Allow- Origin:'origin'. All other cross-origin HTTP requests are non-simple requests. CORS 589 Amazon API Gateway Developer Guide Enabling CORS for a non-simple request If your API's resources receive non-simple requests, you must enable additional CORS support depending on your integration type. Enabling CORS for non-proxy integrations For these integrations, the CORS protocol requires the browser to send a preflight request to the server and wait for approval (or a request for credentials) from the server before sending the actual request. You must configure your API to send an appropriate response to the preflight request. To create a preflight response: 1. Create an OPTIONS method with a mock integration. 2. Add the following response headers to the 200 method response: • Access-Control-Allow-Headers • Access-Control-Allow-Methods • Access-Control-Allow-Origin 3. Set the integration passthrough behavior to NEVER. In this case, the method request of an unmapped content type will be rejected with an HTTP 415 Unsupported Media Type response. For more information, see Method request behavior for payloads without mapping templates for REST APIs in API Gateway. 4. Enter values for the response headers. To allow all origins, all methods, and common headers, use the following header values: • Access-Control-Allow-Headers: 'Content-Type,X-Amz- Date,Authorization,X-Api-Key,X-Amz-Security-Token' • Access-Control-Allow-Methods: 'DELETE,GET,HEAD,OPTIONS,PUT,POST,PATCH' • Access-Control-Allow-Origin: '*' After creating the preflight request, you must return the Access-Control-Allow-Origin: '*' or Access-Control-Allow-Origin:'origin' header for all CORS-enabled methods for at least all 200 responses. CORS 590 Amazon API Gateway Developer Guide Enabling CORS for non-proxy integrations using the AWS Management Console You can use the AWS Management Console to enable CORS. API Gateway creates an OPTIONS method and adds the Access-Control-Allow-Origin header to your existing method integration responses. This doesn’t always work, and sometimes you need to manually modify the integration response to return the Access-Control-Allow-Origin header for all CORS- enabled methods for at least all 200 responses. If you have binary media types set to */* for your API, when API Gateway creates an OPTIONS method, change the contentHandling to CONVERT_TO_TEXT. The following update-integration command changes the contentHandling to CONVERT_TO_TEXT for an integration request: aws apigateway update-integration \ --rest-api-id abc123 \ --resource-id aaa111 \ --http-method OPTIONS \ --patch-operations op='replace',path='/contentHandling',value='CONVERT_TO_TEXT' The following update-integration-response command changes the contentHandling to CONVERT_TO_TEXT for an integration response: aws apigateway update-integration-response \ --rest-api-id abc123 \ --resource-id aaa111 \ --http-method OPTIONS \ --status-code 200 \ --patch-operations op='replace',path='/contentHandling',value='CONVERT_TO_TEXT' Enabling CORS support for proxy integrations For a Lambda proxy integration or HTTP
|
apigateway-dg-162
|
apigateway-dg.pdf
| 162 |
least all 200 responses. If you have binary media types set to */* for your API, when API Gateway creates an OPTIONS method, change the contentHandling to CONVERT_TO_TEXT. The following update-integration command changes the contentHandling to CONVERT_TO_TEXT for an integration request: aws apigateway update-integration \ --rest-api-id abc123 \ --resource-id aaa111 \ --http-method OPTIONS \ --patch-operations op='replace',path='/contentHandling',value='CONVERT_TO_TEXT' The following update-integration-response command changes the contentHandling to CONVERT_TO_TEXT for an integration response: aws apigateway update-integration-response \ --rest-api-id abc123 \ --resource-id aaa111 \ --http-method OPTIONS \ --status-code 200 \ --patch-operations op='replace',path='/contentHandling',value='CONVERT_TO_TEXT' Enabling CORS support for proxy integrations For a Lambda proxy integration or HTTP proxy integration, your backend is responsible for returning the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers, because a proxy integration doesn't return an integration response. The following example Lambda functions return the required CORS headers: CORS 591 Amazon API Gateway Node.js Developer Guide export const handler = async (event) => { const response = { statusCode: 200, headers: { "Access-Control-Allow-Headers" : "Content-Type", "Access-Control-Allow-Origin": "https://www.example.com", "Access-Control-Allow-Methods": "OPTIONS,POST,GET" }, body: JSON.stringify('Hello from Lambda!'), }; return response; }; Python 3 import json def lambda_handler(event, context): return { 'statusCode': 200, 'headers': { 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Origin': 'https://www.example.com', 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET' }, 'body': json.dumps('Hello from Lambda!') } Topics • Enable CORS on a resource using the API Gateway console • Enable CORS on a resource using the API Gateway import API • Test CORS for an API Gateway API Enable CORS on a resource using the API Gateway console You can use the API Gateway console to enable CORS support for one or all methods on a REST API resource that you have created. After you enable COR support, set the integration passthrough CORS 592 Amazon API Gateway Developer Guide behavior to NEVER. In this case, the method request of an unmapped content type will be rejected with an HTTP 415 Unsupported Media Type response. For more information, see Method request behavior for payloads without mapping templates for REST APIs in API Gateway Important Resources can contain child resources. Enabling CORS support for a resource and its methods does not recursively enable it for child resources and their methods. To enable CORS support on a REST API resource 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose an API. 3. Choose a resource under Resources. 4. In the Resource details section, choose Enable CORS. 5. In the Enable CORS box, do the following: CORS 593 Amazon API Gateway Developer Guide a. (Optional) If you created a custom gateway response and want to enable CORS support for a response, select a gateway response. b. Select each method to enable CORS support. The OPTION method must have CORS enabled. If you enable CORS support for an ANY method, CORS is enabled for all methods. c. In the Access-Control-Allow-Headers input field, enter a static string of a comma- separated list of headers that the client must submit in the actual request of the resource. Use the console-provided header list of 'Content-Type,X-Amz- Date,Authorization,X-Api-Key,X-Amz-Security-Token' or specify your own headers. d. Use the console-provided value of '*' as the Access-Control-Allow-Origin header value to allow access requests from all origins, or specify an origin to be permitted to access the resource. e. Choose Save. CORS 594 Amazon API Gateway Developer Guide Important When applying the above instructions to the ANY method in a proxy integration, any applicable CORS headers will not be set. Instead, your backend must return the applicable CORS headers, such as Access-Control-Allow-Origin. After CORS is enabled on the GET method, an OPTIONS method is added to the resource, if it is not already there. The 200 response of the OPTIONS method is automatically configured to return the three Access-Control-Allow-* headers to fulfill preflight handshakes. In addition, the actual (GET) method is also configured by default to return the Access-Control-Allow- Origin header in its 200 response as well. For other types of responses, you will need to manually configure them to return Access-Control-Allow-Origin' header with '*' or specific origins, if you do not want to return the Cross-origin access error. After you enable CORS support on your resource, you must deploy or redeploy the API for the new settings to take effect. For more information, see the section called “Create a deployment”. Note If you cannot enable CORS support on your resource after following the procedure, we recommend that you compare your CORS configuration to the example API /pets resource. To learn how to create the example API, see the section called “Tutorial: Create a REST API by importing an example”. Enable CORS on a resource using the API Gateway import API If you are using the API Gateway Import API, you can set up CORS support using an OpenAPI file. You must first define an OPTIONS method in your resource that returns the required headers. Note Web browsers expect Access-Control-Allow-Headers,
|
apigateway-dg-163
|
apigateway-dg.pdf
| 163 |
deployment”. Note If you cannot enable CORS support on your resource after following the procedure, we recommend that you compare your CORS configuration to the example API /pets resource. To learn how to create the example API, see the section called “Tutorial: Create a REST API by importing an example”. Enable CORS on a resource using the API Gateway import API If you are using the API Gateway Import API, you can set up CORS support using an OpenAPI file. You must first define an OPTIONS method in your resource that returns the required headers. Note Web browsers expect Access-Control-Allow-Headers, and Access-Control-Allow-Origin headers to be set up in each API method that accepts CORS requests. In addition, some browsers first make an HTTP request to an OPTIONS method in the same resource, and then expect to receive the same headers. CORS 595 Amazon API Gateway Example Options method Developer Guide The following example creates an OPTIONS method for a mock integration. OpenAPI 3.0 /users: options: summary: CORS support description: | Enable CORS by returning correct headers tags: - CORS responses: 200: description: Default response for CORS method headers: Access-Control-Allow-Origin: schema: type: "string" Access-Control-Allow-Methods: schema: type: "string" Access-Control-Allow-Headers: schema: type: "string" content: {} x-amazon-apigateway-integration: type: mock requestTemplates: application/json: "{\"statusCode\": 200}" passthroughBehavior: "never" responses: default: statusCode: "200" responseParameters: method.response.header.Access-Control-Allow-Headers: "'Content-Type,X- Amz-Date,Authorization,X-Api-Key'" method.response.header.Access-Control-Allow-Methods: "'*'" method.response.header.Access-Control-Allow-Origin: "'*'" CORS 596 Amazon API Gateway OpenAPI 2.0 Developer Guide /users: options: summary: CORS support description: | Enable CORS by returning correct headers consumes: - "application/json" produces: - "application/json" tags: - CORS x-amazon-apigateway-integration: type: mock requestTemplates: "{\"statusCode\": 200}" passthroughBehavior: "never" responses: "default": statusCode: "200" responseParameters: method.response.header.Access-Control-Allow-Headers : "'Content- Type,X-Amz-Date,Authorization,X-Api-Key'" method.response.header.Access-Control-Allow-Methods : "'*'" method.response.header.Access-Control-Allow-Origin : "'*'" responses: 200: description: Default response for CORS method headers: Access-Control-Allow-Headers: type: "string" Access-Control-Allow-Methods: type: "string" Access-Control-Allow-Origin: type: "string" Once you have configured the OPTIONS method for your resource, you can add the required headers to the other methods in the same resource that need to accept CORS requests. 1. Declare the Access-Control-Allow-Origin and Headers to the response types. CORS 597 Developer Guide Amazon API Gateway OpenAPI 3.0 responses: 200: description: Default response for CORS method headers: Access-Control-Allow-Origin: schema: type: "string" Access-Control-Allow-Methods: schema: type: "string" Access-Control-Allow-Headers: schema: type: "string" content: {} OpenAPI 2.0 responses: 200: description: Default response for CORS method headers: Access-Control-Allow-Headers: type: "string" Access-Control-Allow-Methods: type: "string" Access-Control-Allow-Origin: type: "string" 2. In the x-amazon-apigateway-integration tag, set up the mapping for those headers to your static values: OpenAPI 3.0 responses: default: statusCode: "200" responseParameters: method.response.header.Access-Control-Allow-Headers: "'Content- Type,X-Amz-Date,Authorization,X-Api-Key'" method.response.header.Access-Control-Allow-Methods: "'*'" CORS 598 Amazon API Gateway Developer Guide method.response.header.Access-Control-Allow-Origin: "'*'" responseTemplates: application/json: | {} OpenAPI 2.0 responses: "default": statusCode: "200" responseParameters: method.response.header.Access-Control-Allow-Headers : "'Content- Type,X-Amz-Date,Authorization,X-Api-Key'" method.response.header.Access-Control-Allow-Methods : "'*'" method.response.header.Access-Control-Allow-Origin : "'*'" Example API The following example creates a complete API with an OPTIONS method and a GET method with an HTTP integration. OpenAPI 3.0 openapi: "3.0.1" info: title: "cors-api" description: "cors-api" version: "2024-01-16T18:36:01Z" servers: - url: "/{basePath}" variables: basePath: default: "/test" paths: /: get: operationId: "GetPet" responses: "200": description: "200 response" headers: Access-Control-Allow-Origin: CORS 599 Amazon API Gateway Developer Guide schema: type: "string" content: {} x-amazon-apigateway-integration: httpMethod: "GET" uri: "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets" responses: default: statusCode: "200" responseParameters: method.response.header.Access-Control-Allow-Origin: "'*'" passthroughBehavior: "never" type: "http" options: responses: "200": description: "200 response" headers: Access-Control-Allow-Origin: schema: type: "string" Access-Control-Allow-Methods: schema: type: "string" Access-Control-Allow-Headers: schema: type: "string" content: application/json: schema: $ref: "#/components/schemas/Empty" x-amazon-apigateway-integration: responses: default: statusCode: "200" responseParameters: method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'" method.response.header.Access-Control-Allow-Headers: "'Content-Type,X- Amz-Date,Authorization,X-Api-Key'" method.response.header.Access-Control-Allow-Origin: "'*'" requestTemplates: application/json: "{\"statusCode\": 200}" passthroughBehavior: "never" type: "mock" CORS 600 Developer Guide Amazon API Gateway components: schemas: Empty: type: "object" OpenAPI 2.0 swagger: "2.0" info: description: "cors-api" version: "2024-01-16T18:36:01Z" title: "cors-api" basePath: "/test" schemes: - "https" paths: /: get: operationId: "GetPet" produces: - "application/json" responses: "200": description: "200 response" headers: Access-Control-Allow-Origin: type: "string" x-amazon-apigateway-integration: httpMethod: "GET" uri: "http://petstore.execute-api.us-east-1.amazonaws.com/petstore/pets" responses: default: statusCode: "200" responseParameters: method.response.header.Access-Control-Allow-Origin: "'*'" passthroughBehavior: "never" type: "http" options: consumes: - "application/json" produces: - "application/json" responses: CORS 601 Developer Guide Amazon API Gateway "200": description: "200 response" schema: $ref: "#/definitions/Empty" headers: Access-Control-Allow-Origin: type: "string" Access-Control-Allow-Methods: type: "string" Access-Control-Allow-Headers: type: "string" x-amazon-apigateway-integration: responses: default: statusCode: "200" responseParameters: method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS'" method.response.header.Access-Control-Allow-Headers: "'Content-Type,X- Amz-Date,Authorization,X-Api-Key'" method.response.header.Access-Control-Allow-Origin: "'*'" requestTemplates: application/json: "{\"statusCode\": 200}" passthroughBehavior: "never" type: "mock" definitions: Empty: type: "object" Test CORS for an API Gateway API You can test your API's CORS configuration by invoking your API, and checking the CORS headers in the response. The following curl command sends an OPTIONS request to a deployed API. curl -v -X OPTIONS https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name} < HTTP/1.1 200 OK < Date: Tue, 19 May 2020 00:55:22 GMT < Content-Type: application/json < Content-Length: 0 < Connection: keep-alive < x-amzn-RequestId: a1b2c3d4-5678-90ab-cdef-abc123 < Access-Control-Allow-Origin: * CORS 602 Amazon API Gateway Developer Guide < Access-Control-Allow-Headers: Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz- Security-Token < x-amz-apigw-id: Abcd= < Access-Control-Allow-Methods: DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT The Access-Control-Allow-Origin, Access-Control-Allow-Headers, and Access- Control-Allow-Methods headers in the response show that the API supports CORS. For more information, see CORS for REST APIs in
|
apigateway-dg-164
|
apigateway-dg.pdf
| 164 |
CORS configuration by invoking your API, and checking the CORS headers in the response. The following curl command sends an OPTIONS request to a deployed API. curl -v -X OPTIONS https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name} < HTTP/1.1 200 OK < Date: Tue, 19 May 2020 00:55:22 GMT < Content-Type: application/json < Content-Length: 0 < Connection: keep-alive < x-amzn-RequestId: a1b2c3d4-5678-90ab-cdef-abc123 < Access-Control-Allow-Origin: * CORS 602 Amazon API Gateway Developer Guide < Access-Control-Allow-Headers: Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz- Security-Token < x-amz-apigw-id: Abcd= < Access-Control-Allow-Methods: DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT The Access-Control-Allow-Origin, Access-Control-Allow-Headers, and Access- Control-Allow-Methods headers in the response show that the API supports CORS. For more information, see CORS for REST APIs in API Gateway. Binary media types for REST APIs in API Gateway In API Gateway, the API request and response have a text or binary payload. A text payload is a UTF-8-encoded JSON string. A binary payload is anything other than a text payload. The binary payload can be, for example, a JPEG file, a GZip file, or an XML file. The API configuration required to support binary media depends on whether your API uses proxy or non-proxy integrations. AWS Lambda proxy integrations To handle binary payloads for AWS Lambda proxy integrations, you must base64-encode your function's response. You must also configure the binaryMediaTypes for your API. Your API's binaryMediaTypes configuration is a list of content types that your API treats as binary data. Example binary media types include image/png or application/octet-stream. You can use the wildcard character (*) to cover multiple media types. API Gateway uses the first Accept header from clients to determine if a response should return binary media. To return binary media when you can't control the order of Accept header values, such as requests from a browser, set your API's binary media types to */*. For example code, see the section called “Return binary media from a Lambda proxy integration in API Gateway”. Non-proxy integrations To handle binary payloads for non-proxy integrations, you add the media types to the binaryMediaTypes list of the RestApi resource. Your API's binaryMediaTypes configuration is a list of content types that your API treats as binary data. Alternatively, you can set the contentHandling properties on the Integration and the IntegrationResponse resources. The contentHandling value can be CONVERT_TO_BINARY, CONVERT_TO_TEXT, or undefined. Binary media types 603 Amazon API Gateway Note Developer Guide For MOCK integrations, setting the contentHandling properties isn't supported in the AWS Management Console. You must use the AWS CLI, AWS CloudFormation, or an SDK to set the contentHandling properties. Depending on the contentHandling value, and whether the Content-Type header of the response or the Accept header of the incoming request matches an entry in the binaryMediaTypes list, API Gateway can encode the raw binary bytes as a base64-encoded string, decode a base64-encoded string back to its raw bytes, or pass the body through without modification. You must configure the API as follows to support binary payloads for your API in API Gateway: • Add the desired binary media types to the binaryMediaTypes list on the RestApi resource. If this property and the contentHandling property are not defined, the payloads are handled as UTF-8 encoded JSON strings. • Address the contentHandling property of the Integration resource. • To have the request payload converted from a base64-encoded string to its binary blob, set the property to CONVERT_TO_BINARY. • To have the request payload converted from a binary blob to a base64-encoded string, set the property to CONVERT_TO_TEXT. • To pass the payload through without modification, leave the property undefined. To pass a binary payload through without modification, you must also ensure that the Content-Type matches one of the binaryMediaTypes entries, and that passthrough behaviors are enabled for the API. • Set the contentHandling property of the IntegrationResponse resource. The contentHandling property, Accept header in client requests, and your API's binaryMediaTypes combined determine how API Gateway handles content type conversions. For details, see the section called “Content type conversions in API Gateway”. Important When a request contains multiple media types in its Accept header, API Gateway honors only the first Accept media type. If you can't control the order of the Accept media types Binary media types 604 Amazon API Gateway Developer Guide and the media type of your binary content isn't the first in the list, add the first Accept media type in the binaryMediaTypes list of your API. API Gateway handles all content types in this list as binary. For example, to send a JPEG file using an <img> element in a browser, the browser might send Accept:image/webp,image/*,*/*;q=0.8 in a request. By adding image/webp to the binaryMediaTypes list, the endpoint receives the JPEG file as binary. For detailed information about how API Gateway handles the text and binary payloads, see Content type conversions in API Gateway. Content type conversions in API Gateway The combination of your API's binaryMediaTypes, the headers in
|
apigateway-dg-165
|
apigateway-dg.pdf
| 165 |
first in the list, add the first Accept media type in the binaryMediaTypes list of your API. API Gateway handles all content types in this list as binary. For example, to send a JPEG file using an <img> element in a browser, the browser might send Accept:image/webp,image/*,*/*;q=0.8 in a request. By adding image/webp to the binaryMediaTypes list, the endpoint receives the JPEG file as binary. For detailed information about how API Gateway handles the text and binary payloads, see Content type conversions in API Gateway. Content type conversions in API Gateway The combination of your API's binaryMediaTypes, the headers in client requests, and the integration contentHandling property determine how API Gateway encodes payloads. The following table shows how API Gateway converts the request payload for specific configurations of a request's Content-Type header, the binaryMediaTypes list of a RestApi resource, and the contentHandling property value of the Integration resource. Method request payload Request Content-T ype header binaryMed contentHa iaTypes ndling Integration request payload Text data Any data type Undefined Undefined UTF8-encoded string Text data Any data type Undefined Text data Any data type Undefined Text data A text data type Set with matching media types CONVERT_T O_BINARY Base64-decoded binary blob CONVERT_T O_TEXT UTF8-encoded string Undefined Text data Binary media types 605 Amazon API Gateway Method request payload Request Content-T ype header binaryMed contentHa iaTypes ndling Integration request payload Developer Guide Text data A text data type Set with matching media CONVERT_T O_BINARY Base64-decoded binary blob Text data A text data type Binary data A binary data type types Set with matching media types Set with matching media types CONVERT_T Text data O_TEXT Undefined Binary data Binary data A binary data type Set with matching media CONVERT_T Binary data O_BINARY types Binary data A binary data type Set with matching media CONVERT_T O_TEXT Base64-encoded string types The following table shows how API Gateway converts the response payload for specific configurations of a request's Accept header, the binaryMediaTypes list of a RestApi resource, and the contentHandling property value of the IntegrationResponse resource. Important When a request contains multiple media types in its Accept header, API Gateway honors only the first Accept media type. If you can't control the order of the Accept media types and the media type of your binary content isn't the first in the list, add the first Accept media type in the binaryMediaTypes list of your API. API Gateway handles all content types in this list as binary. Binary media types 606 Amazon API Gateway Developer Guide For example, to send a JPEG file using an <img> element in a browser, the browser might send Accept:image/webp,image/*,*/*;q=0.8 in a request. By adding image/webp to the binaryMediaTypes list, the endpoint receives the JPEG file as binary. Integration response payload Text or binary data Text or binary data Text or binary data Request Accept header binaryMed contentHa iaTypes ndling A text type Undefined Undefined Method response payload UTF8-encoded string A text type Undefined CONVERT_T O_BINARY Base64-decoded blob A text type Undefined CONVERT_T O_TEXT UTF8-encoded string Text data A text type Set with matching media types Undefined Text data Text data A text type Set with matching media CONVERT_T O_BINARY Base64-decoded blob types Text data A text type Set with matching media CONVERT_T O_TEXT UTF8-encoded string Text data A binary type Text data A binary type types Set with matching media types Set with matching media types Undefined Base64-decoded blob CONVERT_T O_BINARY Base64-decoded blob Binary media types 607 Amazon API Gateway Integration response payload Request Accept header binaryMed contentHa iaTypes ndling Developer Guide Method response payload Text data A binary type Set with matching media CONVERT_T O_TEXT UTF8-encoded string Binary data A text type Binary data A text type types Set with matching media types Set with matching media types Undefined Base64-encoded string CONVERT_T Binary data O_BINARY Binary data A text type Set with matching media CONVERT_T O_TEXT Base64-encoded string Binary data A binary type Binary data A binary type Binary data A binary type types Set with matching media types Set with matching media types Set with matching media types Undefined Binary data CONVERT_T Binary data O_BINARY CONVERT_T O_TEXT Base64-encoded string When converting a text payload to a binary blob, API Gateway assumes that the text data is a base64-encoded string and outputs the binary data as a base64-decoded blob. If the conversion fails, it returns a 500 response, which indicates an API configuration error. You don't provide a mapping template for such a conversion, although you must enable the passthrough behaviors on the API. Binary media types 608 Amazon API Gateway Developer Guide When converting a binary payload to a text string, API Gateway always applies a base64 encoding on the binary data. You can define a mapping template for such a payload, but can only access the base64-encoded string in
|
apigateway-dg-166
|
apigateway-dg.pdf
| 166 |
assumes that the text data is a base64-encoded string and outputs the binary data as a base64-decoded blob. If the conversion fails, it returns a 500 response, which indicates an API configuration error. You don't provide a mapping template for such a conversion, although you must enable the passthrough behaviors on the API. Binary media types 608 Amazon API Gateway Developer Guide When converting a binary payload to a text string, API Gateway always applies a base64 encoding on the binary data. You can define a mapping template for such a payload, but can only access the base64-encoded string in the mapping template through $input.body, as shown in the following excerpt of an example mapping template. { "data": "$input.body" } To have the binary payload passed through without modification, you must enable the passthrough behaviors on the API. Enabling binary support using the API Gateway console The section explains how to enable binary support using the API Gateway console. As an example, we use an API that is integrated with Amazon S3. We focus on the tasks to set the supported media types and to specify how the payload should be handled. For detailed information on how to create an API integrated with Amazon S3, see Tutorial: Create a REST API as an Amazon S3 proxy. To enable binary support by using the API Gateway console 1. Set binary media types for the API: a. Create a new API or choose an existing API. For this example, we name the API FileMan. b. Under the selected API in the primary navigation panel, choose API settings. c. In the API settings pane, choose Manage media types in the Binary Media Types section. d. Choose Add binary media type. e. Enter a required media type, for example, image/png, in the input text field. If needed, repeat this step to add more media types. To support all binary media types, specify */*. f. Choose Save changes. 2. Set how message payloads are handled for the API method: a. Create a new or choose an existing resource in the API. For this example, we use the / {folder}/{item} resource. b. Create a new or choose an existing method on the resource. As an example, we use the GET /{folder}/{item} method integrated with the Object GET action in Amazon S3. c. For Content handling, choose an option. Binary media types 609 Amazon API Gateway Developer Guide Choose Passthrough if you don't want to convert the body when the client and backend accepts the same binary format. Choose Convert to text to convert the binary body to a base64-encoded string when, for example, the backend requires that a binary request payload is passed in as a JSON property. And choose Convert to binary when the client submits a base64-encoded string and the backend requires the original binary format, or when the endpoint returns a base64-encoded string and the client accepts only the binary output. d. For Request body passthrough, choose When there are no templates defined (recommended) to enable the passthrough behavior on the request body. You could also choose Never. This means that the API will reject data with content-types that do not have a mapping template. e. Preserve the incoming request's Accept header in the integration request. You should do this if you've set contentHandling to passthrough and want to override that setting at runtime. Binary media types 610 Amazon API Gateway Developer Guide f. For conversion to text, define a mapping template to put the base64-encoded binary data into the required format. An example of a mapping template to convert to text is the following: { "operation": "thumbnail", "base64Image": "$input.body" } The format of this mapping template depends on the endpoint requirements of the input. g. Choose Save. Enabling binary support using the API Gateway REST API The following tasks show how to enable binary support using the API Gateway REST API calls. Topics • Add and update supported binary media types to an API • Configure request payload conversions • Configure response payload conversions • Convert binary data to text data • Convert text data to a binary payload • Pass through a binary payload Binary media types 611 Amazon API Gateway Developer Guide Add and update supported binary media types to an API To enable API Gateway to support a new binary media type, you must add the binary media type to the binaryMediaTypes list of the RestApi resource. For example, to have API Gateway handle JPEG images, submit a PATCH request to the RestApi resource: PATCH /restapis/<restapi_id> { "patchOperations" : [ { "op" : "add", "path" : "/binaryMediaTypes/image~1jpeg" } ] } The MIME type specification of image/jpeg that is part of the path property value is escaped as image~1jpeg. To update the supported binary media types, replace or remove the
|
apigateway-dg-167
|
apigateway-dg.pdf
| 167 |
Developer Guide Add and update supported binary media types to an API To enable API Gateway to support a new binary media type, you must add the binary media type to the binaryMediaTypes list of the RestApi resource. For example, to have API Gateway handle JPEG images, submit a PATCH request to the RestApi resource: PATCH /restapis/<restapi_id> { "patchOperations" : [ { "op" : "add", "path" : "/binaryMediaTypes/image~1jpeg" } ] } The MIME type specification of image/jpeg that is part of the path property value is escaped as image~1jpeg. To update the supported binary media types, replace or remove the media type from the binaryMediaTypes list of the RestApi resource. For example, to change binary support from JPEG files to raw bytes, submit a PATCH request to the RestApi resource, as follows: PATCH /restapis/<restapi_id> { "patchOperations" : [{ "op" : "replace", "path" : "/binaryMediaTypes/image~1jpeg", "value" : "application/octet-stream" }, { "op" : "remove", "path" : "/binaryMediaTypes/image~1jpeg" }] } Configure request payload conversions If the endpoint requires a binary input, set the contentHandling property of the Integration resource to CONVERT_TO_BINARY. To do so, submit a PATCH request, as follows: Binary media types 612 Amazon API Gateway Developer Guide PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration { "patchOperations" : [ { "op" : "replace", "path" : "/contentHandling", "value" : "CONVERT_TO_BINARY" }] } Configure response payload conversions If the client accepts the result as a binary blob instead of a base64-encoded payload returned from the endpoint, set the contentHandling property of the IntegrationResponse resource to CONVERT_TO_BINARY. To do this, submit a PATCH request, as follows: PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/integration/ responses/<status_code> { "patchOperations" : [ { "op" : "replace", "path" : "/contentHandling", "value" : "CONVERT_TO_BINARY" }] } Convert binary data to text data To send binary data as a JSON property of the input to AWS Lambda or Kinesis through API Gateway, do the following: 1. Enable the binary payload support of the API by adding the new binary media type of application/octet-stream to the API's binaryMediaTypes list. PATCH /restapis/<restapi_id> { "patchOperations" : [ { "op" : "add", "path" : "/binaryMediaTypes/application~1octet-stream" Binary media types 613 Amazon API Gateway } ] } Developer Guide 2. Set CONVERT_TO_TEXT on the contentHandling property of the Integration resource and provide a mapping template to assign the base64-encoded string of the binary data to a JSON property. In the following example, the JSON property is body and $input.body holds the base64-encoded string. PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/ integration { "patchOperations" : [ { "op" : "replace", "path" : "/contentHandling", "value" : "CONVERT_TO_TEXT" }, { "op" : "add", "path" : "/requestTemplates/application~1octet-stream", "value" : "{\"body\": \"$input.body\"}" } ] } Convert text data to a binary payload Suppose a Lambda function returns an image file as a base64-encoded string. To pass this binary output to the client through API Gateway, do the following: 1. Update the API's binaryMediaTypes list by adding the binary media type of application/ octet-stream, if it is not already in the list. PATCH /restapis/<restapi_id> { "patchOperations" : [ { "op" : "add", "path" : "/binaryMediaTypes/application~1octet-stream", Binary media types 614 Amazon API Gateway }] } Developer Guide 2. Set the contentHandling property on the Integration resource to CONVERT_TO_BINARY. Do not define a mapping template. If you don't define a mapping template, API Gateway invokes the passthrough template to return the base64-decoded binary blob as the image file to the client. PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/ integration/responses/<status_code> { "patchOperations" : [ { "op" : "replace", "path" : "/contentHandling", "value" : "CONVERT_TO_BINARY" } ] } Pass through a binary payload To store an image in an Amazon S3 bucket using API Gateway, do the following: 1. Update the API's binaryMediaTypes list by adding the binary media type of application/ octet-stream, if it isn't already in the list. PATCH /restapis/<restapi_id> { "patchOperations" : [ { "op" : "add", "path" : "/binaryMediaTypes/application~1octet-stream" } ] } 2. On the contentHandling property of the Integration resource, set CONVERT_TO_BINARY. Set WHEN_NO_MATCH as the passthroughBehavior property value without defining a mapping template. This enables API Gateway to invoke the passthrough template. Binary media types 615 Amazon API Gateway Developer Guide PATCH /restapis/<restapi_id>/resources/<resource_id>/methods/<http_method>/ integration { "patchOperations" : [ { "op" : "replace", "path" : "/contentHandling", "value" : "CONVERT_TO_BINARY" }, { "op" : "replace", "path" : "/passthroughBehaviors", "value" : "WHEN_NO_MATCH" } ] } Import and export content encodings for API Gateway To import the binaryMediaTypes list on a RestApi, use the following API Gateway extension to the API's OpenAPI definition file. The extension is also used to export the API settings. • x-amazon-apigateway-binary-media-types property To import and export the contentHandling property value on an Integration or IntegrationResponse resource, use the following API Gateway extensions to the OpenAPI definitions: • x-amazon-apigateway-integration object • x-amazon-apigateway-integration.response object Return binary media from a Lambda proxy integration in API Gateway To return binary media from an AWS Lambda proxy integration, base64 encode the response from your Lambda function.
|
apigateway-dg-168
|
apigateway-dg.pdf
| 168 |
Import and export content encodings for API Gateway To import the binaryMediaTypes list on a RestApi, use the following API Gateway extension to the API's OpenAPI definition file. The extension is also used to export the API settings. • x-amazon-apigateway-binary-media-types property To import and export the contentHandling property value on an Integration or IntegrationResponse resource, use the following API Gateway extensions to the OpenAPI definitions: • x-amazon-apigateway-integration object • x-amazon-apigateway-integration.response object Return binary media from a Lambda proxy integration in API Gateway To return binary media from an AWS Lambda proxy integration, base64 encode the response from your Lambda function. You must also configure your API's binary media types. When you configure your API's binary media types, your API treats that content type as binary data. The payload size limit is 10 MB. Binary media types 616 Amazon API Gateway Note Developer Guide To use a web browser to invoke an API with this example integration, set your API's binary media types to */*. API Gateway uses the first Accept header from clients to determine if a response should return binary media. To return binary media when you can't control the order of Accept header values, such as requests from a browser, set your API's binary media types to */* (for all content types). The following example Lambda function can return a binary image from Amazon S3 or text to clients. The function's response includes a Content-Type header to indicate to the client the type of data that it returns. The function conditionally sets the isBase64Encoded property in its response, depending on the type of data that it returns. Node.js import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3" const client = new S3Client({region: 'us-east-2'}); export const handler = async (event) => { var randomint = function(max) { return Math.floor(Math.random() * max); } var number = randomint(2); if (number == 1){ const input = { "Bucket" : "bucket-name", "Key" : "image.png" } try { const command = new GetObjectCommand(input) const response = await client.send(command); var str = await response.Body.transformToByteArray(); } catch (err) { console.error(err); } const base64body = Buffer.from(str).toString('base64'); return { 'headers': { "Content-Type": "image/png" }, Binary media types 617 Amazon API Gateway Developer Guide 'statusCode': 200, 'body': base64body, 'isBase64Encoded': true } } else { return { 'headers': { "Content-Type": "text/html" }, 'statusCode': 200, 'body': "<h1>This is text</h1>", } } } Python import base64 import boto3 import json import random s3 = boto3.client('s3') def lambda_handler(event, context): number = random.randint(0,1) if number == 1: response = s3.get_object( Bucket='bucket-name', Key='image.png', ) image = response['Body'].read() return { 'headers': { "Content-Type": "image/png" }, 'statusCode': 200, 'body': base64.b64encode(image).decode('utf-8'), 'isBase64Encoded': True } else: return { 'headers': { "Content-type": "text/html" }, 'statusCode': 200, 'body': "<h1>This is text</h1>", } Binary media types 618 Amazon API Gateway Developer Guide To learn more about binary media types, see Binary media types for REST APIs in API Gateway. Access binary files in Amazon S3 through an API Gateway API The following examples show the OpenAPI file used to access images in Amazon S3, how to download an image from Amazon S3, and how to upload an image to Amazon S3. Topics • OpenAPI file of a sample API to access images in Amazon S3 • Download an image from Amazon S3 • Upload an image to Amazon S3 OpenAPI file of a sample API to access images in Amazon S3 The following OpenAPI file shows a sample API that illustrates downloading an image file from Amazon S3 and uploading an image file to Amazon S3. This API exposes the GET /s3? key={file-name} and PUT /s3?key={file-name} methods for downloading and uploading a specified image file. The GET method returns the image file as a base64-encoded string as part of a JSON output, following the supplied mapping template, in a 200 OK response. The PUT method takes a raw binary blob as input and returns a 200 OK response with an empty payload. OpenAPI 3.0 { "openapi": "3.0.0", "info": { "version": "2016-10-21T17:26:28Z", "title": "ApiName" }, "paths": { "/s3": { "get": { "parameters": [ { "name": "key", "in": "query", "required": false, "schema": { "type": "string" } Binary media types 619 Amazon API Gateway Developer Guide } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "credentials": "arn:aws:iam::123456789012:role/binarySupportRole", "responses": { "default": { "statusCode": "500" }, "2\\d{2}": { "statusCode": "200" } }, "requestParameters": { "integration.request.path.key": "method.request.querystring.key" }, "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}", "passthroughBehavior": "when_no_match", "httpMethod": "GET", "type": "aws" } }, "put": { "parameters": [ { "name": "key", "in": "query", "required": false, "schema": { "type": "string" Binary media types 620 Amazon API Gateway Developer Guide } } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } }, "application/octet-stream": { "schema": { "$ref": "#/components/schemas/Empty" }
|
apigateway-dg-169
|
apigateway-dg.pdf
| 169 |
"application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "credentials": "arn:aws:iam::123456789012:role/binarySupportRole", "responses": { "default": { "statusCode": "500" }, "2\\d{2}": { "statusCode": "200" } }, "requestParameters": { "integration.request.path.key": "method.request.querystring.key" }, "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}", "passthroughBehavior": "when_no_match", "httpMethod": "GET", "type": "aws" } }, "put": { "parameters": [ { "name": "key", "in": "query", "required": false, "schema": { "type": "string" Binary media types 620 Amazon API Gateway Developer Guide } } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } }, "application/octet-stream": { "schema": { "$ref": "#/components/schemas/Empty" } } } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "credentials": "arn:aws:iam::123456789012:role/binarySupportRole", "responses": { "default": { "statusCode": "500" }, "2\\d{2}": { "statusCode": "200" } }, "requestParameters": { "integration.request.path.key": "method.request.querystring.key" }, "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}", "passthroughBehavior": "when_no_match", "httpMethod": "PUT", "type": "aws", "contentHandling": "CONVERT_TO_BINARY" } } } Binary media types 621 Amazon API Gateway }, "x-amazon-apigateway-binary-media-types": [ "application/octet-stream", "image/jpeg" ], "servers": [ { Developer Guide "url": "https://abcdefghi.execute-api.us-east-1.amazonaws.com/{basePath}", "variables": { "basePath": { "default": "/v1" } } } ], "components": { "schemas": { "Empty": { "type": "object", "title": "Empty Schema" } } } } OpenAPI 2.0 { "swagger": "2.0", "info": { "version": "2016-10-21T17:26:28Z", "title": "ApiName" }, "host": "abcdefghi.execute-api.us-east-1.amazonaws.com", "basePath": "/v1", "schemes": [ "https" ], "paths": { "/s3": { "get": { "produces": [ "application/json" Binary media types 622 Developer Guide Amazon API Gateway ], "parameters": [ { "name": "key", "in": "query", "required": false, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "credentials": "arn:aws:iam::123456789012:role/binarySupportRole", "responses": { "default": { "statusCode": "500" }, "2\\d{2}": { "statusCode": "200" } }, "requestParameters": { "integration.request.path.key": "method.request.querystring.key" }, "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}", "passthroughBehavior": "when_no_match", "httpMethod": "GET", "type": "aws" } }, "put": { "produces": [ "application/json", "application/octet-stream" ], "parameters": [ { Binary media types 623 Amazon API Gateway Developer Guide "name": "key", "in": "query", "required": false, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "credentials": "arn:aws:iam::123456789012:role/binarySupportRole", "responses": { "default": { "statusCode": "500" }, "2\\d{2}": { "statusCode": "200" } }, "requestParameters": { "integration.request.path.key": "method.request.querystring.key" }, "uri": "arn:aws:apigateway:us-west-2:s3:path/{key}", "passthroughBehavior": "when_no_match", "httpMethod": "PUT", "type": "aws", "contentHandling" : "CONVERT_TO_BINARY" } } } }, "x-amazon-apigateway-binary-media-types" : ["application/octet-stream", "image/ jpeg"], "definitions": { "Empty": { "type": "object", Binary media types 624 Amazon API Gateway Developer Guide "title": "Empty Schema" } } } Download an image from Amazon S3 To download an image file (image.jpg) as a binary blob from Amazon S3: GET /v1/s3?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/json Accept: application/octet-stream The successful response looks like this: 200 OK HTTP/1.1 [raw bytes] The raw bytes are returned because the Accept header is set to a binary media type of application/octet-stream and binary support is enabled for the API. Alternatively, to download an image file (image.jpg) as a base64-encoded string (formatted as a JSON property) from Amazon S3, add a response template to the 200 integration response, as shown in the following bold-faced OpenAPI definition block: "x-amazon-apigateway-integration": { "credentials": "arn:aws:iam::123456789012:role/binarySupportRole", "responses": { "default": { "statusCode": "500" }, "2\\d{2}": { "statusCode": "200", "responseTemplates": { "application/json": "{\n \"image\": \"$input.body\"\n}" } } }, Binary media types 625 Amazon API Gateway Developer Guide The request to download the image file looks like the following: GET /v1/s3?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/json Accept: application/json The successful response looks like the following: 200 OK HTTP/1.1 { "image": "W3JhdyBieXRlc10=" } Upload an image to Amazon S3 To upload an image file (image.jpg) as a binary blob to Amazon S3: PUT /v1/s3?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/octet-stream Accept: application/json [raw bytes] The successful response looks like the following: 200 OK HTTP/1.1 To upload an image file (image.jpg) as a base64-encoded string to Amazon S3: PUT /v1/s3?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/json Accept: application/json W3JhdyBieXRlc10= The input payload must be a base64-encoded string because the Content-Type header value is set to application/json. The successful response looks like the following: Binary media types 626 Amazon API Gateway 200 OK HTTP/1.1 Developer Guide Access binary files in Lambda using an API Gateway API The following OpenAPI example demonstrates how to access a binary file in AWS Lambda through an API Gateway API. This API exposes the GET /lambda?key={file-name} and the PUT / lambda?key={file-name} methods for downloading and uploading a specified image file. The GET method returns the image file as a base64-encoded string as part of a JSON output, following the supplied mapping template, in a 200 OK response. The PUT method takes a raw binary blob as input and returns a 200 OK response with an empty payload. You create the Lambda function that your API calls, and it must return a base64-encoded string with the Content-Type header of application/json. Topics • OpenAPI file of a sample API
|
apigateway-dg-170
|
apigateway-dg.pdf
| 170 |
API Gateway API. This API exposes the GET /lambda?key={file-name} and the PUT / lambda?key={file-name} methods for downloading and uploading a specified image file. The GET method returns the image file as a base64-encoded string as part of a JSON output, following the supplied mapping template, in a 200 OK response. The PUT method takes a raw binary blob as input and returns a 200 OK response with an empty payload. You create the Lambda function that your API calls, and it must return a base64-encoded string with the Content-Type header of application/json. Topics • OpenAPI file of a sample API to access images in Lambda • Download an image from Lambda • Upload an image to Lambda OpenAPI file of a sample API to access images in Lambda The following OpenAPI file shows an example API that illustrates downloading an image file from Lambda and uploading an image file to Lambda. OpenAPI 3.0 { "openapi": "3.0.0", "info": { "version": "2016-10-21T17:26:28Z", "title": "ApiName" }, "paths": { "/lambda": { "get": { "parameters": [ { "name": "key", "in": "query", "required": false, Binary media types 627 Amazon API Gateway Developer Guide "schema": { "type": "string" } } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/ functions/arn:aws:lambda:us-east-1:123456789012:function:image/invocations", "type": "AWS", "credentials": "arn:aws:iam::123456789012:role/Lambda", "httpMethod": "POST", "requestTemplates": { "application/json": "{\n \"imageKey\": \"$input.params('key')\"\n}" }, "responses": { "default": { "statusCode": "500" }, "2\\d{2}": { "statusCode": "200", "responseTemplates": { "application/json": "{\n \"image\": \"$input.body\"\n}" } } } } }, "put": { Binary media types 628 Amazon API Gateway Developer Guide "parameters": [ { "name": "key", "in": "query", "required": false, "schema": { "type": "string" } } ], "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } }, "application/octet-stream": { "schema": { "$ref": "#/components/schemas/Empty" } } } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/ functions/arn:aws:lambda:us-east-1:123456789012:function:image/invocations", "type": "AWS", "credentials": "arn:aws:iam::123456789012:role/Lambda", "httpMethod": "POST", "contentHandling": "CONVERT_TO_TEXT", "requestTemplates": { "application/json": "{\n \"imageKey\": \"$input.params('key')\", \"image\": \"$input.body\"\n}" }, "responses": { "default": { "statusCode": "500" Binary media types 629 Amazon API Gateway Developer Guide }, "2\\d{2}": { "statusCode": "200" } } } } } }, "x-amazon-apigateway-binary-media-types": [ "application/octet-stream", "image/jpeg" ], "servers": [ { "url": "https://abcdefghi.execute-api.us-east-1.amazonaws.com/{basePath}", "variables": { "basePath": { "default": "/v1" } } } ], "components": { "schemas": { "Empty": { "type": "object", "title": "Empty Schema" } } } } OpenAPI 2.0 { "swagger": "2.0", "info": { "version": "2016-10-21T17:26:28Z", "title": "ApiName" }, "host": "abcdefghi.execute-api.us-east-1.amazonaws.com", "basePath": "/v1", Binary media types 630 Amazon API Gateway Developer Guide "schemes": [ "https" ], "paths": { "/lambda": { "get": { "produces": [ "application/json" ], "parameters": [ { "name": "key", "in": "query", "required": false, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-east-1:123456789012:function:image/invocations", "type": "AWS", "credentials": "arn:aws:iam::123456789012:role/Lambda", "httpMethod": "POST", "requestTemplates": { "application/json": "{\n \"imageKey\": \"$input.params('key')\"\n}" }, "responses": { "default": { "statusCode": "500" }, "2\\d{2}": { "statusCode": "200", "responseTemplates": { Binary media types 631 Amazon API Gateway Developer Guide "application/json": "{\n \"image\": \"$input.body\"\n}" } } } } }, "put": { "produces": [ "application/json", "application/octet-stream" ], "parameters": [ { "name": "key", "in": "query", "required": false, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } }, "500": { "description": "500 response" } }, "x-amazon-apigateway-integration": { "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-east-1:123456789012:function:image/invocations", "type": "AWS", "credentials": "arn:aws:iam::123456789012:role/Lambda", "httpMethod": "POST", "contentHandling" : "CONVERT_TO_TEXT", "requestTemplates": { "application/json": "{\n \"imageKey\": \"$input.params('key')\", \"image\": \"$input.body\"\n}" }, "responses": { "default": { "statusCode": "500" }, Binary media types 632 Amazon API Gateway Developer Guide "2\\d{2}": { "statusCode": "200" } } } } } }, "x-amazon-apigateway-binary-media-types" : ["application/octet-stream", "image/ jpeg"], "definitions": { "Empty": { "type": "object", "title": "Empty Schema" } } } Download an image from Lambda To download an image file (image.jpg) as a binary blob from Lambda: GET /v1/lambda?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/json Accept: application/octet-stream The successful response looks like the following: 200 OK HTTP/1.1 [raw bytes] To download an image file (image.jpg) as a base64-encoded string (formatted as a JSON property) from Lambda: GET /v1/lambda?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/json Accept: application/json Binary media types 633 Amazon API Gateway Developer Guide The successful response looks like the following: 200 OK HTTP/1.1 { "image": "W3JhdyBieXRlc10=" } Upload an image to Lambda To upload an image file (image.jpg) as a binary blob to Lambda: PUT /v1/lambda?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/octet-stream Accept: application/json [raw bytes] The successful response looks like the following: 200 OK To upload an image file (image.jpg) as a base64-encoded string to Lambda: PUT /v1/lambda?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/json Accept: application/json W3JhdyBieXRlc10= The successful response looks like the following: 200 OK Invoke REST APIs in API Gateway To call a deployed API, clients submit requests
|
apigateway-dg-171
|
apigateway-dg.pdf
| 171 |
API Gateway Developer Guide The successful response looks like the following: 200 OK HTTP/1.1 { "image": "W3JhdyBieXRlc10=" } Upload an image to Lambda To upload an image file (image.jpg) as a binary blob to Lambda: PUT /v1/lambda?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/octet-stream Accept: application/json [raw bytes] The successful response looks like the following: 200 OK To upload an image file (image.jpg) as a base64-encoded string to Lambda: PUT /v1/lambda?key=image.jpg HTTP/1.1 Host: abcdefghi.execute-api.us-east-1.amazonaws.com Content-Type: application/json Accept: application/json W3JhdyBieXRlc10= The successful response looks like the following: 200 OK Invoke REST APIs in API Gateway To call a deployed API, clients submit requests to the URL for the API Gateway component service for API execution, known as execute-api. Invoke 634 Amazon API Gateway Developer Guide The base URL for REST APIs is in the following format: https://api-id.execute-api.region.amazonaws.com/stage/ where api-id is the API identifier, region is the AWS Region, and stage is the stage name of the API deployment. Important Before you can invoke an API, you must deploy it in API Gateway. For instructions on deploying an API, see Deploy REST APIs in API Gateway. Topics • Obtaining an API's invoke URL • Invoking an API • Use the API Gateway console to test a REST API method • Use a Java SDK generated by API Gateway for a REST API • Use an Android SDK generated by API Gateway for a REST API • Use a JavaScript SDK generated by API Gateway for a REST API • Use a Ruby SDK generated by API Gateway for a REST API • Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift Obtaining an API's invoke URL You can use the console, the AWS CLI, or an exported OpenAPI definition to obtain an API's invoke URL. Obtaining an API's invoke URL using the console The following procedure shows how to obtain an API's invoke URL in the REST API console. To obtain an API's invoke URL using the REST API console 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Invoke 635 Amazon API Gateway 2. Choose a deployed API. Developer Guide 3. From the main navigation pane, choose Stage. 4. Under Stage details, choose the copy icon to copy your API's invoke URL. This URL is for the root resource of your API. 5. To obtain an API's invoke URL for another resource in your API, expand the stage under the secondary navigation pane, and then choose a method. 6. Choose the copy icon to copy your API's resource-level invoke URL. Invoke 636 Amazon API Gateway Developer Guide Obtaining an API's invoke URL using the AWS CLI The following procedure shows how to obtain an API's invoke URL using the AWS CLI. To obtain an API's invoke URL using the AWS CLI 1. Use the following command to obtain the rest-api-id. This command returns all rest- api-id values in your Region. For more information, see get-rest-apis. aws apigateway get-rest-apis Invoke 637 Amazon API Gateway Developer Guide 2. Replace the example rest-api-id with your rest-api-id, replace the example {stage- name} with your {stage-name}, and replace the {region}, with your Region. https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name}/ Obtaining an API's invoke URL using the exported OpenAPI definition file of the API You can also construct the root URL by combining the host and basePath fields of an exported OpenAPI definition file of the API. For instructions on how to export your API, see the section called “Export a REST API”. Invoking an API You can call your deployed API using the browser, curl, or other applications, like Postman. Additionally, you can use the API Gateway console to test an API call. Test uses the API Gateway's TestInvoke feature, which allows API testing before the API is deployed. For more information, see the section called “Use the console to test a REST API method”. Note Query string parameter values in an invocation URL cannot contain %%. Invoking an API using a web browser If your API permits anonymous access, you can use any web browser to invoke any GET method. Enter the complete invocation URL in the browser's address bar. For other methods or any authentication-required calls, you must specify a payload or sign the requests. You can handle these in a script behind an HTML page or in a client application using one of the AWS SDKs. Invoking an API using curl You can use a tool like curl in your terminal to call your API. The following example curl command invokes the GET method on the getUsers resource of the prod stage of an API. Invoke 638 Amazon API Gateway Linux or Macintosh Developer Guide curl -X GET 'https://b123abcde4.execute-api.us-west-2.amazonaws.com/prod/getUsers' Windows curl -X GET "https://b123abcde4.execute-api.us-west-2.amazonaws.com/prod/getUsers" Use the API Gateway console to test a REST API method Use the API Gateway console to test a
|
apigateway-dg-172
|
apigateway-dg.pdf
| 172 |
requests. You can handle these in a script behind an HTML page or in a client application using one of the AWS SDKs. Invoking an API using curl You can use a tool like curl in your terminal to call your API. The following example curl command invokes the GET method on the getUsers resource of the prod stage of an API. Invoke 638 Amazon API Gateway Linux or Macintosh Developer Guide curl -X GET 'https://b123abcde4.execute-api.us-west-2.amazonaws.com/prod/getUsers' Windows curl -X GET "https://b123abcde4.execute-api.us-west-2.amazonaws.com/prod/getUsers" Use the API Gateway console to test a REST API method Use the API Gateway console to test a REST API method. Topics • Prerequisites • Test a method with the API Gateway console Prerequisites • You must specify the settings for the methods you want to test. Follow the instructions in Methods for REST APIs in API Gateway. Test a method with the API Gateway console Important Testing methods with the API Gateway console might result in changes to resources that cannot be undone. Testing a method with the API Gateway console is the same as calling the method outside of the API Gateway console. For example, if you use the API Gateway console to call a method that deletes an API's resources, if the method call is successful, the API's resources will be deleted. To test a method 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. In the Resources pane, choose the method you want to test. Invoke 639 Amazon API Gateway Developer Guide 4. Choose the Test tab. You might need to choose the right arrow button to show the tab. Enter values in any of the displayed boxes (such as Query strings, Headers, and Request body). The console includes these values in the method request in default application/json form. For additional options you might need to specify, contact the API owner. 5. Choose Test. The following information will be displayed: • Request is the resource's path that was called for the method. • Status is the response's HTTP status code. • Latency (ms) is the time between the receipt of the request from the caller and the returned response. • Response body is the HTTP response body. • Response headers are the HTTP response headers. Tip Depending on the mapping, the HTTP status code, response body, and response headers might be different from those sent from the Lambda function, HTTP proxy, or AWS service proxy. Invoke 640 Amazon API Gateway Developer Guide • Logs are the simulated Amazon CloudWatch Logs entries that would have been written if this method were called outside of the API Gateway console. Note Although the CloudWatch Logs entries are simulated, the results of the method call are real. In addition to using the API Gateway console, you can use AWS CLI or an AWS SDK for API Gateway to test invoking a method. To do so using AWS CLI, see test-invoke-method. Use a Java SDK generated by API Gateway for a REST API In this section, we outline the steps to use a Java SDK generated by API Gateway for a REST API, by using the Simple Calculator API as an example. Before proceeding, you must complete the steps in Generate SDKs for REST APIs in API Gateway. To install and use a Java SDK generated by API Gateway 1. Extract the contents of the API Gateway-generated .zip file that you downloaded earlier. 2. Download and install Apache Maven (must be version 3.5 or later). 3. Download and install JDK 8. 4. Set the JAVA_HOME environment variable. 5. Go to the unzipped SDK folder where the pom.xml file is located. This folder is generated- code by default. Run the mvn install command to install the compiled artifact files to your local Maven repository. This creates a target folder containing the compiled SDK library. 6. Type the following command in an empty directory to create a client project stub to call the API using the installed SDK library. mvn -B archetype:generate \ -DarchetypeGroupdId=org.apache.maven.archetypes \ -DgroupId=examples.aws.apig.simpleCalc.sdk.app \ -DartifactId=SimpleCalc-sdkClient Invoke 641 Amazon API Gateway Note Developer Guide The separator \ in the preceding command is included for readability. The whole command should be on a single line without the separator. This command creates an application stub. The application stub contains a pom.xml file and an src folder under the project's root directory (SimpleCalc-sdkClient in the preceding command). Initially, there are two source files: src/main/java/{package- path}/App.java and src/test/java/{package-path}/AppTest.java. In this example, {package-path} is examples/aws/apig/simpleCalc/sdk/app. This package path is derived from the DarchetypeGroupdId value. You can use the App.java file as a template for your client application, and you can add others in the same folder if needed. You can use the AppTest.java file as a unit test template for your application, and you can add other
|
apigateway-dg-173
|
apigateway-dg.pdf
| 173 |
single line without the separator. This command creates an application stub. The application stub contains a pom.xml file and an src folder under the project's root directory (SimpleCalc-sdkClient in the preceding command). Initially, there are two source files: src/main/java/{package- path}/App.java and src/test/java/{package-path}/AppTest.java. In this example, {package-path} is examples/aws/apig/simpleCalc/sdk/app. This package path is derived from the DarchetypeGroupdId value. You can use the App.java file as a template for your client application, and you can add others in the same folder if needed. You can use the AppTest.java file as a unit test template for your application, and you can add other test code files to the same test folder as needed. 7. Update the package dependencies in the generated pom.xml file to the following, substituting your project's groupId, artifactId, version, and name properties, if necessary: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:// www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/ POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>examples.aws.apig.simpleCalc.sdk.app</groupId> <artifactId>SimpleCalc-sdkClient</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>SimpleCalc-sdkClient</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-core</artifactId> <version>1.11.94</version> </dependency> <dependency> <groupId>my-apig-api-examples</groupId> <artifactId>simple-calc-sdk</artifactId> <version>1.0.0</version> Invoke 642 Amazon API Gateway </dependency> Developer Guide <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> Note When a newer version of dependent artifact of aws-java-sdk-core is incompatible with the version specified above (1.11.94), you must update the <version> tag to the new version. 8. Next, we show how to call the API using the SDK by calling the getABOp(GetABOpRequest req), getApiRoot(GetApiRootRequest req), and postApiRoot(PostApiRootRequest req) methods of the SDK. These methods correspond to the GET /{a}/{b}/{op}, GET /?a={x}&b={y}&op={operator}, and Invoke 643 Amazon API Gateway Developer Guide POST / methods, with a payload of {"a": x, "b": y, "op": "operator"} API requests, respectively. Update the App.java file as follows: package examples.aws.apig.simpleCalc.sdk.app; import java.io.IOException; import com.amazonaws.opensdk.config.ConnectionConfiguration; import com.amazonaws.opensdk.config.TimeoutConfiguration; import examples.aws.apig.simpleCalc.sdk.*; import examples.aws.apig.simpleCalc.sdk.model.*; import examples.aws.apig.simpleCalc.sdk.SimpleCalcSdk.*; public class App { SimpleCalcSdk sdkClient; public App() { initSdk(); } // The configuration settings are for illustration purposes and may not be a recommended best practice. private void initSdk() { sdkClient = SimpleCalcSdk.builder() .connectionConfiguration( new ConnectionConfiguration() .maxConnections(100) .connectionMaxIdleMillis(1000)) .timeoutConfiguration( new TimeoutConfiguration() .httpRequestTimeout(3000) .totalExecutionTimeout(10000) .socketTimeout(2000)) .build(); } // Calling shutdown is not necessary unless you want to exert explicit control of this resource. public void shutdown() { Invoke 644 Amazon API Gateway Developer Guide sdkClient.shutdown(); } // GetABOpResult getABOp(GetABOpRequest getABOpRequest) public Output getResultWithPathParameters(String x, String y, String operator) { operator = operator.equals("+") ? "add" : operator; operator = operator.equals("/") ? "div" : operator; GetABOpResult abopResult = sdkClient.getABOp(new GetABOpRequest().a(x).b(y).op(operator)); return abopResult.getResult().getOutput(); } public Output getResultWithQueryParameters(String a, String b, String op) { GetApiRootResult rootResult = sdkClient.getApiRoot(new GetApiRootRequest().a(a).b(b).op(op)); return rootResult.getResult().getOutput(); } public Output getResultByPostInputBody(Double x, Double y, String o) { PostApiRootResult postResult = sdkClient.postApiRoot( new PostApiRootRequest().input(new Input().a(x).b(y).op(o))); return postResult.getResult().getOutput(); } public static void main( String[] args ) { System.out.println( "Simple calc" ); // to begin App calc = new App(); // call the SimpleCalc API Output res = calc.getResultWithPathParameters("1", "2", "-"); System.out.printf("GET /1/2/-: %s\n", res.getC()); // Use the type query parameter res = calc.getResultWithQueryParameters("1", "2", "+"); System.out.printf("GET /?a=1&b=2&op=+: %s\n", res.getC()); // Call POST with an Input body. res = calc.getResultByPostInputBody(1.0, 2.0, "*"); System.out.printf("PUT /\n\n{\"a\":1, \"b\":2,\"op\":\"*\"}\n %s\n", res.getC()); Invoke 645 Amazon API Gateway Developer Guide } } In the preceding example, the configuration settings used to instantiate the SDK client are for illustration purposes and are not necessarily recommended best practice. Also, calling sdkClient.shutdown() is optional, especially if you need precise control on when to free up resources. We have shown the essential patterns to call an API using a Java SDK. You can extend the instructions to calling other API methods. Use an Android SDK generated by API Gateway for a REST API In this section, we will outline the steps to use an Android SDK generated by API Gateway for a REST API. Before proceeding further, you must have already completed the steps in Generate SDKs for REST APIs in API Gateway. Note The generated SDK is not compatible with Android 4.4 and earlier. For more information, see the section called “Important notes”. To install and use an Android SDK generated by API Gateway 1. Extract the contents of the API Gateway-generated .zip file that you downloaded earlier. 2. Download and install Apache Maven (preferably version 3.x). 3. Download and install JDK 8. 4. Set the JAVA_HOME environment variable. 5. Run the mvn install command to install the compiled artifact files to your local Maven repository. This creates a target folder containing the compiled SDK library. 6. Copy the SDK file (the name of which is derived from the Artifact Id and Artifact Version you specified when generating the SDK, e.g., simple-calcsdk-1.0.0.jar) from the target folder, along with all of the other libraries from the target/lib folder, into your project's lib folder. Invoke 646 Amazon API Gateway Developer Guide If you use Android Studio, create a libs folder under your client app module
|
apigateway-dg-174
|
apigateway-dg.pdf
| 174 |
4. Set the JAVA_HOME environment variable. 5. Run the mvn install command to install the compiled artifact files to your local Maven repository. This creates a target folder containing the compiled SDK library. 6. Copy the SDK file (the name of which is derived from the Artifact Id and Artifact Version you specified when generating the SDK, e.g., simple-calcsdk-1.0.0.jar) from the target folder, along with all of the other libraries from the target/lib folder, into your project's lib folder. Invoke 646 Amazon API Gateway Developer Guide If you use Android Studio, create a libs folder under your client app module and copy the required .jar file into this folder. Verify that the dependencies section in the module's gradle file contains the following. compile fileTree(include: ['*.jar'], dir: 'libs') compile fileTree(include: ['*.jar'], dir: 'app/libs') Make sure no duplicated .jar files are declared. 7. Use the ApiClientFactory class to initialize the API Gateway-generated SDK. For example: ApiClientFactory factory = new ApiClientFactory(); // Create an instance of your SDK. Here, 'SimpleCalcClient.java' is the compiled java class for the SDK generated by API Gateway. final SimpleCalcClient client = factory.build(SimpleCalcClient.class); // Invoke a method: // For the 'GET /?a=1&b=2&op=+' method exposed by the API, you can invoke it by calling the following SDK method: Result output = client.rootGet("1", "2", "+"); // where the Result class of the SDK corresponds to the Result model of the API. // // For the 'GET /{a}/{b}/{op}' method exposed by the API, you can call the following SDK method to invoke the request, Result output = client.aBOpGet(a, b, c); // where a, b, c can be "1", "2", "add", respectively. // For the following API method: // POST / // host: ... // Content-Type: application/json // // { "a": 1, "b": 2, "op": "+" } // you can call invoke it by calling the rootPost method of the SDK as follows: Input body = new Input(); Invoke 647 Amazon API Gateway input.a=1; input.b=2; input.op="+"; Result output = client.rootPost(body); Developer Guide // where the Input class of the SDK corresponds to the Input model of the API. // Parse the result: // If the 'Result' object is { "a": 1, "b": 2, "op": "add", "c":3"}, you retrieve the result 'c') as String result=output.c; 8. To use an Amazon Cognito credentials provider to authorize calls to your API, use the ApiClientFactory class to pass a set of AWS credentials by using the SDK generated by API Gateway, as shown in the following example. // Use CognitoCachingCredentialsProvider to provide AWS credentials // for the ApiClientFactory AWSCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider( context, // activity context "identityPoolId", // Cognito identity pool id Regions.US_EAST_1 // region of Cognito identity pool ); ApiClientFactory factory = new ApiClientFactory() .credentialsProvider(credentialsProvider); 9. To set an API key by using the API Gateway- generated SDK, use code similar to the following. ApiClientFactory factory = new ApiClientFactory() .apiKey("YOUR_API_KEY"); Invoke 648 Amazon API Gateway Developer Guide Use a JavaScript SDK generated by API Gateway for a REST API The following procedure shows how to use a JavaScript SDK generated by API Gateway. Note These instructions assume you have already completed the instructions in Generate SDKs for REST APIs in API Gateway. Important If your API only has ANY methods defined, the generated SDK package will not contain an apigClient.js file, and you will need to define the ANY methods yourself. To install, initiate and call a JavaScript SDK generated by API Gateway for a REST API 1. 2. Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Enable cross-origin resource sharing (CORS) for all of the methods the SDK generated by API Gateway will call. For instructions, see CORS for REST APIs in API Gateway. 3. In your web page, include references to the following scripts. <script type="text/javascript" src="lib/axios/dist/axios.standalone.js"></script> <script type="text/javascript" src="lib/CryptoJS/rollups/hmac-sha256.js"></script> <script type="text/javascript" src="lib/CryptoJS/rollups/sha256.js"></script> <script type="text/javascript" src="lib/CryptoJS/components/hmac.js"></script> <script type="text/javascript" src="lib/CryptoJS/components/enc-base64.js"></ script> <script type="text/javascript" src="lib/url-template/url-template.js"></script> <script type="text/javascript" src="lib/apiGatewayCore/sigV4Client.js"></script> <script type="text/javascript" src="lib/apiGatewayCore/apiGatewayClient.js"></ script> <script type="text/javascript" src="lib/apiGatewayCore/simpleHttpClient.js"></ script> <script type="text/javascript" src="lib/apiGatewayCore/utils.js"></script> <script type="text/javascript" src="apigClient.js"></script> 4. In your code, initialize the SDK generated by API Gateway by using code similar to the following. Invoke 649 Amazon API Gateway Developer Guide var apigClient = apigClientFactory.newClient(); To initialize the SDK generated by API Gateway with AWS credentials, use code similar to the following. If you use AWS credentials, all requests to the API will be signed. var apigClient = apigClientFactory.newClient({ accessKey: 'ACCESS_KEY', secretKey: 'SECRET_KEY', }); To use an API key with the SDK generated by API Gateway, pass the API key as a parameter to the Factory object by using code similar to the following. If you use an API key, it is specified as part of the x-api-key header and all requests to the API will be signed. This means you must set the appropriate CORS Accept headers for each request. var apigClient = apigClientFactory.newClient({
|
apigateway-dg-175
|
apigateway-dg.pdf
| 175 |
credentials, use code similar to the following. If you use AWS credentials, all requests to the API will be signed. var apigClient = apigClientFactory.newClient({ accessKey: 'ACCESS_KEY', secretKey: 'SECRET_KEY', }); To use an API key with the SDK generated by API Gateway, pass the API key as a parameter to the Factory object by using code similar to the following. If you use an API key, it is specified as part of the x-api-key header and all requests to the API will be signed. This means you must set the appropriate CORS Accept headers for each request. var apigClient = apigClientFactory.newClient({ apiKey: 'API_KEY' }); 5. Call the API methods in API Gateway by using code similar to the following. Each call returns a promise with a success and failure callbacks. var params = { // This is where any modeled request parameters should be added. // The key is the parameter name, as it is defined in the API in API Gateway. param0: '', param1: '' }; var body = { // This is where you define the body of the request, }; var additionalParams = { // If there are any unmodeled query parameters or headers that must be // sent with the request, add them here. headers: { param0: '', param1: '' Invoke 650 Amazon API Gateway Developer Guide }, queryParams: { param0: '', param1: '' } }; apigClient.methodName(params, body, additionalParams) .then(function(result){ // Add success callback code here. }).catch( function(result){ // Add error callback code here. }); Here, the methodName is constructed from the method request's resource path and the HTTP verb. For the SimpleCalc API, the SDK methods for the API methods of 1. GET /?a=...&b=...&op=... 2. POST / { "a": ..., "b": ..., "op": ...} 3. GET /{a}/{b}/{op} the corresponding SDK methods are as follows: 1. rootGet(params); // where params={"a": ..., "b": ..., "op": ...} is resolved to the query parameters 2. rootPost(null, body); // where body={"a": ..., "b": ..., "op": ...} 3. aBOpGet(params); // where params={"a": ..., "b": ..., "op": ...} is resolved to the path parameters Use a Ruby SDK generated by API Gateway for a REST API The following procedure shows how to use a Ruby SDK generated by API Gateway. Note These instructions assume you already completed the instructions in Generate SDKs for REST APIs in API Gateway. Invoke 651 Amazon API Gateway Developer Guide To install, instantiate, and call a Ruby SDK generated by API Gateway for a REST API 1. Unzip the downloaded Ruby SDK file. The generated SDK source is shown as follows. 2. Build a Ruby Gem from the generated SDK source, using the following shell commands in a terminal window: # change to /simplecalc-sdk directory cd simplecalc-sdk # build the generated gem gem build simplecalc-sdk.gemspec After this, simplecalc-sdk-1.0.0.gem becomes available. 3. Install the gem: gem install simplecalc-sdk-1.0.0.gem 4. Create a client application. Instantiate and initialize the Ruby SDK client in the app: require 'simplecalc-sdk' client = SimpleCalc::Client.new( Invoke 652 Amazon API Gateway Developer Guide http_wire_trace: true, retry_limit: 5, http_read_timeout: 50 ) If the API has authorization of the AWS_IAM type is configured, you can include the caller's AWS credentials by supplying accessKey and secretKey during the initialization: require 'pet-sdk' client = Pet::Client.new( http_wire_trace: true, retry_limit: 5, http_read_timeout: 50, access_key_id: 'ACCESS_KEY', secret_access_key: 'SECRET_KEY' ) 5. Make API calls through the SDK in the app. Tip If you are not familiar with the SDK method call conventions, you can review the client.rb file in the generated SDK lib folder. The folder contains documentation of each supported API method call. To discover supported operations: # to show supported operations: puts client.operation_names This results in the following display, corresponding to the API methods of GET /? a={.}&b={.}&op={.}, GET /{a}/{b}/{op}, and POST /, plus a payload of the {a:"…", b:"…", op:"…"} format, respectively: [:get_api_root, :get_ab_op, :post_api_root] To invoke the GET /?a=1&b=2&op=+ API method, call the following the Ruby SDK method: Invoke 653 Amazon API Gateway Developer Guide resp = client.get_api_root({a:"1", b:"2", op:"+"}) To invoke the POST / API method with a payload of {a: "1", b: "2", "op": "+"}, call the following Ruby SDK method: resp = client.post_api_root(input: {a:"1", b:"2", op:"+"}) To invoke the GET /1/2/+ API method, call the following Ruby SDK method: resp = client.get_ab_op({a:"1", b:"2", op:"+"}) The successful SDK method calls return the following response: resp : { result: { input: { a: 1, b: 2, op: "+" }, output: { c: 3 } } } Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift In this tutorial, we will show how to use an iOS SDK generated by API Gateway for a REST API in an Objective-C or Swift app to call the underlying API. We will use the SimpleCalc API as an example to illustrate the following topics: • How to install
|
apigateway-dg-176
|
apigateway-dg.pdf
| 176 |
method: resp = client.get_ab_op({a:"1", b:"2", op:"+"}) The successful SDK method calls return the following response: resp : { result: { input: { a: 1, b: 2, op: "+" }, output: { c: 3 } } } Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift In this tutorial, we will show how to use an iOS SDK generated by API Gateway for a REST API in an Objective-C or Swift app to call the underlying API. We will use the SimpleCalc API as an example to illustrate the following topics: • How to install the required AWS Mobile SDK components into your Xcode project • How to create the API client object before calling the API's methods • How to call the API methods through the corresponding SDK methods on the API client object • How to prepare a method input and parse its result using the corresponding model classes of the SDK Invoke 654 Amazon API Gateway Topics • Use generated iOS SDK (Objective-C) to call API • Use generated iOS SDK (Swift) to call API Use generated iOS SDK (Objective-C) to call API Developer Guide Before beginning the following procedure, you must complete the steps in Generate SDKs for REST APIs in API Gateway for iOS in Objective-C and download the .zip file of the generated SDK. Install the AWS mobile SDK and an iOS SDK generated by API Gateway in an Objective-C project The following procedure describes how to install the SDK. To install and use an iOS SDK generated by API Gateway in Objective-C 1. Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Using the SimpleCalc API, you may want to rename the unzipped SDK folder to something like sdk_objc_simple_calc. In this SDK folder there is a README.md file and a Podfile file. The README.md file contains the instructions to install and use the SDK. This tutorial provides details about these instructions. The installation leverages CocoaPods to import required API Gateway libraries and other dependent AWS Mobile SDK components. You must update the Podfile to import the SDKs into your app's Xcode project. The unarchived SDK folder also contains a generated-src folder that contains the source code of the generated SDK of your API. 2. Launch Xcode and create a new iOS Objective-C project. Make a note of the project's target. You will need to set it in the Podfile. Invoke 655 Amazon API Gateway Developer Guide 3. To import the AWS Mobile SDK for iOS into the Xcode project by using CocoaPods, do the following: a. Install CocoaPods by running the following command in a terminal window: sudo gem install cocoapods pod setup b. Copy the Podfile file from the extracted SDK folder into the same directory containing your Xcode project file. Replace the following block: target '<YourXcodeTarget>' do pod 'AWSAPIGateway', '~> 2.4.7' end with your project's target name: target 'app_objc_simple_calc' do pod 'AWSAPIGateway', '~> 2.4.7' end If your Xcode project already contains a file named Podfile, add the following line of code to it: pod 'AWSAPIGateway', '~> 2.4.7' c. Open a terminal window and run the following command: pod install This installs the API Gateway component and other dependent AWS Mobile SDK components. d. Close the Xcode project and then open the .xcworkspace file to relaunch Xcode. e. Add all of the .h and .m files from the extracted SDK's generated-src directory into your Xcode project. Invoke 656 Amazon API Gateway Developer Guide To import the AWS Mobile SDK for iOS Objective-C into your project by explicitly downloading AWS Mobile SDK or using Carthage, follow the instructions in the README.md file. Be sure to use only one of these options to import the AWS Mobile SDK. Call API methods using the iOS SDK generated by API Gateway in an Objective-C project When you generated the SDK with the prefix of SIMPLE_CALC for this SimpleCalc API with two models for input (Input) and output (Result) of the methods, in the SDK, the resulting API client class becomes SIMPLE_CALCSimpleCalcClient and the corresponding data classes are SIMPLE_CALCInput and SIMPLE_CALCResult, respectively. The API requests and responses are mapped to the SDK methods as follows: • The API request of GET /?a=...&b=...&op=... becomes the SDK method of Invoke 657 Amazon API Gateway Developer Guide (AWSTask *)rootGet:(NSString *)op a:(NSString *)a b:(NSString *)b The AWSTask.result property is of the SIMPLE_CALCResult type if the Result model was added to the method response. Otherwise, the property is of the NSDictionary type. • This API request of POST / { "a": "Number", "b": "Number", "op": "String" } becomes the SDK method of (AWSTask *)rootPost:(SIMPLE_CALCInput *)body • The API request of GET /{a}/{b}/{op} becomes the SDK method of (AWSTask *)aBOpGet:(NSString *)a b:(NSString *)b op:(NSString *)op The following procedure describes how to call the API methods
|
apigateway-dg-177
|
apigateway-dg.pdf
| 177 |
of GET /?a=...&b=...&op=... becomes the SDK method of Invoke 657 Amazon API Gateway Developer Guide (AWSTask *)rootGet:(NSString *)op a:(NSString *)a b:(NSString *)b The AWSTask.result property is of the SIMPLE_CALCResult type if the Result model was added to the method response. Otherwise, the property is of the NSDictionary type. • This API request of POST / { "a": "Number", "b": "Number", "op": "String" } becomes the SDK method of (AWSTask *)rootPost:(SIMPLE_CALCInput *)body • The API request of GET /{a}/{b}/{op} becomes the SDK method of (AWSTask *)aBOpGet:(NSString *)a b:(NSString *)b op:(NSString *)op The following procedure describes how to call the API methods in Objective-C app source code; for example, as part of the viewDidLoad delegate in a ViewController.m file. To call the API through the iOS SDK generated by API Gateway 1. Import the API client class header file to make the API client class callable in the app: #import "SIMPLE_CALCSimpleCalc.h" The #import statement also imports SIMPLE_CALCInput.h and SIMPLE_CALCResult.h for the two model classes. Invoke 658 Amazon API Gateway Developer Guide 2. Instantiate the API client class: SIMPLE_CALCSimpleCalcClient *apiInstance = [SIMPLE_CALCSimpleCalcClient defaultClient]; To use Amazon Cognito with the API, set the defaultServiceConfiguration property on the default AWSServiceManager object, as shown in the following, before calling the defaultClient method to create the API client object (shown in the preceding example): AWSCognitoCredentialsProvider *creds = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1 identityPoolId:your_cognito_pool_id]; AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:creds]; AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration; 3. Call the GET /?a=1&b=2&op=+ method to perform 1+2: [[apiInstance rootGet: @"+" a:@"1" b:@"2"] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) { _textField1.text = [self handleApiResponse:task]; return nil; }]; where the helper function handleApiResponse:task formats the result as a string to be displayed in a text field (_textField1). - (NSString *)handleApiResponse:(AWSTask *)task { if (task.error != nil) { return [NSString stringWithFormat: @"Error: %@", task.error.description]; } else if (task.result != nil && [task.result isKindOfClass:[SIMPLE_CALCResult class]]) { return [NSString stringWithFormat:@"%@ %@ %@ = %@\n",task.result.input.a, task.result.input.op, task.result.input.b, task.result.output.c]; } return nil; } The resulting display is 1 + 2 = 3. 4. Call the POST / with a payload to perform 1-2: Invoke 659 Amazon API Gateway Developer Guide SIMPLE_CALCInput *input = [[SIMPLE_CALCInput alloc] init]; input.a = [NSNumber numberWithInt:1]; input.b = [NSNumber numberWithInt:2]; input.op = @"-"; [[apiInstance rootPost:input] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) { _textField2.text = [self handleApiResponse:task]; return nil; }]; The resulting display is 1 - 2 = -1. 5. Call the GET /{a}/{b}/{op} to perform 1/2: [[apiInstance aBOpGet:@"1" b:@"2" op:@"div"] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) { _textField3.text = [self handleApiResponse:task]; return nil; }]; The resulting display is 1 div 2 = 0.5. Here, div is used in place of / because the simple Lambda function in the backend does not handle URL encoded path variables. Use generated iOS SDK (Swift) to call API Before beginning the following procedure, you must complete the steps in Generate SDKs for REST APIs in API Gateway for iOS in Swift and download the .zip file of the generated SDK. Topics • Install AWS mobile SDK and API Gateway-generated SDK in a Swift project • Call API methods through the iOS SDK generated by API Gateway in a Swift project Install AWS mobile SDK and API Gateway-generated SDK in a Swift project The following procedure describes how to install the SDK. Invoke 660 Amazon API Gateway Developer Guide To install and use an iOS SDK generated by API Gateway in Swift 1. Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Using the SimpleCalc API, you may want to rename the unzipped SDK folder to something like sdk_swift_simple_calc. In this SDK folder there is a README.md file and a Podfile file. The README.md file contains the instructions to install and use the SDK. This tutorial provides details about these instructions. The installation leverages CocoaPods to import required AWS Mobile SDK components. You must update the Podfile to import the SDKs into your Swift app's Xcode project. The unarchived SDK folder also contains a generated-src folder that contains the source code of the generated SDK of your API. 2. Launch Xcode and create a new iOS Swift project. Make a note of the project's target. You will need to set it in the Podfile. 3. To import the required AWS Mobile SDK components into the Xcode project by using CocoaPods, do the following: a. If it is not installed, install CocoaPods by running the following command in a terminal window: sudo gem install cocoapods pod setup b. Copy the Podfile file from the extracted SDK folder into the same directory containing your Xcode project file. Replace the following block: target '<YourXcodeTarget>' do Invoke 661 Amazon API Gateway Developer Guide pod 'AWSAPIGateway', '~> 2.4.7' end with your project's target name as shown: target 'app_swift_simple_calc' do pod 'AWSAPIGateway', '~> 2.4.7' end If your Xcode project already contains a Podfile with the correct target, you
|
apigateway-dg-178
|
apigateway-dg.pdf
| 178 |
components into the Xcode project by using CocoaPods, do the following: a. If it is not installed, install CocoaPods by running the following command in a terminal window: sudo gem install cocoapods pod setup b. Copy the Podfile file from the extracted SDK folder into the same directory containing your Xcode project file. Replace the following block: target '<YourXcodeTarget>' do Invoke 661 Amazon API Gateway Developer Guide pod 'AWSAPIGateway', '~> 2.4.7' end with your project's target name as shown: target 'app_swift_simple_calc' do pod 'AWSAPIGateway', '~> 2.4.7' end If your Xcode project already contains a Podfile with the correct target, you can simply add the following line of code to the do ... end loop: pod 'AWSAPIGateway', '~> 2.4.7' c. Open a terminal window and run the following command in the app directory: pod install This installs the API Gateway component and any dependent AWS Mobile SDK components into the app's project. d. Close the Xcode project and then open the *.xcworkspace file to relaunch Xcode. e. Add all of the SDK's header files (.h) and Swift source code files (.swift) from the extracted generated-src directory to your Xcode project. Invoke 662 Amazon API Gateway Developer Guide f. To enable calling the Objective-C libraries of the AWS Mobile SDK from your Swift code project, set the Bridging_Header.h file path on the Objective-C Bridging Header property under the Swift Compiler - General setting of your Xcode project configuration: Tip You can type bridging in the search box of Xcode to locate the Objective-C Bridging Header property. g. Build the Xcode project to verify that it is properly configured before proceeding further. If your Xcode uses a more recent version of Swift than the one supported for the AWS Invoke 663 Amazon API Gateway Developer Guide Mobile SDK, you will get Swift compiler errors. In this case, set the Use Legacy Swift Language Version property to Yes under the Swift Compiler - Version setting: To import the AWS Mobile SDK for iOS in Swift into your project by explicitly downloading the AWS Mobile SDK or using Carthage, follow the instructions in the README.md file that comes with the SDK package. Be sure to use only one of these options to import the AWS Mobile SDK. Call API methods through the iOS SDK generated by API Gateway in a Swift project When you generated the SDK with the prefix of SIMPLE_CALC for this SimpleCalc API with two models to describe the input (Input) and output (Result) of the API's requests and responses, in the SDK, the resulting API client class becomes SIMPLE_CALCSimpleCalcClient and the corresponding data classes are SIMPLE_CALCInput and SIMPLE_CALCResult, respectively. The API requests and responses are mapped to the SDK methods as follows: • The API request of GET /?a=...&b=...&op=... becomes the SDK method of public func rootGet(op: String?, a: String?, b: String?) -> AWSTask The AWSTask.result property is of the SIMPLE_CALCResult type if the Result model was added to the method response. Otherwise, it is of the NSDictionary type. • This API request of Invoke 664 Developer Guide Amazon API Gateway POST / { "a": "Number", "b": "Number", "op": "String" } becomes the SDK method of public func rootPost(body: SIMPLE_CALCInput) -> AWSTask • The API request of GET /{a}/{b}/{op} becomes the SDK method of public func aBOpGet(a: String, b: String, op: String) -> AWSTask The following procedure describes how to call the API methods in Swift app source code; for example, as part of the viewDidLoad() delegate in a ViewController.m file. To call the API through the iOS SDK generated by API Gateway 1. Instantiate the API client class: let client = SIMPLE_CALCSimpleCalcClient.default() To use Amazon Cognito with the API, set a default AWS service configuration (shown following) before getting the default method (shown previously): let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.USEast1, identityPoolId: "my_pool_id") let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider) Invoke 665 Amazon API Gateway Developer Guide AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration 2. Call the GET /?a=1&b=2&op=+ method to perform 1+2: client.rootGet("+", a: "1", b:"2").continueWithBlock {(task: AWSTask) -> AnyObject? in self.showResult(task) return nil } where the helper function self.showResult(task) prints the result or error to the console; for example: func showResult(task: AWSTask) { if let error = task.error { print("Error: \(error)") } else if let result = task.result { if result is SIMPLE_CALCResult { let res = result as! SIMPLE_CALCResult print(String(format:"%@ %@ %@ = %@", res.input!.a!, res.input!.op!, res.input!.b!, res.output!.c!)) } else if result is NSDictionary { let res = result as! NSDictionary print("NSDictionary: \(res)") } } } In a production app, you can display the result or error in a text field. The resulting display is 1 + 2 = 3. 3. Call the POST / with a payload to perform 1-2: let body = SIMPLE_CALCInput() body.a=1 body.b=2 body.op="-" client.rootPost(body).continueWithBlock {(task: AWSTask) -> AnyObject? in self.showResult(task) return nil } Invoke 666 Amazon API Gateway
|
apigateway-dg-179
|
apigateway-dg.pdf
| 179 |
let result = task.result { if result is SIMPLE_CALCResult { let res = result as! SIMPLE_CALCResult print(String(format:"%@ %@ %@ = %@", res.input!.a!, res.input!.op!, res.input!.b!, res.output!.c!)) } else if result is NSDictionary { let res = result as! NSDictionary print("NSDictionary: \(res)") } } } In a production app, you can display the result or error in a text field. The resulting display is 1 + 2 = 3. 3. Call the POST / with a payload to perform 1-2: let body = SIMPLE_CALCInput() body.a=1 body.b=2 body.op="-" client.rootPost(body).continueWithBlock {(task: AWSTask) -> AnyObject? in self.showResult(task) return nil } Invoke 666 Amazon API Gateway Developer Guide The resultant display is 1 - 2 = -1. 4. Call the GET /{a}/{b}/{op} to perform 1/2: client.aBOpGet("1", b:"2", op:"div").continueWithBlock {(task: AWSTask) -> AnyObject? in self.showResult(task) return nil } The resulting display is 1 div 2 = 0.5. Here, div is used in place of / because the simple Lambda function in the backend does not handle URL encoded path variables. Develop REST APIs using OpenAPI in API Gateway You can use API Gateway to import a REST API from an external definition file into API Gateway. Currently, API Gateway supports OpenAPI v2.0 and OpenAPI v3.0 definition files, with exceptions listed in Amazon API Gateway important notes for REST APIs. You can update an API by overwriting it with a new definition, or you can merge a definition with an existing API. You specify the options by using a mode query parameter in the request URL. For a tutorial on using the Import API feature from the API Gateway console, see Tutorial: Create a REST API by importing an example. Topics • Import an edge-optimized API into API Gateway • Import a Regional API into API Gateway • Import an OpenAPI file to update an existing API definition • Set the OpenAPI basePath property • AWS variables for OpenAPI import • Errors and warnings from importing your API into API Gateway • Export a REST API from API Gateway OpenAPI 667 Amazon API Gateway Developer Guide Import an edge-optimized API into API Gateway You can import an API's OpenAPI definition file to create a new edge-optimized API by specifying the EDGE endpoint type as an additional input, besides the OpenAPI file, to the import operation. You can do so using the API Gateway console, AWS CLI, or an AWS SDK. For a tutorial on using the Import API feature from the API Gateway console, see Tutorial: Create a REST API by importing an example. Topics • Import an edge-optimized API using the API Gateway console • Import an edge-optimized API using the AWS CLI Import an edge-optimized API using the API Gateway console To import an edge-optimized API using the API Gateway console, do the following: 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API. 3. Under REST API, choose Import. 4. Copy an API's OpenAPI definition and paste it into the code editor, or choose Choose file to load an OpenAPI file from a local drive. 5. For API endpoint type, select Edge-optimized. 6. Choose Create API to start importing the OpenAPI definitions. Import an edge-optimized API using the AWS CLI The following import-rest-api command imports an API from an OpenAPI definition file to create a new edge-optimized API: aws apigateway import-rest-api \ --fail-on-warnings \ --body 'file://path/to/API_OpenAPI_template.json' or with an explicit specification of the endpointConfigurationTypes query string parameter to EDGE: aws apigateway import-rest-api \ OpenAPI 668 Amazon API Gateway Developer Guide --parameters endpointConfigurationTypes=EDGE \ --fail-on-warnings \ --body 'file://path/to/API_OpenAPI_template.json' Import a Regional API into API Gateway When importing an API, you can choose the regional endpoint configuration for the API. You can use the API Gateway console, the AWS CLI, or an AWS SDK. When you export an API, the API endpoint configuration is not included in the exported API definitions. For a tutorial on using the Import API feature from the API Gateway console, see Tutorial: Create a REST API by importing an example. Topics • Import a regional API using the API Gateway console • Import a regional API using the AWS CLI Import a regional API using the API Gateway console To import an API of a regional endpoint using the API Gateway console, do the following: 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API. 3. Under REST API, choose Import. 4. Copy an API's OpenAPI definition and paste it into the code editor, or choose Choose file to load an OpenAPI file from a local drive. 5. For API endpoint type, select Regional. 6. Choose Create API to start importing the OpenAPI definitions. Import a regional API using the AWS CLI The following import-rest-api command imports an OpenAPI definition file and sets the endpoint type to Regional: aws apigateway import-rest-api \ OpenAPI 669
|
apigateway-dg-180
|
apigateway-dg.pdf
| 180 |
the API Gateway console, do the following: 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Create API. 3. Under REST API, choose Import. 4. Copy an API's OpenAPI definition and paste it into the code editor, or choose Choose file to load an OpenAPI file from a local drive. 5. For API endpoint type, select Regional. 6. Choose Create API to start importing the OpenAPI definitions. Import a regional API using the AWS CLI The following import-rest-api command imports an OpenAPI definition file and sets the endpoint type to Regional: aws apigateway import-rest-api \ OpenAPI 669 Amazon API Gateway Developer Guide --parameters endpointConfigurationTypes=REGIONAL \ --fail-on-warnings \ --body 'file://path/to/API_OpenAPI_template.json' Import an OpenAPI file to update an existing API definition You can import API definitions only to update an existing API, without changing its endpoint configuration, as well as stages and stage variables, or references to API keys. The import-to-update operation can occur in two modes: merge or overwrite. When an API (A) is merged into another (B), the resulting API retains the definitions of both A and B if the two APIs do not share any conflicting definitions. When conflicts arise, the method definitions of the merging API (A) overrides the corresponding method definitions of the merged API (B). For example, suppose B has declared the following methods to return 200 and 206 responses: GET /a POST /a and A declares the following method to return 200 and 400 responses: GET /a When A is merged into B, the resulting API yields the following methods: GET /a which returns 200 and 400 responses, and POST /a which returns 200 and 206 responses. Merging an API is useful when you have decomposed your external API definitions into multiple, smaller parts and only want to apply changes from one of those parts at a time. For example, this might occur if multiple teams are responsible for different parts of an API and have changes available at different rates. In this mode, items from the existing API that aren't specifically defined in the imported definition are left alone. OpenAPI 670 Amazon API Gateway Developer Guide When an API (A) overwrites another API (B), the resulting API takes the definitions of the overwriting API (A). Overwriting an API is useful when an external API definition contains the complete definition of an API. In this mode, items from an existing API that aren't specifically defined in the imported definition are deleted. To merge an API, submit a PUT request to https://apigateway.<region>.amazonaws.com/ restapis/<restapi_id>?mode=merge. The restapi_id path parameter value specifies the API to which the supplied API definition will be merged. The following code snippet shows an example of the PUT request to merge an OpenAPI API definition in JSON, as the payload, with the specified API already in API Gateway. PUT /restapis/<restapi_id>?mode=merge Host:apigateway.<region>.amazonaws.com Content-Type: application/json Content-Length: ... An OpenAPI API definition in JSON The merging update operation takes two complete API definitions and merges them together. For a small and incremental change, you can use the resource update operation. To overwrite an API, submit a PUT request to https:// apigateway.<region>.amazonaws.com/restapis/<restapi_id>?mode=overwrite. The restapi_id path parameter specifies the API that will be overwritten with the supplied API definitions. The following code snippet shows an example of an overwriting request with the payload of a JSON-formatted OpenAPI definition: PUT /restapis/<restapi_id>?mode=overwrite Host:apigateway.<region>.amazonaws.com Content-Type: application/json Content-Length: ... An OpenAPI API definition in JSON OpenAPI 671 Amazon API Gateway Developer Guide When the mode query parameter isn't specified, merge is assumed. Note The PUT operations are idempotent, but not atomic. That means if a system error occurs part way through processing, the API can end up in a bad state. However, repeating the operation successfully puts the API into the same final state as if the first operation had succeeded. Set the OpenAPI basePath property In OpenAPI 2.0, you can use the basePath property to provide one or more path parts that precede each path defined in the paths property. Because API Gateway has several ways to express a resource's path, the Import API feature provides the following options for interpreting the basePath property during import: ignore, prepend, and split. In OpenAPI 3.0, basePath is no longer a top-level property. Instead, API Gateway uses a server variable as a convention. The Import API feature provides the same options for interpreting the base path during import. The base path is identified as follows: • If the API doesn't contain any basePath variables, the Import API feature checks the server.url string to see if it contains a path beyond "/". If it does, that path is used as the base path. • If the API contains only one basePath variable, the Import API feature uses it as the base path, even if it's not referenced in the server.url. • If the
|
apigateway-dg-181
|
apigateway-dg.pdf
| 181 |
property. Instead, API Gateway uses a server variable as a convention. The Import API feature provides the same options for interpreting the base path during import. The base path is identified as follows: • If the API doesn't contain any basePath variables, the Import API feature checks the server.url string to see if it contains a path beyond "/". If it does, that path is used as the base path. • If the API contains only one basePath variable, the Import API feature uses it as the base path, even if it's not referenced in the server.url. • If the API contains multiple basePath variables, the Import API feature uses only the first one as the base path. Ignore If the OpenAPI file has a basePath value of /a/b/c and the paths property contains /e and /f, the following POST or PUT request: POST /restapis?mode=import&basepath=ignore OpenAPI 672 Amazon API Gateway Developer Guide PUT /restapis/api_id?basepath=ignore results in the following resources in the API: • / • /e • /f The effect is to treat the basePath as if it was not present, and all of the declared API resources are served relative to the host. This can be used, for example, when you have a custom domain name with an API mapping that doesn't include a Base Path and a Stage value that refers to your production stage. Note API Gateway automatically creates a root resource for you, even if it isn't explicitly declared in your definition file. When unspecified, basePath takes ignore by default. Prepend If the OpenAPI file has a basePath value of /a/b/c and the paths property contains /e and /f, the following POST or PUT request: POST /restapis?mode=import&basepath=prepend PUT /restapis/api_id?basepath=prepend results in the following resources in the API: • / • /a • /a/b OpenAPI 673 Amazon API Gateway • /a/b/c • /a/b/c/e • /a/b/c/f Developer Guide The effect is to treat the basePath as specifying additional resources (without methods) and to add them to the declared resource set. This can be used, for example, when different teams are responsible for different parts of an API and the basePath could reference the path location for each team's API part. Note API Gateway automatically creates intermediate resources for you, even if they aren't explicitly declared in your definition. Split If the OpenAPI file has a basePath value of /a/b/c and the paths property contains /e and /f, the following POST or PUT request: POST /restapis?mode=import&basepath=split PUT /restapis/api_id?basepath=split results in the following resources in the API: • / • /b • /b/c • /b/c/e • /b/c/f The effect is to treat top-most path part, /a, as the beginning of each resource's path, and to create additional (no method) resources within the API itself. This could, for example, be used when a is a stage name that you want to expose as part of your API. OpenAPI 674 Amazon API Gateway Developer Guide AWS variables for OpenAPI import You can use the following AWS variables in OpenAPI definitions. API Gateway resolves the variables when the API is imported. To specify a variable, use ${variable-name}. The following table describes the available AWS variables. Variable name Description AWS::AccountId AWS::Partition AWS::Region The AWS account ID that imports the API. For example, 123456789012. The AWS partition in which the API is imported. For standard AWS Regions, the partition is aws. The AWS Region in which the API is imported. For example, us-east-2 . AWS variables example The following example uses AWS variables to specify an AWS Lambda function for an integration. OpenAPI 3.0 openapi: "3.0.1" info: title: "tasks-api" version: "v1.0" paths: /: get: summary: List tasks description: Returns a list of tasks responses: 200: description: "OK" content: OpenAPI 675 Amazon API Gateway Developer Guide application/json: schema: type: array items: $ref: "#/components/schemas/Task" 500: description: "Internal Server Error" content: {} x-amazon-apigateway-integration: uri: arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/ functions/arn:${AWS::Partition}:lambda:${AWS::Region}: ${AWS::AccountId}:function:LambdaFunctionName/invocations responses: default: statusCode: "200" passthroughBehavior: "when_no_match" httpMethod: "POST" contentHandling: "CONVERT_TO_TEXT" type: "aws_proxy" components: schemas: Task: type: object properties: id: type: integer name: type: string description: type: string Errors and warnings from importing your API into API Gateway When you import your external definition file into API Gateway, API Gateway might generate warnings and errors. The following sections discuss the errors and warnings that might occur during import. Errors during import During the import, errors can be generated for major issues like an invalid OpenAPI document. Errors are returned as exceptions (for example, BadRequestException) in an unsuccessful OpenAPI 676 Amazon API Gateway Developer Guide response. When an error occurs, the new API definition is discarded and no change is made to the existing API. Warnings during import During the import, warnings can be generated for minor issues like a missing model reference. If a warning occurs, the operation will continue if the failonwarnings=false query expression is appended to the request URL. Otherwise,
|
apigateway-dg-182
|
apigateway-dg.pdf
| 182 |
warnings that might occur during import. Errors during import During the import, errors can be generated for major issues like an invalid OpenAPI document. Errors are returned as exceptions (for example, BadRequestException) in an unsuccessful OpenAPI 676 Amazon API Gateway Developer Guide response. When an error occurs, the new API definition is discarded and no change is made to the existing API. Warnings during import During the import, warnings can be generated for minor issues like a missing model reference. If a warning occurs, the operation will continue if the failonwarnings=false query expression is appended to the request URL. Otherwise, the updates will be rolled back. By default, failonwarnings is set to false. In such cases, warnings are returned as a field in the resulting RestApi resource. Otherwise, warnings are returned as a message in the exception. Export a REST API from API Gateway Once you created and configured a REST API in API Gateway, using the API Gateway console or otherwise, you can export it to an OpenAPI file using the API Gateway Export API, which is part of the Amazon API Gateway Control Service. To use the API Gateway Export API, you need to sign your API requests. For more information about signing requests, see Signing AWS API requests in the IAM User Guide. You have options to include the API Gateway integration extensions, as well as the Postman extensions, in the exported OpenAPI definition file. Note When exporting the API using the AWS CLI, be sure to include the extensions parameter as shown in the following example, to ensure that the x-amazon-apigateway-request- validator extension is included: aws apigateway get-export --parameters extensions='apigateway' --rest-api-id abcdefg123 --stage-name dev --export-type swagger latestswagger2.json You cannot export an API if its payloads are not of the application/json type. If you try, you will get an error response stating that JSON body models are not found. Request to export a REST API With the Export API, you export an existing REST API by submitting a GET request, specifying the to-be-exported API as part of URL paths. The request URL is of the following format: OpenAPI 677 Amazon API Gateway OpenAPI 3.0 Developer Guide https://<host>/restapis/<restapi_id>/stages/<stage_name>/exports/oas30 OpenAPI 2.0 https://<host>/restapis/<restapi_id>/stages/<stage_name>/exports/swagger You can append the extensions query string to specify whether to include API Gateway extensions (with the integration value) or Postman extensions (with the postman value). In addition, you can set the Accept header to application/json or application/yaml to receive the API definition output in JSON or YAML format, respectively. For more information about submitting GET requests using the API Gateway Export API, see GetExport. Note If you define models in your API, they must be for the content type of "application/json" for API Gateway to export the model. Otherwise, API Gateway throws an exception with the "Only found non-JSON body models for ..." error message. Models must contain properties or be defined as a particular JSONSchema type. Download REST API OpenAPI definition in JSON To export and download a REST API in OpenAPI definitions in JSON format: OpenAPI 3.0 GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30 Host: apigateway.<region>.amazonaws.com Accept: application/json OpenAPI 678 Amazon API Gateway Developer Guide OpenAPI 2.0 GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger Host: apigateway.<region>.amazonaws.com Accept: application/json Here, <region> could be, for example, us-east-1. For all the regions where API Gateway is available, see Regions and Endpoints. Download REST API OpenAPI definition in YAML To export and download a REST API in OpenAPI definitions in YAML format: OpenAPI 3.0 GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30 Host: apigateway.<region>.amazonaws.com Accept: application/yaml OpenAPI 2.0 GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger Host: apigateway.<region>.amazonaws.com Accept: application/yaml Download REST API OpenAPI definition with Postman extensions in JSON To export and download a REST API in OpenAPI definitions with Postman in JSON format: OpenAPI 679 Amazon API Gateway OpenAPI 3.0 Developer Guide GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30?extensions=postman Host: apigateway.<region>.amazonaws.com Accept: application/json OpenAPI 2.0 GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger?extensions=postman Host: apigateway.<region>.amazonaws.com Accept: application/json Download REST API OpenAPI definition with API Gateway integration in YAML To export and download a REST API in OpenAPI definitions with API Gateway integration in YAML format: OpenAPI 3.0 GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30?extensions=integrations Host: apigateway.<region>.amazonaws.com Accept: application/yaml OpenAPI 2.0 GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger? extensions=integrations Host: apigateway.<region>.amazonaws.com Accept: application/yaml OpenAPI 680 Amazon API Gateway Developer Guide Export REST API using the API Gateway console After deploying your REST API to a stage, you can proceed to export the API in the stage to an OpenAPI file using the API Gateway console. In the Stages pane in the API Gateway console, choose Stage actions, Export. Specify an API specification type, Format, and Extensions to download your API's OpenAPI definition. Publish REST APIs for customers to invoke Simply creating and developing an API Gateway API doesn't automatically make it callable by your users. To make it callable, you must deploy your API to a stage. In addition, you might want to customize the URL that your users will use to access your API. You can give it a
|
apigateway-dg-183
|
apigateway-dg.pdf
| 183 |
export the API in the stage to an OpenAPI file using the API Gateway console. In the Stages pane in the API Gateway console, choose Stage actions, Export. Specify an API specification type, Format, and Extensions to download your API's OpenAPI definition. Publish REST APIs for customers to invoke Simply creating and developing an API Gateway API doesn't automatically make it callable by your users. To make it callable, you must deploy your API to a stage. In addition, you might want to customize the URL that your users will use to access your API. You can give it a domain that is consistent with your brand or is more memorable than the default URL for your API. In this section, you can learn how to deploy your API and customize the URL that you provide to users to access it. Note To augment the security of your API Gateway APIs, the execute-api. {region}.amazonaws.com domain is registered in the Public Suffix List (PSL). For further security, we recommend that you use cookies with a __Host- prefix if you ever need to set sensitive cookies in the default domain name for your API Gateway APIs. This practice will help to defend your domain against cross-site request forgery attempts (CSRF). For more information see the Set-Cookie page in the Mozilla Developer Network. Topics Publish 681 Amazon API Gateway Developer Guide • Deploy REST APIs in API Gateway • Custom domain name for public REST APIs in API Gateway Deploy REST APIs in API Gateway After creating your API, you must deploy it to make it callable by your users. To deploy an API, you create an API deployment and associate it with a stage. A stage is a logical reference to a lifecycle state of your API (for example, dev, prod, beta, v2). API stages are identified by the API ID and stage name. They're included in the URL that you use to invoke the API. Each stage is a named reference to a deployment of the API and is made available for client applications to call. Important Every time you update an API, you must redeploy the API to an existing stage or to a new stage. Updating an API includes modifying routes, methods, integrations, authorizers, resource policies, and anything else other than stage settings. As your API evolves, you can continue to deploy it to different stages as different versions of the API. You can also deploy your API updates as a canary release deployment. This enables your API clients to access, on the same stage, the production version through the production release, and the updated version through the canary release. To call a deployed API, the client submits a request against an API's URL. The URL is determined by an API's protocol (HTTP(S) or (WSS)), hostname, stage name, and (for REST APIs) resource path. The hostname and the stage name determine the API's base URL. Using the API's default domain name, the base URL of a REST API (for example) in a given stage ({stageName}) is in the following format: https://{restapi-id}.execute-api.{region}.amazonaws.com/{stageName} To make the API's default base URL more user-friendly, you can create a custom domain name (for example, api.example.com) to replace the default hostname of the API. To support multiple APIs under the custom domain name, you must map an API stage to a base path. Deploy REST APIs 682 Amazon API Gateway Developer Guide With a custom domain name of {api.example.com} and the API stage mapped to a base path of ({basePath}) under the custom domain name, the base URL of a REST API becomes the following: https://{api.example.com}/{basePath} For each stage, you can optimize API performance by adjusting the default account-level request throttling limits and enabling API caching. You can also enable logging for API calls to CloudTrail or CloudWatch, and can select a client certificate for the backend to authenticate the API requests. In addition, you can override stage-level settings for individual methods and define stage variables to pass stage-specific environment contexts to the API integration at runtime. Stages enable robust version control of your API. For example, you can deploy an API to a test stage and a prod stage, and use the test stage as a test build and use the prod stage as a stable build. After the updates pass the test, you can promote the test stage to the prod stage. The promotion can be done by redeploying the API to the prod stage or updating a stage variable value from the stage name of test to that of prod. In this section, we discuss how to deploy an API by using the API Gateway console or calling the API Gateway REST API. To use other tools, see the documentation of the AWS CLI or an AWS SDK. Topics • Create a
|
apigateway-dg-184
|
apigateway-dg.pdf
| 184 |
as a test build and use the prod stage as a stable build. After the updates pass the test, you can promote the test stage to the prod stage. The promotion can be done by redeploying the API to the prod stage or updating a stage variable value from the stage name of test to that of prod. In this section, we discuss how to deploy an API by using the API Gateway console or calling the API Gateway REST API. To use other tools, see the documentation of the AWS CLI or an AWS SDK. Topics • Create a deployment for a REST API in API Gateway • Set up a stage for a REST API in API Gateway • Set up an API Gateway canary release deployment • Updates to REST APIs that require redeployment Create a deployment for a REST API in API Gateway In API Gateway, a REST API deployment is represented by a Deployment resource. It's similar to an executable of an API that is represented by a RestApi resource. For the client to call your API, you must create a deployment and associate a stage with it. A stage is represented by a Stage resource. It represents a snapshot of the API, including methods, integrations, models, mapping templates, and Lambda authorizers (formerly known as custom authorizers). When you update the API, you can redeploy the API by associating a new stage with the existing deployment. We discuss creating a stage in the section called “Set up a stage”. Deploy REST APIs 683 Amazon API Gateway Topics • Create a deployment • Next steps for your API deployment Create a deployment Developer Guide The following procedures show how to create a deployment for a REST API. AWS Management Console You must have created a REST API before deploying it for the first time. For more information, see Develop REST APIs in API Gateway. The API Gateway console lets you deploy an API by creating a deployment and associating it with a new or existing stage. 1. 2. 3. 4. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. In the APIs navigation pane, choose the API you want to deploy. In the Resources pane, choose Deploy API. For Stage, select from the following: a. b. c. To create a new stage, select New stage, and then enter a name in Stage name. Optionally, you can provide a description for the deployment in Deployment description. To choose an existing stage, select the stage name from the dropdown menu. You might want to provide a description of the new deployment in Deployment description. To create a deployment that is not associated with a stage, select No stage. Later, you can associate this deployment with a stage. 5. Choose Deploy. AWS CLI When you create a deployment, you instantiate the Deployment resource. The following create-deployment command creates a new deployment: Deploy REST APIs 684 Amazon API Gateway Developer Guide aws apigateway create-deployment --rest-api-id rest-api-id You can't call the API until you associate this deployment with a stage. With an existing stage, you can do this by updating the stage's deploymentId property with the newly created deployment ID. The following update-stage command updates the stage with a new deployment. In the console, this is called the Active deployment. aws apigateway update-stage \ --rest-api-id rest-api-id \ --stage-name 'stage-name' \ --patch-operations op='replace',path='/deploymentId',value='deployment-id' When you create your deployment, you can also associate it with a new stage at the same time. The following create-deployment command creates a new deployment and associates it with a new stage called beta: aws apigateway create-deployment \ --rest-api-id rest-api-id \ --stage-name beta To redeploy an API, perform the same steps. You can reuse the same stage. Next steps for your API deployment The following are next steps for your API deployment. Modify stage settings After an API is deployed, you can modify the stage settings to enable or disable the API cache, logging, or request throttling. You can also choose a client certificate for the backend to authenticate API Gateway and set stage variables to pass deployment context to the API integration at runtime. For more information, see Modify stage settings After modifying stage settings, you must redeploy the API for the changes to take effect. Note If the updated settings, such as enabling logging, requires a new IAM role, you can add the required IAM role without redeploying the API. However, it might take a few minutes Deploy REST APIs 685 Amazon API Gateway Developer Guide before the new IAM role takes effect. Before that happens, traces of your API calls are not logged even if you have enabled the logging option. Choose different deployment-stage combinations Because a deployment represents an API snapshot and a stage defines a path into a snapshot, you can choose different
|
apigateway-dg-185
|
apigateway-dg.pdf
| 185 |
redeploy the API for the changes to take effect. Note If the updated settings, such as enabling logging, requires a new IAM role, you can add the required IAM role without redeploying the API. However, it might take a few minutes Deploy REST APIs 685 Amazon API Gateway Developer Guide before the new IAM role takes effect. Before that happens, traces of your API calls are not logged even if you have enabled the logging option. Choose different deployment-stage combinations Because a deployment represents an API snapshot and a stage defines a path into a snapshot, you can choose different deployment-stage combinations to control how users call into different versions of the API. This is useful, for example, when you want to roll back API state to a previous deployment or to merge a 'private branch' of the API into the public one. The following procedure shows how to do this using the Stage Editor in the API Gateway console. It is assumed that you must have deployed an API more than once. 1. 2. If you're not already on the Stages pane, in the main navigation pane, choose Stages. Select the stage you want to update. 3. On the Deployment history tab, select the deployment you want the stage to use. 4. Choose Change active deployment. 5. Confirm you want to change the active deployment and choose Change active deployment in the Make active deployment dialog box. Pass deployment-specific data to your API. For a deployment, you can set or modify stage variables to pass deployment-specific data to the API integration at runtime. You can do this on the Stage Variables tab in the Stage Editor. For more information, see instructions in Use stage variables for a REST API in API Gateway. Set up a stage for a REST API in API Gateway A stage is a named reference to a deployment, which is a snapshot of the API. You use a Stage to manage and optimize a particular deployment. For example, you can configure stage settings to enable caching, customize request throttling, configure logging, define stage variables, or attach a canary release for testing. The following section shows how to create and configure your stage. Create a new stage After the initial deployment, you can add more stages and associate them with existing deployments. You can use the API Gateway console to create a new stage, or you can choose an Deploy REST APIs 686 Amazon API Gateway Developer Guide existing stage while deploying an API. In general, you can add a new stage to an API deployment before redeploying the API. To create a new stage using the API Gateway console, follow these steps: 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. 4. 5. 6. 7. In the main navigation pane, choose Stages under an API. From the Stages navigation pane, choose Create stage. For Stage name, enter a name, for example, prod. Note Stage names can only contain alphanumeric characters, hyphens, and underscores. Maximum length is 128 characters. (Optional). For Description, enter a stage description. For Deployment, select the date and time of the existing API deployment you want to associate with this stage. 8. Under Additional settings, you can specify additional settings for your stage. 9. Choose Create stage. Modify stage settings After a successful deployment of an API, the stage is populated with default settings. You can use the console or the API Gateway REST API to change the stage settings, including API caching and logging. The following steps show you how to do so using the Stage editor of the API Gateway console. 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. 4. 5. 6. 7. In the main navigation pane, choose Stages under an API. In the Stages pane, choose the name of the stage. In the Stage details section, choose Edit. (Optional) For Stage description, edit the description. For Additional settings, you modify the following settings: Deploy REST APIs 687 Amazon API Gateway Cache settings Developer Guide To enable API caching for the stage, turn on Provision API cache. Then configure the Default method-level caching, Cache capacity, Encrypt cache data, Cache time-to-live (TTL), as well as any requirements for per-key cache invalidation. Caching is not active until you turn on the default method-level caching or turn on the method-level cache for a specific method. For more information about cache settings, see Cache settings for REST APIs in API Gateway. Note If you enable API caching for an API stage, your AWS account might be charged for API caching. Caching isn't eligible for the AWS Free Tier. Throttling settings To set stage-level throttling targets for all of the methods associated with this API, turn on Throttling. For
|
apigateway-dg-186
|
apigateway-dg.pdf
| 186 |
capacity, Encrypt cache data, Cache time-to-live (TTL), as well as any requirements for per-key cache invalidation. Caching is not active until you turn on the default method-level caching or turn on the method-level cache for a specific method. For more information about cache settings, see Cache settings for REST APIs in API Gateway. Note If you enable API caching for an API stage, your AWS account might be charged for API caching. Caching isn't eligible for the AWS Free Tier. Throttling settings To set stage-level throttling targets for all of the methods associated with this API, turn on Throttling. For Rate, enter a target rate. This is the rate, in requests per second, that tokens are added to the token bucket. The stage-level rate must not be more than the account-level rate as specified in Quotas for configuring and running a REST API in API Gateway. For Burst, enter a target burst rate. The burst rate, is the capacity of the token bucket. This allows more requests through for a period of time than the target rate. This stage-level burst rate must not be more than the account-level burst rate as specified in Quotas for configuring and running a REST API in API Gateway. Note Throttling rates are not hard limits, and are applied on a best-effort basis. In some cases, clients can exceed the targets that you set. Don’t rely on throttling to control Deploy REST APIs 688 Amazon API Gateway Developer Guide costs or block access to an API. Consider using AWS Budgets to monitor costs and AWS WAF to manage API requests. Firewall and certificate settings To associate an AWS WAF web ACL with the stage, select a web ACL from the Web ACL dropdown list. If desired, choose Block API Request if WebACL cannot be evaluated (Fail- Close). To select a client certificate for your stage, select a certificate from the Client certificate dropdown menu. 8. Choose Continue. 9. Review your changes and choose Save changes. 10. To enable Amazon CloudWatch Logs for all of the methods associated with this stage of this API Gateway API, in the Logs and tracing section, choose Edit. Note To enable CloudWatch Logs, you must also specify the ARN of an IAM role that enables API Gateway to write information to CloudWatch Logs on behalf of your user. To do so, choose Settings from the APIs main navigation pane. Then, for CloudWatch log role, enter the ARN of an IAM role. For common application scenarios, the IAM role could attach the managed policy of AmazonAPIGatewayPushToCloudWatchLogs. The IAM role must also contain the following trust relationship statement: { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "apigateway.amazonaws.com" }, "Action": "sts:AssumeRole" } ] Deploy REST APIs 689 Amazon API Gateway } Developer Guide For more information about CloudWatch, see the Amazon CloudWatch User Guide. 11. Select a logging level from the CloudWatch Logs dropdown menu. The logging levels are the following: • Off – Logging is not turned on for this stage. • Errors only – Logging is enabled for errors only. • Errors and info logs – Logging is enabled for all events. 12. Select Data tracing to have API Gateway report to CloudWatch the data trace logging for your stage. This can be useful to troubleshoot APIs, but can result in logging sensitive data. Note We recommend that you don't use Data tracing for production APIs. 13. Select Detailed metrics to have API Gateway report to CloudWatch the API metrics of API calls, Latency, Integration latency, 400 errors, and 500 errors. For more information about CloudWatch, see the Basic monitoring and detailed monitoring in the Amazon CloudWatch User Guide. Important Your account is charged for accessing method-level CloudWatch metrics, but not the API-level or stage-level metrics. 14. To enable access logging to a destination, turn on Custom access logging. 15. For Access log destination ARN, enter the ARN of a log group or a Firehose stream. The ARN format for Firehose is arn:aws:firehose:{region}:{account- id}:deliverystream/amazon-apigateway-{your-stream-name}. The name of your Firehose stream must be amazon-apigateway-{your-stream-name}. 16. In Log format, enter a log format. To learn more about example log formats, see the section called “CloudWatch log formats for API Gateway”. 17. To enable AWS X-Ray tracing for the API stage, select X-Ray tracing. For more information, see Trace user requests to REST APIs using X-Ray in API Gateway. Deploy REST APIs 690 Amazon API Gateway Developer Guide 18. Choose Save changes. Redeploy your API for the new settings to take effect. Override stage-level settings After you customize the stage-level settings, you can override them for each API method. Some of these options might result in additional charges to your AWS account. 1. To configure method overrides, expand the stage under the secondary navigation pane, and then choose a
|
apigateway-dg-187
|
apigateway-dg.pdf
| 187 |
API Gateway”. 17. To enable AWS X-Ray tracing for the API stage, select X-Ray tracing. For more information, see Trace user requests to REST APIs using X-Ray in API Gateway. Deploy REST APIs 690 Amazon API Gateway Developer Guide 18. Choose Save changes. Redeploy your API for the new settings to take effect. Override stage-level settings After you customize the stage-level settings, you can override them for each API method. Some of these options might result in additional charges to your AWS account. 1. To configure method overrides, expand the stage under the secondary navigation pane, and then choose a method. 2. 3. For Method overrides, choose Edit. To turn on method-level CloudWatch settings, for CloudWatch Logs, select a logging level. Deploy REST APIs 691 Amazon API Gateway Developer Guide 4. To turn on data trace logging for your method, select Data tracing. Note We recommend that you don't use Data tracing for production APIs. 5. 6. 7. To turn on method-level detailed metrics, select Detailed metrics. Your account is charged for accessing method-level CloudWatch metrics, but not the API-level or stage-level metrics. To turn on method-level throttling, select Throttling. Enter the appropriate method-level options. To learn more about throttling, see the section called “Throttling”. To configure the method-level cache, select Enable method cache. If you change the default method-level caching setting in the Stage details, it doesn't affect this setting. 8. Choose Save. Delete a stage When you no longer need a stage, you can delete it to avoid paying for unused resources. The following steps show you how to use the API Gateway console to delete a stage. Warning Deleting a stage might cause part or all of the corresponding API to be unusable by API callers. Deleting a stage cannot be undone, but you can recreate the stage and associate it with the same deployment. 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. 4. In the main navigation pane, choose Stages. In the Stages pane, choose the stage you want to delete, and then choose Stage actions, Delete stage. 5. When you're prompted, enter confirm, and then choose Delete. Deploy REST APIs 692 Amazon API Gateway Developer Guide Set up tags for an API stage in API Gateway In API Gateway, you can add a tag to an API stage, remove the tag from the stage, or view the tag. To do this, you can use the API Gateway console, the AWS CLI/SDK, or the API Gateway REST API. A stage can also inherit tags from its parent REST API. For more information, see the section called “Tag inheritance in the Amazon API Gateway V1 API”. For more information about tagging API Gateway resources, see Tagging. Topics • Set up tags for an API stage using the API Gateway console • Set up tags for an API stage using the AWS CLI • Set up tags for an API stage using the API Gateway REST API Set up tags for an API stage using the API Gateway console The following procedure describes how to set up tags for an API stage. To set up tags for an API stage by using the API Gateway console 1. Sign in to the API Gateway console. 2. Choose an existing API, or create a new API that includes resources, methods, and the corresponding integrations. 3. Choose a stage or deploy the API to a new stage. 4. In the main navigation pane, choose Stages. 5. Choose the Tags tab. You might need to choose the right arrow button to show the tab. 6. Choose Manage tags. 7. In the Tag Editor, choose Add tag. Enter a tag key (for example, Department) in the Key field, and enter a tag value (for example, Sales) in the Value field. Choose Save to save the tag. 8. If needed, repeat step 5 to add more tags to the API stage. The maximum number of tags per stage is 50. 9. To remove an existing tag from the stage, choose Remove. 10. If the API has been deployed previously in the API Gateway console, you need to redeploy it for the changes to take effect. Deploy REST APIs 693 Amazon API Gateway Developer Guide Set up tags for an API stage using the AWS CLI You can set up tags for an API stage using the AWS CLI using the create-stage command or the tag- resource command. You can delete one or more tags from an API stage using the untag-resource command. The following create-stage command adds a tag when creating a test stage: aws apigateway create-stage --rest-api-id abc1234 --stage-name test --description 'Testing stage' --deployment-id efg456 --tag Department=Sales The following tag-resource command adds a tag to a prod stage: aws apigateway tag-resource --resource-arn arn:aws:apigateway:us-east-2::/ restapis/abc123/stages/prod --tags
|
apigateway-dg-188
|
apigateway-dg.pdf
| 188 |
REST APIs 693 Amazon API Gateway Developer Guide Set up tags for an API stage using the AWS CLI You can set up tags for an API stage using the AWS CLI using the create-stage command or the tag- resource command. You can delete one or more tags from an API stage using the untag-resource command. The following create-stage command adds a tag when creating a test stage: aws apigateway create-stage --rest-api-id abc1234 --stage-name test --description 'Testing stage' --deployment-id efg456 --tag Department=Sales The following tag-resource command adds a tag to a prod stage: aws apigateway tag-resource --resource-arn arn:aws:apigateway:us-east-2::/ restapis/abc123/stages/prod --tags Department=Sales The following untag-resource command removes the Department=Sales tag from the test stage: aws apigateway untag-resource --resource-arn arn:aws:apigateway:us-east-2::/ restapis/abc123/stages/test --tag-keys Department Set up tags for an API stage using the API Gateway REST API You can set up tags for an API stage using the API Gateway REST API by doing one of the following: • Call tags:tag to tag an API stage. • Call tags:untag to delete one or more tags from an API stage. • Call stage:create to add one or more tags to an API stage that you're creating. You can also call tags:get to describe tags in an API stage. Tag an API stage After you deploy an API (m5zr3vnks7) to a stage (test), tag the stage by calling tags:tag. The required stage Amazon Resource Name (ARN) (arn:aws:apigateway:us-east-1::/ restapis/m5zr3vnks7/stages/test) must be URL encoded (arn%3Aaws%3Aapigateway %3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages%2Ftest). Deploy REST APIs 694 Amazon API Gateway Developer Guide PUT /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages %2Ftest { "tags" : { "Department" : "Sales" } } You can also use the previous request to update an existing tag to a new value. You can add tags to a stage when calling stage:create to create the stage: POST /restapis/<restapi_id>/stages { "stageName" : "test", "deploymentId" : "adr134", "description" : "test deployment", "cacheClusterEnabled" : "true", "cacheClusterSize" : "500", "variables" : { "sv1" : "val1" }, "documentationVersion" : "test", "tags" : { "Department" : "Sales", "Division" : "Retail" } } Untag an API stage To remove the Department tag from the stage, call tags:untag: DELETE /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages %2Ftest?tagKeys=Department Host: apigateway.us-east-1.amazonaws.com Authorization: ... Deploy REST APIs 695 Amazon API Gateway Developer Guide To remove more than one tag, use a comma-separated list of tag keys in the query expression—for example, ?tagKeys=Department,Division,…. Describe tags for an API stage To describe existing tags on a given stage, call tags:get: GET /tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fm5zr3vnks7%2Fstages %2Ftags Host: apigateway.us-east-1.amazonaws.com Authorization: ... The successful response is similar to the following: 200 OK { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/ restapi-tags-{rel}.html", "name": "tags", "templated": true }, "tags:tag": { "href": "/tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis %2Fm5zr3vnks7%2Fstages%2Ftags" }, "tags:untag": { "href": "/tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis %2Fm5zr3vnks7%2Fstages%2Ftags{?tagKeys}", "templated": true } }, "tags": { "Department": "Sales" } } Use stage variables for a REST API in API Gateway Stage variables are key-value pairs that you can define as configuration attributes associated with a deployment stage of a REST API. They act like environment variables and can be used in your API Deploy REST APIs 696 Amazon API Gateway Developer Guide setup and mapping templates. With deployment stages in API Gateway, you can manage multiple release stages for each API and use stage variables you can configure an API deployment stage to interact with different backend endpoints. Stage variables are not intended to be used for sensitive data, such as credentials. To pass sensitive data to integrations, use an AWS Lambda authorizer. You can pass sensitive data to integrations in the output of the Lambda authorizer. To learn more, see the section called “Output from an API Gateway Lambda authorizer”. Use cases for stage variables The following are use cases for your stage variables. Specify a different backend endpoint Your API can pass a GET request as an HTTP proxy to the backend web host. You can use a stage variable so that when API callers invoke your production endpoint, API Gateway calls example.com. Then, when API callers invoke the beta stage, API Gateway calls a different web host, such as beta.example.com. Similarly, stage variables can be used to specify a different AWS Lambda function name for each stage in your API. You can't use a stage variable to set a different integration endpoint, such as pointing the GET request to an HTTP proxy integration in one stage and a Lambda proxy integration in another stage. When specifying a Lambda function name as a stage variable value, you must configure the permissions on the Lambda function manually. When you specify a Lambda function in the API Gateway console, a AWS CLI command will pop-up to configure the proper permissions. You can also use the following AWS CLI command to do this. aws lambda add-permission --function-name "arn:aws:lambda:us- east-2:123456789012:function:my-function" --source-arn "arn:aws:execute- api:us-east-2:123456789012:api_id/*/HTTP_METHOD/resource" --principal apigateway.amazonaws.com --statement-id apigateway-access --action lambda:InvokeFunction Pass information using mapping templates You can access stage variables in the mapping templates, or pass configuration
|
apigateway-dg-189
|
apigateway-dg.pdf
| 189 |
proxy integration in one stage and a Lambda proxy integration in another stage. When specifying a Lambda function name as a stage variable value, you must configure the permissions on the Lambda function manually. When you specify a Lambda function in the API Gateway console, a AWS CLI command will pop-up to configure the proper permissions. You can also use the following AWS CLI command to do this. aws lambda add-permission --function-name "arn:aws:lambda:us- east-2:123456789012:function:my-function" --source-arn "arn:aws:execute- api:us-east-2:123456789012:api_id/*/HTTP_METHOD/resource" --principal apigateway.amazonaws.com --statement-id apigateway-access --action lambda:InvokeFunction Pass information using mapping templates You can access stage variables in the mapping templates, or pass configuration parameters to your AWS Lambda or HTTP backend. For example, you might want to reuse the same Lambda function for multiple stages in your API, but the function should read data from a different Amazon DynamoDB table depending on the stage. In the mapping templates that generate Deploy REST APIs 697 Amazon API Gateway Developer Guide the request for the Lambda function, you can use stage variables to pass the table name to Lambda. To use a stage variable, you first configure a stage variable, and then you assign it a value. For example, to customize the HTTP integration endpoint, first create the url stage variable, and then in your API's integration request, enter the stage variable value, http:// ${stageVariables.url}. This value tells API Gateway to substitute your stage variable ${} at runtime, depending on which stage your API is running. For more information, see the section called “Set up stage variables for REST APIs in API Gateway”. Set up stage variables for REST APIs in API Gateway This section shows how to set up various stage variables for two deployment stages of a sample API by using the Amazon API Gateway console. To understand how to use stage variables in API Gateway, we recommend that you follow all procedures in this section. Prerequisites Before you begin, make sure the following prerequisites are met: • You must have an API available in API Gateway. Follow the instructions in Develop REST APIs in API Gateway. • You must have deployed the API at least once. Follow the instructions in Deploy REST APIs in API Gateway. • You must have created the first stage for a deployed API. Follow the instructions in Create a new stage. Invoke an HTTP endpoint through an API with a stage variable This procedure describes how to create a stage variable for an HTTP endpoint and two stages for your API. In addition, you create the stage variables, url, stageName, and function that are used in the following procedures in this section. To invoke an HTTP endpoint through an API with a stage variable 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Create an API, and then create a GET method on the API's root resource. Set the integration type to HTTP and set the Endpoint URL to http://${stageVariables.url}. Deploy REST APIs 698 Amazon API Gateway Developer Guide 3. Deploy the API to a new stage named beta. 4. In the main navigation pane, choose Stages, and then select the beta stage. 5. On the Stage variables tab, choose Edit. 6. Choose Add stage variable. 7. For Name, enter url. For value, enter httpbin.org/get. 8. Choose Add stage variable, and then do the following: For Name, enter stageName. For value, enter beta. 9. Choose Add stage variable, and then do the following: For Name, enter function. For value, enter HelloWorld. 10. Choose Save. 11. Now create a second stage. From the Stages navigation pane, choose Create stage. For Stage name, enter prod. Select a recent deployment from Deployment, and then choose Create stage. 12. As with the beta stage, set the same three stage variables (url, stageName, and function) to different values (petstore-demo-endpoint.execute-api.com/petstore/pets, prod, and HelloEveryone), respectively. 13. In the Stages navigation pane, choose beta. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. This starts the beta stage GET request on the root resource of the API. Note The Invoke URL link points to the root resource of the API in its beta stage. Entering the URL in a web browser calls the beta stage GET method on the root resource. If methods are defined on child resources and not on the root resource itself, entering the URL in a web browser returns a {"message":"Missing Authentication Token"} error response. In this case, you must append the name of a specific child resource to the Invoke URL link. 14. The response you get from the beta stage GET request is shown next. You can also verify the result by using a browser to navigate to http://httpbin.org/get. This value was assigned to the url variable in the beta stage. The
|
apigateway-dg-190
|
apigateway-dg.pdf
| 190 |
a web browser calls the beta stage GET method on the root resource. If methods are defined on child resources and not on the root resource itself, entering the URL in a web browser returns a {"message":"Missing Authentication Token"} error response. In this case, you must append the name of a specific child resource to the Invoke URL link. 14. The response you get from the beta stage GET request is shown next. You can also verify the result by using a browser to navigate to http://httpbin.org/get. This value was assigned to the url variable in the beta stage. The two responses are identical. Deploy REST APIs 699 Amazon API Gateway Developer Guide 15. In the Stages navigation pane, choose the prod stage. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. This starts the prod stage GET request on the root resource of the API. 16. The response you get from the prod stage GET request is shown next. You can verify the result by using a browser to navigate to http://petstore-demo-endpoint.execute-api.com/ petstore/pets. This value was assigned to the url variable in the prod stage. The two responses are identical. Pass stage-specific metadata into an HTTP backend This procedure describes how to use a stage variable value in a query parameter expression to pass stage-specific metadata into an HTTP backend. We will use the stageName stage variable declared in the previous procedure. To pass stage-specific metadata into an HTTP backend 1. In the Resource navigation pane, choose the GET method. To add a query string parameter to the method's URL, choose the Method request tab, and then in the Method request settings section, choose Edit. 2. Choose URL query string parameters and do the following: a. b. c. Choose Add query string. For Name, enter stageName. Keep Required and Caching turned off. 3. Choose Save. 4. Choose the Integration request tab, and then in the Integration request settings section, choose Edit. 5. For Endpoint URL, append ?stageName=${stageVariables.stageName} to the previously defined URL value, so the entire Endpoint URL is http:// ${stageVariables.url}?stageName=${stageVariables.stageName}. 6. Choose Deploy API and select the beta stage. 7. In the main navigation pane, choose Stages. In the Stages navigation pane, choose beta. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. Deploy REST APIs 700 Amazon API Gateway Note Developer Guide We use the beta stage here because the HTTP endpoint (as specified by the url variable "http://httpbin.org/get") accepts query parameter expressions and returns them as the args object in its response. 8. You get the following response. Notice that beta, assigned to the stageName stage variable, is passed in the backend as the stageName argument. Invoke a Lambda function through an API with a stage variable This procedure describes how to use a stage variable to call a Lambda function as a backend of your API. You use the function stage variable declared in Invoke an HTTP endpoint through an API with a stage variable. When setting a Lambda function as the value of a stage variable, use the function's local name, possibly including its alias or version specification, as in HelloWorld, HelloWorld:1 or HelloWorld:alpha. Do not use the function's ARN (for example, arn:aws:lambda:us- east-1:123456789012:function:HelloWorld). The API Gateway console assumes the stage variable value for a Lambda function as the unqualified function name and expands the given stage variable into an ARN. To invoke a Lambda function through an API with a stage variable 1. Create a Lambda function named HelloWorld using the default Node.js runtime. The code must contain the following: Deploy REST APIs 701 Amazon API Gateway Developer Guide export const handler = function(event, context, callback) { if (event.stageName) callback(null, 'Hello, World! I\'m calling from the ' + event.stageName + ' stage.'); else callback(null, 'Hello, World! I\'m not sure where I\'m calling from...'); }; For more information on how to create a Lambda function, see Getting started with the REST API console. 2. In the Resources pane, select Create resource, and then do the following: a. b. c. For Resource path, select /. For Resource name, enter lambdav1. Choose Create resource. 3. Choose the /lambdav1 resource, and then choose Create method. Then, do the following: a. b. c. d. For Method type, select GET. For Integration type, select Lambda function. Keep Lambda proxy integration turned off. For Lambda function, enter ${stageVariables.function}. Tip When prompted with the Add permission command, copy the add-permission command. Run the command on each Lambda function that will be assigned to the function stage variable. For example, if the $stageVariables.function value is HelloWorld, run the following AWS CLI command: Deploy REST APIs 702 Amazon API Gateway Developer Guide aws
|
apigateway-dg-191
|
apigateway-dg.pdf
| 191 |
For Resource name, enter lambdav1. Choose Create resource. 3. Choose the /lambdav1 resource, and then choose Create method. Then, do the following: a. b. c. d. For Method type, select GET. For Integration type, select Lambda function. Keep Lambda proxy integration turned off. For Lambda function, enter ${stageVariables.function}. Tip When prompted with the Add permission command, copy the add-permission command. Run the command on each Lambda function that will be assigned to the function stage variable. For example, if the $stageVariables.function value is HelloWorld, run the following AWS CLI command: Deploy REST APIs 702 Amazon API Gateway Developer Guide aws lambda add-permission --function-name arn:aws:lambda:us- east-1:account-id:function:HelloWorld --source-arn arn:aws:execute- api:us-east-1:account-id:api-id/*/GET/lambdav1 --principal apigateway.amazonaws.com --statement-id statement-id-guid --action lambda:InvokeFunction Failing to do so results in a 500 Internal Server Error response when invoking the method. Replace ${stageVariables.function} with the Lambda function name that is assigned to the stage variable. e. Choose Create method. 4. Deploy the API to both the prod and beta stages. 5. In the main navigation pane, choose Stages. In the Stages navigation pane, choose beta. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in a web browser. Append /lambdav1 to the URL before you press enter. You get the following response. "Hello, World! I'm not sure where I'm calling from..." Deploy REST APIs 703 Amazon API Gateway Developer Guide Pass stage-specific metadata to a Lambda function through a stage variable This procedure describes how to use a stage variable to pass stage-specific configuration metadata into a Lambda function. You create a POST method and an input mapping template to generate payload using the stageName stage variable you declared earlier. To pass stage-specific metadata to a Lambda function through a stage variable 1. Choose the /lambdav1 resource, and then choose Create method. Then, do the following: a. b. c. d. For Method type, select POST. For Integration type, select Lambda function. Keep Lambda proxy integration turned off. For Lambda function, enter ${stageVariables.function}. e. When prompted with the Add permission command, copy the the add-permission command. Run the command on each Lambda function that will be assigned to the function stage variable. f. Choose Create method. 2. Choose the Integration request tab, and then in the Integration request settings section, choose Edit. 3. Choose Mapping templates, and then choose Add mapping template. 4. 5. For Content type, enter application/json. For Template body, enter the following template: #set($inputRoot = $input.path('$')) { "stageName" : "$stageVariables.stageName" } Note In a mapping template, a stage variable must be referenced within quotes (as in "$stageVariables.stageName" or "${stageVariables.stageName}"). In other places, it must be referenced without quotes (as in ${stageVariables.function}). Deploy REST APIs 704 Amazon API Gateway 6. Choose Save. Developer Guide 7. Deploy the API to both the beta and prod stages. 8. To use a REST API client to pass stage-specific metadata, do the following: a. In the Stages navigation pane, choose beta. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in the input field of a REST API client. Append /lambdav1 before you submit your request. You get the following response. "Hello, World! I'm calling from the beta stage." b. In the Stages navigation pane, choose prod. Under Stage details, choose the copy icon to copy your API's invoke URL, and then enter your API's invoke URL in the input field of a REST API client. Append /lambdav1 before you submit your request. You get the following response. "Hello, World! I'm calling from the prod stage." 9. To use the Test feature to pass stage-specific metadata, do the following: a. b. c. In the Resources navigation pane, choose the Test tab. You might need to choose the right arrow button to show the tab. For function, enter HelloWorld. For stageName, enter beta. d. Choose Test. You do not need to add a body to your POST request. You get the following response. "Hello, World! I'm calling from the beta stage." e. You can repeat the previous steps to test the Prod stage. For stageName, enter Prod. You get the following response. "Hello, World! I'm calling from the prod stage." Deploy REST APIs 705 Amazon API Gateway Developer Guide API Gateway stage variables reference for REST APIs in API Gateway You can use API Gateway stage variables in the following cases. Parameter mapping expressions A stage variable can be used in a parameter mapping expression for an API method's request or response header parameter, without any partial substitution. In the following example, the stage variable is referenced without the $ and the enclosing {...}. • stageVariables.<variable_name> Mapping templates A stage variable can be used anywhere in a mapping template, as shown in the following examples. • { "name" : "$stageVariables.<variable_name>"} • { "name"
|
apigateway-dg-192
|
apigateway-dg.pdf
| 192 |
705 Amazon API Gateway Developer Guide API Gateway stage variables reference for REST APIs in API Gateway You can use API Gateway stage variables in the following cases. Parameter mapping expressions A stage variable can be used in a parameter mapping expression for an API method's request or response header parameter, without any partial substitution. In the following example, the stage variable is referenced without the $ and the enclosing {...}. • stageVariables.<variable_name> Mapping templates A stage variable can be used anywhere in a mapping template, as shown in the following examples. • { "name" : "$stageVariables.<variable_name>"} • { "name" : "${stageVariables.<variable_name>}"} HTTP integration URIs A stage variable can be used as part of an HTTP integration URL, as shown in the following examples: • A full URI without protocol – http://${stageVariables.<variable_name>} • A full domain – http://${stageVariables.<variable_name>}/resource/operation • A subdomain – http://${stageVariables.<variable_name>}.example.com/ resource/operation • A path – http://example.com/${stageVariables.<variable_name>}/bar • A query string – http://example.com/foo?q=${stageVariables.<variable_name>} AWS integration URIs A stage variable can be used as part of AWS URI action or path components, as shown in the following example. • arn:aws:apigateway:<region>:<service>:${stageVariables.<variable_name>} Deploy REST APIs 706 Amazon API Gateway Developer Guide AWS integration URIs (Lambda functions) A stage variable can be used in place of a Lambda function name, or version/alias, as shown in the following examples. • arn:aws:apigateway:<region>:lambda:path/2015-03-31/ functions/arn:aws:lambda:<region>:<account_id>:function: ${stageVariables.<function_variable_name>}/invocations • arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/ arn:aws:lambda:<region>:<account_id>:function:<function_name>: ${stageVariables.<version_variable_name>}/invocations Note To use a stage variable for a Lambda function, the function must be in the same account as the API. Stage variables don't support cross-account Lambda functions. Amazon Cognito user pool A stage variable can be used in place of a Amazon Cognito user pool for a COGNITO_USER_POOLS authorizer. • arn:aws:cognito-idp:<region>:<account_id>:userpool/ ${stageVariables.<variable_name>} AWS integration credentials A stage variable can be used as part of AWS user/role credential ARN, as shown in the following example. • arn:aws:iam::<account_id>:${stageVariables.<variable_name>} Set up an API Gateway canary release deployment Canary release is a software development strategy in which a new version of an API (as well as other software) is deployed for testing purposes, and the base version remains deployed as a production release for normal operations on the same stage. For purposes of discussion, we refer Deploy REST APIs 707 Amazon API Gateway Developer Guide to the base version as a production release in this documentation. Although this is reasonable, you are free to apply canary release on any non-production version for testing. In a canary release deployment, total API traffic is separated at random into a production release and a canary release with a pre-configured ratio. Typically, the canary release receives a small percentage of API traffic and the production release takes up the rest. The updated API features are only visible to API traffic through the canary. You can adjust the canary traffic percentage to optimize test coverage or performance. By keeping canary traffic small and the selection random, most users are not adversely affected at any time by potential bugs in the new version, and no single user is adversely affected all the time. After the test metrics pass your requirements, you can promote the canary release to the production release and disable the canary from the deployment. This makes the new features available in the production stage. Topics • Canary release deployment in API Gateway • Create a canary release deployment • Update a canary release • Promote a canary release • Turn off a canary release Canary release deployment in API Gateway In API Gateway, a canary release deployment uses the deployment stage for the production release of the base version of an API, and attaches to the stage a canary release for the new versions, relative to the base version, of the API. The stage is associated with the initial deployment and the canary with subsequent deployments. At the beginning, both the stage and the canary point to the same API version. We use stage and production release interchangeably and use canary and canary release interchangeably throughout this section. To deploy an API with a canary release, you create a canary release deployment by adding canary settings to the stage of a regular deployment. The canary settings describe the underlying canary release and the stage represents the production release of the API within this deployment. To add canary settings, set canarySettings on the deployment stage and specify the following: • A deployment ID, initially identical to the ID of the base version deployment set on the stage. Deploy REST APIs 708 Amazon API Gateway Developer Guide • A percentage of API traffic, between 0.0 and 100.0 inclusive, for the canary release. • Stage variables for the canary release that can override production release stage variables. • The use of the stage cache for canary requests, if the useStageCache is set and API caching is enabled on the stage. After a canary release is
|
apigateway-dg-193
|
apigateway-dg.pdf
| 193 |
this deployment. To add canary settings, set canarySettings on the deployment stage and specify the following: • A deployment ID, initially identical to the ID of the base version deployment set on the stage. Deploy REST APIs 708 Amazon API Gateway Developer Guide • A percentage of API traffic, between 0.0 and 100.0 inclusive, for the canary release. • Stage variables for the canary release that can override production release stage variables. • The use of the stage cache for canary requests, if the useStageCache is set and API caching is enabled on the stage. After a canary release is enabled, the deployment stage cannot be associated with another non- canary release deployment until the canary release is disabled and the canary settings removed from the stage. When you enable API execution logging, the canary release has its own logs and metrics generated for all canary requests. They are reported to a production stage CloudWatch Logs log group as well as a canary-specific CloudWatch Logs log group. The same applies to access logging. The separate canary-specific logs are helpful to validate new API changes and decide whether to accept the changes and promote the canary release to the production stage, or to discard the changes and revert the canary release from the production stage. The production stage execution log group is named API-Gateway-Execution-Logs/{rest- api-id}/{stage-name} and the canary release execution log group is named API-Gateway- Execution-Logs/{rest-api-id}/{stage-name}/Canary. For access logging, you must create a new log group or choose an existing one. The canary release access log group name has the /Canary suffix appended to the selected log group name. A canary release can use the stage cache, if enabled, to store responses and use cached entries to return results to the next canary requests, within a pre-configured time-to-live (TTL) period. In a canary release deployment, the production release and canary release of the API can be associated with the same version or with different versions. When they are associated with different versions, responses for production and canary requests are cached separately and the stage cache returns corresponding results for production and canary requests. When the production release and canary release are associated with the same deployment, the stage cache uses a single cache key for both types of requests and returns the same response for the same requests from the production release and canary release. Create a canary release deployment You create a canary release deployment when deploying the API with canary settings as an additional input to the deployment creation operation. Deploy REST APIs 709 Amazon API Gateway Developer Guide You can also create a canary release deployment from an existing non-canary deployment by making a stage:update request to add the canary settings on the stage. When creating a non-canary release deployment, you can specify a non-existing stage name. API Gateway creates one if the specified stage does not exist. However, you cannot specify any non- existing stage name when creating a canary release deployment. You will get an error and API Gateway will not create any canary release deployment. You can create a canary release deployment in API Gateway using the API Gateway console, the AWS CLI, or an AWS SDK. Topics • Create a canary deployment using the API Gateway console • Create a canary deployment using the AWS CLI Create a canary deployment using the API Gateway console To use the API Gateway console to create a canary release deployment, follow the instructions below: To create the initial canary release deployment 1. Sign in to the API Gateway console. 2. Choose an existing REST API or create a new REST API. 3. In the main navigation pane, choose Resources, and then choose Deploy API. Follow the on- screen instructions in Deploy API to deploy the API to a new stage. So far, you have deployed the API to a production release stage. Next, you configure canary settings on the stage and, if needed, also enable caching, set stage variables, or configure API execution or access logs. 4. To enable API caching or associate an AWS WAF web ACL with the stage, in the Stage details section, choose Edit. For more information, see the section called “Cache settings” or the section called “To associate an AWS WAF web ACL with an API Gateway API stage using the API Gateway console”. 5. To configure execution or access logging, in the Logs and tracing section, choose Edit and follow the on-screen instructions. For more information, see Set up CloudWatch logging for REST APIs in API Gateway. Deploy REST APIs 710 Amazon API Gateway Developer Guide 6. To set stage variables, choose the Stage variables tab and follow the on-screen instructions to add or modify stage variables. For more information, see the section called “Use stage variables”. 7. Choose the Canary
|
apigateway-dg-194
|
apigateway-dg.pdf
| 194 |
or the section called “To associate an AWS WAF web ACL with an API Gateway API stage using the API Gateway console”. 5. To configure execution or access logging, in the Logs and tracing section, choose Edit and follow the on-screen instructions. For more information, see Set up CloudWatch logging for REST APIs in API Gateway. Deploy REST APIs 710 Amazon API Gateway Developer Guide 6. To set stage variables, choose the Stage variables tab and follow the on-screen instructions to add or modify stage variables. For more information, see the section called “Use stage variables”. 7. Choose the Canary tab, and then choose Create canary. You might need to choose the right arrow button to show the Canary tab. 8. Under Canary settings, for Canary, enter the percentage of requests to be diverted to the canary. 9. If desired, select Stage cache to turn on caching for the canary release. The cache is not available for the canary release until API caching is enabled. 10. To override existing stage variables, for Canary override, enter a new stage variable value. After the canary release is initialized on the deployment stage, you change the API and want to test the changes. You can redeploy the API to the same stage so that both the updated version and the base version are accessible through the same stage. The following steps describe how to do that. To deploy the latest API version to a canary 1. With each update of the API, choose Deploy API. 2. In Deploy API, choose the stage that contains a canary from the Deployment stage dropdown list. 3. (Optional) Enter a description for Deployment description. 4. Choose Deploy to push the latest API version to the canary release. 5. If desired, reconfigure the stage settings, logs, or canary settings, as describe in To create the initial canary release deployment. As a result, the canary release points to the latest version while the production release still points to the initial version of the API. The canarySettings now has a new deploymentId value, whereas the stage still has the initial deploymentId value. Behind the scenes, the console calls stage:update. Deploy REST APIs 711 Amazon API Gateway Developer Guide Create a canary deployment using the AWS CLI To create a canary deployment for a new stage 1. Use the following create-deployment command to create a deployment with two stage variables, but without a canary: aws apigateway create-deployment \ --variables sv0=val0,sv1=val1 \ --rest-api-id abcd1234 \ --stage-name 'prod' The output will look like the following: { "id": "du4ot1", "createdDate": 1511379050 } 2. Use the following create-deployment command to create a canary deployment on the prod stage: aws apigateway create-deployment \ --rest-api-id abcd1234 \ --canary-settings percentTraffic=10.5,stageVariableOverrides={sv1='val2',sv2='val3'},useStageCache=false \ --stage-name 'prod' The output will look like the following: { "id": "a6rox0", "createdDate": 1511379433 } The resulting deployment id identifies the test version of the API for the canary release. As a result, the associated stage is canary-enabled. 3. (Optional) Use the following get-stage command to view the stage representation: Deploy REST APIs 712 Amazon API Gateway Developer Guide aws apigateway get-stage --rest-api-id acbd1234 --stage-name prod The following shows a representation of the Stage as the output of the command: { "stageName": "prod", "variables": { "sv0": "val0", "sv1": "val1" }, "cacheClusterEnabled": false, "cacheClusterStatus": "NOT_AVAILABLE", "deploymentId": "du4ot1", "lastUpdatedDate": 1511379433, "createdDate": 1511379050, "canarySettings": { "percentTraffic": 10.5, "deploymentId": "a6rox0", "useStageCache": false, "stageVariableOverrides": { "sv2": "val3", "sv1": "val2" } }, "methodSettings": {} } In this example, the base version of the API will use the stage variables of {"sv0":val0", "sv1":val1"}, while the test version uses the stage variables of {"sv1":val2", "sv2":val3"}. Both the production release and canary release use the same stage variable of sv1, but with different values, val1 and val2, respectively. The stage variable of sv0 is used solely in the production release and the stage variable of sv2 is used in the canary release only. You can also create a canary release deployment from an existing regular deployment by updating the stage to enable a canary. Deploy REST APIs 713 Amazon API Gateway Developer Guide To create a canary release deployment from an existing deployment 1. Use the create-deployment command to create a deployment without a canary: aws apigateway create-deployment \ --variables sv0=val0,sv1=val1 \ --rest-api-id abcd1234 \ --stage-name 'beta' 2. Use the update-stage command to update the stage to enable a canary: aws apigateway update-stage \ --rest-api-id abcd1234 \ --stage-name 'beta' \ --patch-operations '[{ "op": "replace", "value": "0.0", "path": "/canarySettings/percentTraffic" }, { "op": "copy", "from": "/canarySettings/stageVariableOverrides", "path": "/variables" }, { "op": "copy", "from": "/canarySettings/deploymentId", "path": "/deploymentId" }]' The output will look like the following: { "stageName": "beta", "variables": { "sv0": "val0", "sv1": "val1" }, "cacheClusterEnabled": false, "cacheClusterStatus": "NOT_AVAILABLE", "deploymentId": "cifeiw", "lastUpdatedDate": 1511381930, "createdDate": 1511380879, "canarySettings": { Deploy REST APIs 714 Amazon API Gateway Developer Guide "percentTraffic": 10.5, "deploymentId":
|
apigateway-dg-195
|
apigateway-dg.pdf
| 195 |
apigateway create-deployment \ --variables sv0=val0,sv1=val1 \ --rest-api-id abcd1234 \ --stage-name 'beta' 2. Use the update-stage command to update the stage to enable a canary: aws apigateway update-stage \ --rest-api-id abcd1234 \ --stage-name 'beta' \ --patch-operations '[{ "op": "replace", "value": "0.0", "path": "/canarySettings/percentTraffic" }, { "op": "copy", "from": "/canarySettings/stageVariableOverrides", "path": "/variables" }, { "op": "copy", "from": "/canarySettings/deploymentId", "path": "/deploymentId" }]' The output will look like the following: { "stageName": "beta", "variables": { "sv0": "val0", "sv1": "val1" }, "cacheClusterEnabled": false, "cacheClusterStatus": "NOT_AVAILABLE", "deploymentId": "cifeiw", "lastUpdatedDate": 1511381930, "createdDate": 1511380879, "canarySettings": { Deploy REST APIs 714 Amazon API Gateway Developer Guide "percentTraffic": 10.5, "deploymentId": "cifeiw", "useStageCache": false, "stageVariableOverrides": { "sv2": "val3", "sv1": "val2" } }, "methodSettings": {} } Because you enabled a canary on an existing version of the API, both the production release (Stage) and canary release (canarySettings) point to the same deployment. After you change the API and deploy it to this stage again, the new version will be in the canary release, while the base version remains in the production release. This is manifested in the stage evolution when the deploymentId in the canary release is updated to the new deployment id and the deploymentId in the production release remains unchanged. Update a canary release After a canary release is deployed, you may want to adjust the percentage of the canary traffic or enable or disable the use of a stage cache to optimize the test performance. You can also modify stage variables used in the canary release when the execution context is updated. To make such updates, call the stage:update operation with new values on canarySettings. You can update a canary release using the API Gateway console, the AWS CLI update-stage command or an AWS SDK. Topics • Update a canary release using the API Gateway console • Update a canary release using the AWS CLI Update a canary release using the API Gateway console To use the API Gateway console to update existing canary settings on a stage, do the following: To update existing canary settings 1. Sign in to the API Gateway console and choose an existing REST API. Deploy REST APIs 715 Amazon API Gateway Developer Guide 2. In the main navigation pane, choose Stages, and then choose an existing stage. 3. Choose the Canary tab, and then choose Edit. You might need to choose the right arrow button to show the Canary tab. 4. Update the Request distribution by increasing or decreasing the percentage number between 0.0 and 100.0, inclusive. 5. Select or clear the Stage cache the check box. 6. Add, remove, or modify Canary stage variables. 7. Choose Save. Update a canary release using the AWS CLI To use the AWS CLI to update a canary, use the update-stage command and modify the patch operation for each parameter of the canary. The following update-stage command updates if the canary uses the stage cache: aws apigateway update-stage \ --rest-api-id {rest-api-id} \ --stage-name '{stage-name}' \ --patch-operations op=replace,path=/canarySettings/useStageCache,value=true The following update-stage command updates the canary traffic percentage: aws apigateway update-stage \ --rest-api-id {rest-api-id} \ --stage-name '{stage-name}' \ --patch-operations op=replace,path=/canarySettings/percentTraffic,value=25.0 The following update-stage updates stage variables. The example shows how to create a new stage variable named newVar, override the var2 stage variable, and remove the var1 stage variable: aws apigateway update-stage \ --rest-api-id {rest-api-id} \ --stage-name '{stage-name}' \ --patch-operations '[{ "op": "replace", "path": "/canarySettings/stageVariableOverrides/newVar", "value": "newVal" Deploy REST APIs 716 Amazon API Gateway }, { "op": "replace", "path": "/canarySettings/stageVariableOverrides/var2", "value": "val4" }, { "op": "remove", "path": "/canarySettings/stageVariableOverrides/var1" }]' Developer Guide You can update all of the above by combining the operations into a single patch-operations value: aws apigateway update-stage \ --rest-api-id {rest-api-id} \ --stage-name '{stage-name}' \ --patch-operations '[{ "op": "replace", "path": "/canarySettings/percentTraffic", "value": "20.0" }, { "op": "replace", "path": "/canarySettings/useStageCache", "value": "true" }, { "op": "remove", "path": "/canarySettings/stageVariableOverrides/var1" }, { "op": "replace", "path": "/canarySettings/stageVariableOverrides/newVar", "value": "newVal" }, { "op": "replace", "path": "/canarySettings/stageVariableOverrides/val2", "value": "val4" }]' Promote a canary release When you promote a canary release, the canary release replaces the current stage settings. Promoting a canary release does not disable the canary on the stage. To disable a canary, you must remove the canary settings on the stage. To promote a canary, do the following. Deploy REST APIs 717 Amazon API Gateway Developer Guide • Reset the deployment ID of the stage with the deployment ID settings of the canary. This updates the API snapshot of the stage with the snapshot of the canary, making the test version the production release as well. • Update stage variables with canary stage variables, if any. This updates the API execution context of the stage with that of the canary. Without this update, the new API version may produce unexpected results if the test version uses different stage variables or different values of existing stage variables. • Set the percentage
|
apigateway-dg-196
|
apigateway-dg.pdf
| 196 |
APIs 717 Amazon API Gateway Developer Guide • Reset the deployment ID of the stage with the deployment ID settings of the canary. This updates the API snapshot of the stage with the snapshot of the canary, making the test version the production release as well. • Update stage variables with canary stage variables, if any. This updates the API execution context of the stage with that of the canary. Without this update, the new API version may produce unexpected results if the test version uses different stage variables or different values of existing stage variables. • Set the percentage of canary traffic to 0.0%. Topics • Promote a canary release using the API Gateway console • Promote a canary release using the AWS CLI Promote a canary release using the API Gateway console To use the API Gateway console to promote a canary release deployment, do the following: To promote a canary release deployment 1. 2. Sign in to the API Gateway console and choose an existing API in the primary navigation pane. In the main navigation pane, choose Stages, and then choose an existing stage. 3. Choose the Canary tab. 4. Choose Promote canary. 5. Confirm changes to be made and choose Promote canary. After the promotion, the production release references the same API version (deploymentId) as the canary release. You can verify this using the AWS CLI. For example, see the section called “Promote a canary release using the AWS CLI”. Promote a canary release using the AWS CLI To promote a canary release to the production release using the AWS CLI commands, call the update-stage command to copy the canary-associated deploymentId to the stage-associated deploymentId, to reset the canary traffic percentage to zero (0.0), and, to copy any canary- bound stage variables to the corresponding stage-bound ones. Deploy REST APIs 718 Amazon API Gateway Developer Guide Suppose we have a canary release deployment, described by a stage similar to the following: { "_links": { ... }, "accessLogSettings": { ... }, "cacheClusterEnabled": false, "cacheClusterStatus": "NOT_AVAILABLE", "canarySettings": { "deploymentId": "eh1sby", "useStageCache": false, "stageVariableOverrides": { "sv2": "val3", "sv1": "val2" }, "percentTraffic": 10.5 }, "createdDate": "2017-11-20T04:42:19Z", "deploymentId": "nfcn0x", "lastUpdatedDate": "2017-11-22T00:54:28Z", "methodSettings": { ... }, "stageName": "prod", "variables": { "sv1": "val1" } } Use the following update-stage command to promote the canary: aws apigateway update-stage \ --rest-api-id {rest-api-id} \ --stage-name '{stage-name}' \ --patch-operations '[{ "op": "replace", "value": "0.0", "path": "/canarySettings/percentTraffic" }, { "op": "copy", Deploy REST APIs 719 Amazon API Gateway Developer Guide "from": "/canarySettings/stageVariableOverrides", "path": "/variables" }, { "op": "copy", "from": "/canarySettings/deploymentId", "path": "/deploymentId" }]' The output will look like the following: { "_links": { ... }, "accessLogSettings": { ... }, "cacheClusterEnabled": false, "cacheClusterStatus": "NOT_AVAILABLE", "canarySettings": { "deploymentId": "eh1sby", "useStageCache": false, "stageVariableOverrides": { "sv2": "val3", "sv1": "val2" }, "percentTraffic": 0 }, "createdDate": "2017-11-20T04:42:19Z", "deploymentId": "eh1sby", "lastUpdatedDate": "2017-11-22T05:29:47Z", "methodSettings": { ... }, "stageName": "prod", "variables": { "sv2": "val3", "sv1": "val2" } } Promoting a canary release to the stage does not disable the canary and the deployment remains to be a canary release deployment. To make it a regular production release deployment, you Deploy REST APIs 720 Amazon API Gateway Developer Guide must disable the canary settings. For more information about how to disable a canary release deployment, see the section called “Turn off a canary release”. Turn off a canary release To turn off a canary release deployment is to set the canarySettings to null to remove it from the stage. You can disable a canary release deployment using the API Gateway console, the AWS CLI, or an AWS SDK. Topics • Turn off a canary release using the API Gateway console • Turn off a canary release using the AWS CLI Turn off a canary release using the API Gateway console To use the API Gateway console to turn off a canary release deployment, use the following steps: To turn off a canary release deployment 1. 2. Sign in to the API Gateway console and choose an existing API in the main navigation pane. In the main navigation pane, choose Stages, and then choose an existing stage. 3. Choose the Canary tab. 4. Choose Delete. 5. Confirm you want to delete the canary by choosing Delete. As a result, the canarySettings property becomes null and is removed from the deployment stage. You can verify this using the AWS CLI. For example, see the section called “Turn off a canary release using the AWS CLI”. Turn off a canary release using the AWS CLI The following update-stage command turns off the canary release deployment: aws apigateway update-stage \ --rest-api-id abcd1234 \ --stage-name canary \ --patch-operations '[{"op":"remove", "path":"/canarySettings"}]' Deploy REST APIs 721 Amazon API Gateway Developer Guide The output looks like the following: { "stageName": "prod", "accessLogSettings": { ... }, "cacheClusterEnabled": false, "cacheClusterStatus": "NOT_AVAILABLE", "deploymentId": "nfcn0x", "lastUpdatedDate": 1511309280, "createdDate": 1511152939, "methodSettings":
|
apigateway-dg-197
|
apigateway-dg.pdf
| 197 |
the canarySettings property becomes null and is removed from the deployment stage. You can verify this using the AWS CLI. For example, see the section called “Turn off a canary release using the AWS CLI”. Turn off a canary release using the AWS CLI The following update-stage command turns off the canary release deployment: aws apigateway update-stage \ --rest-api-id abcd1234 \ --stage-name canary \ --patch-operations '[{"op":"remove", "path":"/canarySettings"}]' Deploy REST APIs 721 Amazon API Gateway Developer Guide The output looks like the following: { "stageName": "prod", "accessLogSettings": { ... }, "cacheClusterEnabled": false, "cacheClusterStatus": "NOT_AVAILABLE", "deploymentId": "nfcn0x", "lastUpdatedDate": 1511309280, "createdDate": 1511152939, "methodSettings": { ... } } As shown in the output, the canarySettings property is no longer present in the stage of a canary- disabled deployment. Updates to REST APIs that require redeployment Maintaining an API amounts to viewing, updating and deleting the existing API setups. You can maintain an API using the API Gateway console, AWS CLI, an SDK or the API Gateway REST API. Updating an API involves modifying certain resource properties or configuration settings of the API. Resource updates require redeploying the API, where configuration updates do not. The following table describes API resources that require redeployment of your API when you update them. Resource Notes ApiKey Authorizer For applicable properties and supported operations, see apikey:update. The update requires redeploying the API. For applicable properties and supported operations, see authorizer:update. The update requires redeploying the API. Documenta tionPart For applicable properties and supported operations, see documentationpart: update. The update requires redeploying the API. Deploy REST APIs 722 Amazon API Gateway Developer Guide Resource Notes Documenta tionVersion For applicable properties and supported operations, see documentationversi on:update. The update requires redeploying the API. GatewayRe sponse For applicable properties and supported operations, see gatewayresponse:up date. The update requires redeploying the API. Integration For applicable properties and supported operations, see integration:update. The update requires redeploying the API. Integrati onResponse For applicable properties and supported operations, see integrationrespons e:update. The update requires redeploying the API. Method For applicable properties and supported operations, see method:update. The update requires redeploying the API. MethodRes ponse For applicable properties and supported operations, see methodresponse:upd ate. The update requires redeploying the API. Model For applicable properties and supported operations, see model:update. The update requires redeploying the API. RequestVa lidator For applicable properties and supported operations, see requestvalidator:u pdate. The update requires redeploying the API. Resource RestApi For applicable properties and supported operations, see resource:update. The update requires redeploying the API. For applicable properties and supported operations, see restapi:update. The update requires redeploying the API. This includes modifying resource policies. VpcLink For applicable properties and supported operations, see vpclink:update. The update requires redeploying the API. The following table describes API configurations that don't require redeployment of your API when you update them. Deploy REST APIs 723 Amazon API Gateway Developer Guide Configuration Notes Account For applicable properties and supported operations, see account:update. The update does not require redeploying the API. Deployment For applicable properties and supported operations, see deployment:update. DomainName For applicable properties and supported operations, see domainname:update. The update does not require redeploying the API. BasePathM apping For applicable properties and supported operations, see basepathmapping:up date. The update does not require redeploying the API. IP address type The update does not require redeploying the API. Stage Usage For applicable properties and supported operations, see stage:update. The update does not require redeploying the API. For applicable properties and supported operations, see usage:update. The update does not require redeploying the API. UsagePlan For applicable properties and supported operations, see usageplan:update. The update does not require redeploying the API. Custom domain name for public REST APIs in API Gateway Custom domain names are simpler and more intuitive URLs that you can provide to your API users. After deploying your API, you (and your customers) can invoke the API using the default base URL of the following format: https://api-id.execute-api.region.amazonaws.com/stage where api-id is generated by API Gateway, region is the AWS Region, and stage is specified by you when deploying the API. The hostname portion of the URL, api-id.execute-api.region.amazonaws.com refers to an API endpoint. The default API endpoint name is randomly generated, difficult to recall, and not user-friendly. Custom domain names 724 Amazon API Gateway Developer Guide With custom domain names, you can set up your API's hostname, and choose a base path (for example, myservice) to map the alternative URL to your API. For example, a more user-friendly API base URL can become: https://api.example.com/myservice Note For information about custom domain names for private APIs, see the section called “Custom domain names for private APIs”. Considerations The following considerations might impact your use of a custom domain name: • You can disable the default endpoint for your API. Clients can still connect to your default endpoint, but they will receive a 403 Forbidden status
|
apigateway-dg-198
|
apigateway-dg.pdf
| 198 |
Gateway Developer Guide With custom domain names, you can set up your API's hostname, and choose a base path (for example, myservice) to map the alternative URL to your API. For example, a more user-friendly API base URL can become: https://api.example.com/myservice Note For information about custom domain names for private APIs, see the section called “Custom domain names for private APIs”. Considerations The following considerations might impact your use of a custom domain name: • You can disable the default endpoint for your API. Clients can still connect to your default endpoint, but they will receive a 403 Forbidden status code. • A Regional custom domain name can be associated with REST APIs and HTTP APIs. You can use the API Gateway Version 2 APIs to create and manage Regional custom domain names for REST APIs. • A custom domain name must be unique within a Region across all AWS accounts. • You can migrate your custom domain name between edge-optimized and Regional endpoints, but you can't migrate a public custom domain to a private custom domain name. • You must create or update your DNS provider's resource record to map to your API endpoint. Without such a mapping, API requests bound for the custom domain name cannot reach API Gateway. • You can support an almost infinite number of domain names without exceeding the default quota by using a wildcard certificate. For more information, see the section called “Wildcard custom domain names”. • You can choose a security policy for your custom domain name. For more information, see the section called “Choose a security policy”. • To configure API mappings with multiple levels, you must use a Regional custom domain name and use the TLS 1.2 security policy. Custom domain names 725 Amazon API Gateway Developer Guide Prerequisites for custom domain names The following are prerequisites for creating a public or private custom domain name. For information about custom domain names for private APIs, see the section called “Custom domain names for private APIs”. Register a domain name You must have a registered internet domain name in order to set up custom domain names for your APIs. You can register your internet domain name using Amazon Route 53 or using a third- party domain registrar of your choice. Your custom domain name can be the name of a subdomain or the root domain (also known as the "zone apex") of a registered internet domain. Your domain name must follow the RFC 1035 specification and can have a maximum of 63 octets per label and 255 octets in total. Specify the certificate for your custom domain name Before setting up a custom domain name for an API, you must have an SSL/TLS certificate ready in ACM. If ACM is not available in the AWS Region where you are creating your custom domain name, you must import a certificate to API Gateway in that Region. To import an SSL/TLS certificate, you must provide the PEM-formatted SSL/TLS certificate body, its private key, and the certificate chain for the custom domain name. Each certificate stored in ACM is identified by its ARN. With certificates issued by ACM, you do not have to worry about exposing any sensitive certificate details, such as the private key. To use an AWS managed certificate for a domain name, you simply reference its ARN. If your application uses certificate pinning, sometimes known as SSL pinning, to pin an ACM certificate, the application might not be able to connect to your domain after AWS renews the certificate. For more information, see Certificate pinning problems in the AWS Certificate Manager User Guide. Wildcard custom domain names With wildcard custom domain names, you can support an almost infinite number of domain names without exceeding the default quota. For example, you could give each of your customers their own domain name, customername.api.example.com. To create a wildcard custom domain name, specify a wildcard (*) as the first subdomain of a custom domain that represents all possible subdomains of a root domain. Custom domain names 726 Amazon API Gateway Developer Guide For example, the wildcard custom domain name *.example.com results in subdomains such as a.example.com, b.example.com, and c.example.com, which all route to the same domain. Wildcard custom domain names support distinct configurations from API Gateway's standard custom domain names. For example, in a single AWS account, you can configure *.example.com and a.example.com to behave differently. You can use the $context.domainName and $context.domainPrefix context variables to determine the domain name that a client used to call your API. To learn more about context variables, see Variables for data transformations for API Gateway. To create a wildcard custom domain name, you must provide a certificate issued by ACM that has been validated using either the DNS or the email validation method. Note You can't create a
|
apigateway-dg-199
|
apigateway-dg.pdf
| 199 |
domain. Wildcard custom domain names support distinct configurations from API Gateway's standard custom domain names. For example, in a single AWS account, you can configure *.example.com and a.example.com to behave differently. You can use the $context.domainName and $context.domainPrefix context variables to determine the domain name that a client used to call your API. To learn more about context variables, see Variables for data transformations for API Gateway. To create a wildcard custom domain name, you must provide a certificate issued by ACM that has been validated using either the DNS or the email validation method. Note You can't create a wildcard custom domain name if a different AWS account has created a custom domain name that conflicts with the wildcard custom domain name. For example, if account A has created a.example.com, then account B can't create the wildcard custom domain name *.example.com. If account A and account B share an owner, you can contact the AWS Support Center to request an exception. Next steps for custom domain names The following are next steps for custom domain names. Next steps • To learn how to set your SSL/TLS certificate, see the section called “Get certificates ready in AWS Certificate Manager”. • To learn how to create a Regional custom domain name, see the section called “Set up a Regional custom domain name”. • To learn how to create an edge-optimized custom domain name, see the section called “Set up an edge-optimized custom domain name in API Gateway”. • To learn how to migrate between Regional and edge-optimized custom domain names, see the section called “Migrate custom domain names”. Custom domain names 727 Amazon API Gateway Developer Guide • To learn how to connect API stages to a custom domain name, see the section called “API mappings”. • To learn how to choose a security policy for your custom domain name, see the section called “Choose a security policy”. • To learn how to turn off the default endpoint for your custom domain name, see the section called “Disable the default endpoint”. • To learn how to use Route 53 health checks to control DNS failover from an API Gateway API, see the section called “DNS failover”. If this is your first time creating a custom domain name, we recommend that you start with the section called “Get certificates ready in AWS Certificate Manager”, to specify your certificate, and then the section called “Set up a Regional custom domain name” to create a Regional custom domain name. Get certificates ready in AWS Certificate Manager Before setting up a custom domain name for an API, you must have an SSL/TLS certificate ready in AWS Certificate Manager. For more information, see the AWS Certificate Manager User Guide. Considerations The following are considerations for your SSL/TLS certificate. • If you create an edge-optimized custom domain name, API Gateway leverages CloudFront to support certificates for custom domain names. As such, the requirements and constraints of a custom domain name SSL/TLS certificate are dictated by CloudFront. For example, the maximum size of the public key is 2048 and the private key size can be 1024, 2048, and 4096. The public key size is determined by the certificate authority you use. Ask your certificate authority to return keys of a size different from the default length. For more information, see Secure access to your objects and Create signed URLs and signed cookies. • To use an ACM certificate with a Regional custom domain name, you must request or import the certificate in the same Region as your API. The certificate must cover the custom domain name. • To use an ACM certificate with an edge-optimized custom domain name, you must request or import the certificate in the US East (N. Virginia) – us-east-1 Region. • You must have a registered domain name, such as example.com. You can use either Amazon Route 53 or a third-party accredited domain registrar. For a list of such registrars, see Accredited Registrar Directory at the ICANN website. Custom domain names 728 Amazon API Gateway Developer Guide To create or import an SSL/TLS certificate into ACM The following procedures show how to create or import an SSL/TLS certificate for a domain name. To request a certificate provided by ACM for a domain name 1. Sign in to the AWS Certificate Manager console. 2. Choose Request a certificate. 3. For Certificate type, choose Request a public certificate. 4. Choose Next. 5. For Fully qualified domain name, enter a custom domain name for your API, for example, api.example.com. 6. Optionally, choose Add another name to this certificate. 7. 8. For Validation method, choose a method for validating domain ownership. For Key algorithm, choose an encryption algorithm. 9. Choose Request. 10. For a valid request, a registered owner of the internet domain must consent to the request
|
apigateway-dg-200
|
apigateway-dg.pdf
| 200 |
a certificate provided by ACM for a domain name 1. Sign in to the AWS Certificate Manager console. 2. Choose Request a certificate. 3. For Certificate type, choose Request a public certificate. 4. Choose Next. 5. For Fully qualified domain name, enter a custom domain name for your API, for example, api.example.com. 6. Optionally, choose Add another name to this certificate. 7. 8. For Validation method, choose a method for validating domain ownership. For Key algorithm, choose an encryption algorithm. 9. Choose Request. 10. For a valid request, a registered owner of the internet domain must consent to the request before ACM issues the certificate. If you use Route 53 to manage your public DNS records, you can update your records through the ACM console directly. To import into ACM a certificate for a domain name 1. Get a PEM-encoded SSL/TLS certificate for your custom domain name from a certificate authority. For a partial list of such CAs, see the Mozilla Included CA List. a. Generate a private key for the certificate and save the output to a file, using the OpenSSL toolkit at the OpenSSL website: openssl genrsa -out private-key-file 2048 b. Generate a certificate signing request (CSR) with the previously generated private key, using OpenSSL: openssl req -new -sha256 -key private-key-file -out CSR-file c. Submit the CSR to the certificate authority and save the resulting certificate. d. Download the certificate chain from the certificate authority. Custom domain names 729 Amazon API Gateway Developer Guide Note If you obtain the private key in another way and the key is encrypted, you can use the following command to decrypt the key before submitting it to API Gateway for setting up a custom domain name. openssl pkcs8 -topk8 -inform pem -in MyEncryptedKey.pem -outform pem - nocrypt -out MyDecryptedKey.pem 2. Upload the certificate to AWS Certificate Manager: a. Sign in to the AWS Certificate Manager console. b. Choose Import a certificate. c. For Certificate body, enter the body of the PEM-formatted server certificate from your certificate authority. The following shows an abbreviated example of such a certificate. -----BEGIN CERTIFICATE----- EXAMPLECA+KgAwIBAgIQJ1XxJ8Pl++gOfQtj0IBoqDANBgkqhkiG9w0BAQUFADBB ... az8Cg1aicxLBQ7EaWIhhgEXAMPLE -----END CERTIFICATE----- d. For Certificate private key, enter your PEM-formatted certificate's private key. The following shows an abbreviated example of such a key. -----BEGIN RSA PRIVATE KEY----- EXAMPLEBAAKCAQEA2Qb3LDHD7StY7Wj6U2/opV6Xu37qUCCkeDWhwpZMYJ9/nETO ... 1qGvJ3u04vdnzaYN5WoyN5LFckrlA71+CszD1CGSqbVDWEXAMPLE -----END RSA PRIVATE KEY----- e. For Certificate chain, enter the PEM-formatted intermediate certificates and, optionally, the root certificate, one after the other without any blank lines. If you include the root certificate, your certificate chain must start with intermediate certificates and end with the root certificate. Use the intermediate certificates provided by your certificate authority. Do not include any intermediaries that are not in the chain of trust path. The following shows an abbreviated example. Custom domain names 730 Amazon API Gateway Developer Guide -----BEGIN CERTIFICATE----- EXAMPLECA4ugAwIBAgIQWrYdrB5NogYUx1U9Pamy3DANBgkqhkiG9w0BAQUFADCB ... 8/ifBlIK3se2e4/hEfcEejX/arxbx1BJCHBvlEPNnsdw8EXAMPLE -----END CERTIFICATE----- Here is another example. -----BEGIN CERTIFICATE----- Intermediate certificate 2 -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- Intermediate certificate 1 -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- Optional: Root certificate -----END CERTIFICATE----- f. Choose Next, and then choose Next. After the certificate is successfully created or imported, make note of the certificate ARN. You need it when setting up the custom domain name. Set up a Regional custom domain name in API Gateway Use a Regional custom domain name to create a user-friendly API base URL. With a Regional custom domain name, you can map HTTP and REST API stages to the same custom domain name and use mutual TLS authentication. Considerations The following are considerations for your Regional custom domain name: • You must provide a Region-specific ACM certificate. This certificate must be in the same Region as your API. For more information about creating or uploading a custom domain name certificate, see the section called “Get certificates ready in AWS Certificate Manager”. • When you create a Regional custom domain name (or migrate one) with an ACM certificate, API Gateway creates a service-linked role in your account. The service-linked role is required to attach your ACM certificate to your Regional endpoint. The role is named Custom domain names 731 Amazon API Gateway Developer Guide AWSServiceRoleForAPIGateway and will have the APIGatewayServiceRolePolicy managed policy attached to it. For more information about use of the service-linked role, see Using Service-Linked Roles. • After your create your Regional custom domain name, you must create a DNS record to point the custom domain name to the Regional domain. This enables the traffic that is bound to the custom domain name to be routed to the API's Regional hostname. The DNS record can be the CNAME or an A Alias record. If you use Route 53 as your DNS provider, create an A Alias record. If you use a third-party DNS provider, use a CNAME record. If you use a CNAME record and create an API Gateway interface VPC endpoint
|
apigateway-dg-201
|
apigateway-dg.pdf
| 201 |
see Using Service-Linked Roles. • After your create your Regional custom domain name, you must create a DNS record to point the custom domain name to the Regional domain. This enables the traffic that is bound to the custom domain name to be routed to the API's Regional hostname. The DNS record can be the CNAME or an A Alias record. If you use Route 53 as your DNS provider, create an A Alias record. If you use a third-party DNS provider, use a CNAME record. If you use a CNAME record and create an API Gateway interface VPC endpoint with private DNS enabled for a private API, you can't resolve the custom domain name within the VPC that hosts your private API. Create a Regional custom domain name The following procedure shows how to create a Regional custom domain name. After you complete this procedure, you create a base path mapping to map stages of your API to your custom domain name. AWS Management Console 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Custom domain names from the main navigation pane. 3. Choose Create. 4. 5. For Domain name, enter a domain name. For Minimum TLS version, select a version. 6. Under Endpoint configuration, for API endpoint type, choose Regional. 7. Choose an ACM certificate. The certificate must be in the same Region as the API. 8. Choose Create. AWS CLI The following create-domain-name command creates a custom domain name: aws apigatewayv2 create-domain-name \ --domain-name 'regional.example.com' \ Custom domain names 732 Amazon API Gateway Developer Guide --domain-name-configurations CertificateArn=arn:aws:acm:us- west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678 The output will look like the following: { "ApiMappingSelectionExpression": "$request.basepath", "DomainName": "regional.example.com", "DomainNameConfigurations": [ { "ApiGatewayDomainName": "d-numh1z56v6.execute-api.us- west-2.amazonaws.com", "CertificateArn": "arn:aws:acm:us- west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678", "DomainNameStatus": "AVAILABLE", "EndpointType": "REGIONAL", "HostedZoneId": "Z2OJLYMUO9EFXC", "SecurityPolicy": "TLS_1_2" } ] } The DomainNameConfigurations property value returns the Regional API's hostname. You must create a DNS record to point your custom domain name to this Regional domain name. This enables the traffic that is bound to the custom domain name to be routed to this Regional API's hostname. Create a base path mapping for your Regional custom domain name After you create your custom domain name, you create a base path mapping to map your API to your custom domain name. For example, you can map the stage test for the API ID of abcd1234 to the custom domain name regional.example.com using the API mapping key of myApi. This maps the API https://abcd1234.execute-api.us-west-2.amazonaws.com/test to https://regional.example.com/myApi. AWS Management Console 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a custom domain name. 3. Choose Configure API mappings. Custom domain names 733 Amazon API Gateway Developer Guide 4. Choose Add new mapping. 5. Specify the API, Stage, and Path for the mapping. 6. Choose Save. AWS CLI The following create-api-mapping command creates a base path mapping: aws apigatewayv2 create-api-mapping \ --domain-name 'regional.example.com' \ --api-mapping-key 'myApi' \ --api-id abcd1234 \ --stage 'test' As a result, the base URL using the custom domain name for the API that is deployed in the stage becomes https://regional.example.com/myAPI. With a Regional custom domain name, you can create an API mapping with multiple levels, such as https://regional.example.com/orders/v1/items/123. You can also map HTTP and REST API stages to the same custom domain name. For more information, see the section called “API mappings”. Create a DNS record for your Regional custom domain name After you create your custom domain name and create base path mappings, you create a DNS record to point your custom domain name your newly created Regional domain name. AWS Management Console To use the AWS Management Console, follow the Route 53 documentation on configuring Route 53 to route traffic to API Gateway. AWS CLI To configure your DNS records to map the Regional custom domain name to its hostname of the given hosted zone ID, first create a JSON file that contains the configuration for setting up a DNS record for the Regional domain name. The following setup-dns-record.json shows how to create a DNS A record to map a Regional custom domain name (regional.example.com) to its Regional hostname (d- Custom domain names 734 Amazon API Gateway Developer Guide numh1z56v6.execute-api.us-west-2.amazonaws.com) provisioned as part of the custom domain name creation. The DNSName and HostedZoneId properties of AliasTarget can take the regionalDomainName and regionalHostedZoneId values, respectively, of the custom domain name. You can also get the Regional Route 53 Hosted Zone IDs in Amazon API Gateway Endpoints and Quotas. { "Changes": [ { "Action": "CREATE", "ResourceRecordSet": { "Name": "regional.example.com", "Type": "A", "AliasTarget": { "DNSName": "d-numh1z56v6.execute-api.us-west-2.amazonaws.com", "HostedZoneId": "Z2OJLYMUO9EFXC", "EvaluateTargetHealth": false } } } ] } The following change-resource-record-sets creates a DNS record for your Regional custom domain name: aws route53 change-resource-record-sets \ --hosted-zone-id Z2OJLYMUO9EFXC \ --change-batch file://path/to/your/setup-dns-record.json Replace thehosted-zone-id with the Route 53 Hosted Zone ID of the DNS record set in your
|
apigateway-dg-202
|
apigateway-dg.pdf
| 202 |
DNSName and HostedZoneId properties of AliasTarget can take the regionalDomainName and regionalHostedZoneId values, respectively, of the custom domain name. You can also get the Regional Route 53 Hosted Zone IDs in Amazon API Gateway Endpoints and Quotas. { "Changes": [ { "Action": "CREATE", "ResourceRecordSet": { "Name": "regional.example.com", "Type": "A", "AliasTarget": { "DNSName": "d-numh1z56v6.execute-api.us-west-2.amazonaws.com", "HostedZoneId": "Z2OJLYMUO9EFXC", "EvaluateTargetHealth": false } } } ] } The following change-resource-record-sets creates a DNS record for your Regional custom domain name: aws route53 change-resource-record-sets \ --hosted-zone-id Z2OJLYMUO9EFXC \ --change-batch file://path/to/your/setup-dns-record.json Replace thehosted-zone-id with the Route 53 Hosted Zone ID of the DNS record set in your account. The change-batch parameter value points to a JSON file (setup-dns- record.json) in a folder (path/to/your). Set up an edge-optimized custom domain name in API Gateway When you create a custom domain name for an edge-optimized API, API Gateway sets up a CloudFront distribution and a DNS record to map the API domain name to the CloudFront distribution domain name. Requests for the API are then routed to API Gateway through the Custom domain names 735 Amazon API Gateway Developer Guide mapped CloudFront distribution. This mapping is for API requests that are bound for the custom domain name to be routed to API Gateway through the mapped CloudFront distribution. Considerations The following are considerations for your edge-optimized custom domain name: • To set up an edge-optimized custom domain name or to update its certificate, you must have a permission to update CloudFront distributions. The following permissions are required to update CloudFront distributions: { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCloudFrontUpdateDistribution", "Effect": "Allow", "Action": [ "cloudfront:updateDistribution" ], "Resource": [ "*" ] } ] } • You must request or import a certificate for your edge-optimized custom domain name in the US East (N. Virginia) – us-east-1 Region. • The CloudFront distribution created by API Gateway is owned by a Region-specific account affiliated with API Gateway. When tracing operations to create and update such a CloudFront distribution in CloudTrail, you must use this API Gateway account ID. For more information, see Log custom domain name creation in CloudTrail. • API Gateway supports edge-optimized custom domain names by leveraging Server Name Indication (SNI) on the CloudFront distribution. For more information on using custom domain names on a CloudFront distribution, including the required certificate format and the maximum size of a certificate key length, see Using Alternate Domain Names and HTTPS in the Amazon CloudFront Developer Guide • An edge-optimized custom domain names takes about 40 minutes to be ready. Custom domain names 736 Amazon API Gateway Developer Guide • After you create your edge-optimized custom domain name, you must create a DNS record to map the custom domain name to the CloudFront distribution name. Create an edge-optimize custom domain name The following procedure describes how to create an edge-optimized custom domain name for an API. AWS Management Console 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Custom domain names from the main navigation pane. 3. Choose Add domain name. 4. 5. For Domain name, enter a domain name. For API endpoint type, choose Edge-optimized. 6. Choose a minimum TLS version. 7. Choose an ACM certificate. 8. Choose Add domain name. REST API 1. Call domainname:create, specifying the custom domain name and the ARN of a certificate stored in AWS Certificate Manager. The successful API call returns a 201 Created response containing the certificate ARN as well as the associated CloudFront distribution name in its payload. 2. Note the CloudFront distribution domain name shown in the output. You need it in the next step to set the custom domain's A-record alias target in your DNS. For code examples of this REST API call, see domainname:create. An edge-optimized custom domain names takes about 40 minutes to be ready, but the console immediately displays the associated CloudFront distribution domain name, in the form of distribution-id.cloudfront.net, along with the certificate ARN. In the meantime, you can Custom domain names 737 Amazon API Gateway Developer Guide create a base path mapping and then configure the DNS record alias to map the custom domain name to the associated CloudFront distribution domain name. Configure base path mapping of an API with a custom domain name as its hostname You can use base path mapping to use a single custom domain name as the hostname of multiple APIs. This makes an API accessible through the combination of the custom domain name and the associated base path. For example, if in API Gateway, you created an API named PetStore and another API named Dogs and then set up a custom domain name of api.example.com, you can set the PetStore API's URL as https://api.example.com. This associates the PetStore API with the base path of an empty string. If you set the PetStore API's URL as https://api.example.com/PetStore, this associates the
|
apigateway-dg-203
|
apigateway-dg.pdf
| 203 |
its hostname You can use base path mapping to use a single custom domain name as the hostname of multiple APIs. This makes an API accessible through the combination of the custom domain name and the associated base path. For example, if in API Gateway, you created an API named PetStore and another API named Dogs and then set up a custom domain name of api.example.com, you can set the PetStore API's URL as https://api.example.com. This associates the PetStore API with the base path of an empty string. If you set the PetStore API's URL as https://api.example.com/PetStore, this associates the PetStore API with the base path of PetStore. You can assign a base path of MyDogList for the Dogs API. The URL of https://api.example.com/MyDogList is then the root URL of the Dogs API. To configure API mappings on multiple levels, you can only use a Regional custom domain name. Edge-optimized custom domain names are not supported. For more information, see the section called “API mappings”. The following procedure sets up API mappings to map paths from your custom domain name to your API stages. AWS Management Console 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Custom domain names from the API Gateway console main navigation pane. 3. Choose a custom domain name. 4. Choose Configure API mappings. 5. Choose Add new mapping. 6. Specify the API, Stage, and Path (optional) for the mapping. 7. Choose Save. REST API Call basepathmapping:create on a specific custom domain name, specifying the basePath, restApiId, and a deployment stage property in the request payload. Custom domain names 738 Amazon API Gateway Developer Guide The successful API call returns a 201 Created response. For code examples of the REST API call, see basepathmapping:create. Create a DNS record for your edge-optimized custom domain name After you initiate the creation of your edge-optimized custom domain name, set up the DNS record alias. We recommend that you use Route 53 to create an A-record alias for your custom domain name and specify the CloudFront distribution domain name as the alias target. This means that Route 53 can route your custom domain name even if it is a zone apex. For more information, see Choosing Between Alias and Non-Alias Resource Record Sets in the Amazon Route 53 Developer Guide. For instructions for Amazon Route 53, see Routing traffic to an Amazon API Gateway API by using your domain name in the Amazon Route 53 Developer Guide. Log custom domain name creation in CloudTrail When CloudTrail is enabled for logging API Gateway calls made by your account, API Gateway logs the associated CloudFront distribution updates when a custom domain name is created or updated for an API. These logs are available in us-east-1. Because these CloudFront distributions are owned by API Gateway, each of these reported CloudFront distributions is identified by one of the following Region-specific API Gateway account IDs, instead of the API owner's account ID. Region us-east-1 us-east-2 us-west-1 us-west-2 ca-central-1 eu-west-1 eu-west-2 Account ID 392220576650 718770453195 968246515281 109351309407 796887884028 631144002099 544388816663 Custom domain names 739 Amazon API Gateway Developer Guide Region eu-west-3 eu-central-1 eu-central-2 eu-north-1 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 Account ID 061510835048 474240146802 166639821150 394634713161 753362059629 359345898052 969236854626 020402002396 360671645888 195145609632 798376113853 652364314486 849137399833 507069717855 644042651268 174803364771 287228555773 855739686837 614065512851 Custom domain names 740 Amazon API Gateway Developer Guide Rotate a certificate imported into ACM ACM automatically handles renewal of certificates it issues. You do not need to rotate any ACM- issued certificates for your custom domain names. CloudFront handles it on your behalf. However, if you import a certificate into ACM and use it for a custom domain name, you must rotate the certificate before it expires. This involves importing a new third-party certificate for the domain name and rotate the existing certificate to the new one. You need to repeat the process when the newly imported certificate expires. Alternatively, you can request ACM to issue a new certificate for the domain name and rotate the existing one to the new ACM-issued certificate. After that, you can leave ACM and CloudFront to handle the certificate rotation for you automatically. To create or import a new ACM certificate, follow the steps in the section called “To create or import an SSL/TLS certificate into ACM”. The following procedure describes how to rotate a certificate for a domain name. Note It takes about 40 minutes to rotate a certificate imported into ACM. AWS Management Console 1. Request or import a certificate in ACM. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 3. Choose Custom domain names from the API Gateway console main navigation pane. 4. Choose an edge-optimized custom domain name. 5. 6. For Endpoint configuration, choose Edit. For ACM certificate, select a
|
apigateway-dg-204
|
apigateway-dg.pdf
| 204 |
import a new ACM certificate, follow the steps in the section called “To create or import an SSL/TLS certificate into ACM”. The following procedure describes how to rotate a certificate for a domain name. Note It takes about 40 minutes to rotate a certificate imported into ACM. AWS Management Console 1. Request or import a certificate in ACM. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 3. Choose Custom domain names from the API Gateway console main navigation pane. 4. Choose an edge-optimized custom domain name. 5. 6. For Endpoint configuration, choose Edit. For ACM certificate, select a certificate from dropdown list. 7. Choose Save changes to begin rotating the certificate for the custom domain name. REST API Call domainname:update action, specifying the ARN of the new ACM certificate for the specified domain name. Custom domain names 741 Amazon API Gateway AWS CLI Developer Guide The following update-domain-name updates the ACM certificate for an edge-optimized domain name. aws apigateway update-domain-name \ --domain-name edge.example.com \ --patch-operations "op='replace',path='/certificateArn',value='arn:aws:acm:us- east-2:111122223333:certificate/CERTEXAMPLE123EXAMPLE'" The following update-domain-name updates the ACM certificate for a Regional domain name. aws apigateway update-domain-name \ --domain-name regional.example.com \ --patch-operations "op='replace',path='/ regionalCertificateArn',value='arn:aws:acm:us-east-2:111122223333:certificate/ CERTEXAMPLE123EXAMPLE'" Call your API with custom domain names Calling an API with a custom domain name is the same as calling the API with its default domain name, provided that the correct URL is used. The following examples compare and contrast a set of default URLs and corresponding custom URLs of two APIs (udxjef and qf3duz) in a specified Region (us-east-1), and of a given custom domain name (api.example.com). API ID udxjef Stage prod udxjef tst Custom domain names Default URL Base path Custom URL https://u dxjef.execute- api.us-east-1 .amazonaw s.com/prod https://u dxjef.execute- api.us-east-1 /petstore https://a pi.example.com/ petstore /petdepot https://a pi.example.com/ petdepot 742 Amazon API Gateway Developer Guide API ID Stage Default URL Base path Custom URL qf3duz dev qf3duz tst .amazonaw s.com/tst https://q f3duz.execute- api.us-east-1 .amazonaw s.com/dev https://q f3duz.execute- api.us-east-1 .amazonaw s.com/tst /bookstore https://a pi.example.com/ bookstore /bookstand https://a pi.example.com/ bookstand API Gateway supports custom domain names for an API by using Server Name Indication (SNI). You can invoke the API with a custom domain name using a browser or a client library that supports SNI. API Gateway enforces SNI on the CloudFront distribution. For information on how CloudFront uses custom domain names, see Amazon CloudFront Custom SSL. Migrate a custom domain name to a different API endpoint type in API Gateway You can migrate your custom domain name between edge-optimized and Regional endpoints. You can't migrate a public custom domain name to a private custom domain name. You first add the new endpoint configuration type to the existing endpointConfiguration.types list for the custom domain name. Next, you set up a DNS record to point the custom domain name to the newly provisioned endpoint. Finally, you remove the obsolete custom domain name configuration data. Considerations The following are considerations for migrating your custom domain between a Regional API endpoint and an edge-optimized API endpoint: Custom domain names 743 Amazon API Gateway Developer Guide • An edge-optimized custom domain name requires a certificate provided by ACM from the US East (N. Virginia) – us-east-1 Region. This certificate is distributed to all the geographic locations. • A Regional custom domain name requires a certificate provided by ACM in the same Region hosting the API. You can migrate an edge-optimized custom domain name that is not in the us- east-1 Region to a Regional custom domain name by requesting a new ACM certificate from the Region that is local to the API. • It might take up to 60 seconds to complete a migration between an edge-optimized custom domain name and a Regional custom domain name. The migration time also depends on when you update your DNS records. Migrate custom domain names The following procedure shows how to migrate an edge-optimized custom domain name to a Regional custom domain name. AWS Management Console 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Custom domain names from the main navigation pane. 3. Choose an edge-optimized custom domain name. 4. For Endpoint configuration, choose Edit. 5. Choose Add Regional endpoint. 6. For ACM certificate, choose a certificate. The Regional certificate must be in the same Region as the Regional API. 7. Choose Save changes. 8. Set up a DNS record to point the Regional custom domain name to this Regional hostname. For more information, see configuring Route 53 to route traffic to API Gateway. 9. After you confirm that your DNS configuration is using the correct endpoint, you delete the edge-optimized endpoint configuration. Choose your custom domain name, and then for Edge-optimized endpoint configuration, choose Delete. 10. Confirm your choice and delete the endpoint. Custom domain names 744 Amazon API Gateway AWS CLI Developer Guide The following update-domain-name command migrates an edge-optmized
|
apigateway-dg-205
|
apigateway-dg.pdf
| 205 |
in the same Region as the Regional API. 7. Choose Save changes. 8. Set up a DNS record to point the Regional custom domain name to this Regional hostname. For more information, see configuring Route 53 to route traffic to API Gateway. 9. After you confirm that your DNS configuration is using the correct endpoint, you delete the edge-optimized endpoint configuration. Choose your custom domain name, and then for Edge-optimized endpoint configuration, choose Delete. 10. Confirm your choice and delete the endpoint. Custom domain names 744 Amazon API Gateway AWS CLI Developer Guide The following update-domain-name command migrates an edge-optmized custom domain name to a Regional custom domain name: aws apigateway update-domain-name \ --domain-name 'api.example.com' \ --patch-operations '[ { "op":"add", "path": "/endpointConfiguration/types","value": "REGIONAL" }, { "op":"add", "path": "/regionalCertificateArn", "value": "arn:aws:acm:us- west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149" } ]' The Regional certificate must be of the same Region as the Regional API. The output will look like the following: { "certificateArn": "arn:aws:acm:us- east-1:123456789012:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a", "certificateName": "edge-cert", "certificateUploadDate": "2017-10-16T23:22:57Z", "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net", "domainName": "api.example.com", "endpointConfiguration": { "types": [ "EDGE", "REGIONAL" ] }, "regionalCertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/ cd833b28-58d2-407e-83e9-dce3fd852149", "regionalDomainName": "d-fdisjghyn6.execute-api.us-west-2.amazonaws.com" } For the migrated Regional custom domain name, the resulting regionalDomainName property returns the Regional API hostname. You must set up a DNS record to point the Regional custom domain name to this Regional hostname. This enables the traffic that is bound to the custom domain name to be routed to the Regional host. After the DNS record is set, you can remove the edge-optimized custom domain name. The following update-domain-name command removes the edge-optimized custom domain name: Custom domain names 745 Amazon API Gateway Developer Guide aws apigateway update-domain-name \ --domain-name api.example.com \ --patch-operations '[ {"op":"remove", "path":"/endpointConfiguration/types", "value":"EDGE"}, {"op":"remove", "path":"certificateName"}, {"op":"remove", "path":"certificateArn"} ]' The following procedure shows how to migrate a Regional custom domain name to an edge- optimized custom domain name. AWS Management Console 1. 2. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. In the main navigation pane, choose Custom domain names. 3. Choose a Regional custom domain name. 4. For Endpoint configuration, choose Edit. 5. Choose Add edge-optimized endpoint. 6. For ACM certificate, choose a certificate. The edge-optimized domain certificate must be created in the us-east-1 Region. 7. Choose Save. 8. Set up a DNS record to point the edge-optimized custom domain name to this edge- optimized hostname. For more information, see configuring Route 53 to route traffic to API Gateway. 9. After you confirm that your DNS configuration is using the correct endpoint, you delete the Regional endpoint configuration. Choose your custom domain name, and then for Regional endpoint configuration, choose Delete. 10. Confirm your choice and delete the endpoint. AWS CLI The following update-domain-name command migrates your Regional custom domain name to an edge-optimized custom domain name: aws apigateway update-domain-name \ Custom domain names 746 Amazon API Gateway Developer Guide --domain-name 'api.example.com' \ --patch-operations '[ { "op":"add", "path": "/endpointConfiguration/types","value": "EDGE" }, { "op":"add", "path": "/certificateName", "value": "edge-cert" }, {"op":"add", "path": "/certificateArn", "value": "arn:aws:acm:us- east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a"} ]' The edge-optimized domain certificate must be created in the us-east-1 Region. The output will look like the following: { "certificateArn": "arn:aws:acm:us- east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a", "certificateName": "edge-cert", "certificateUploadDate": "2017-10-16T23:22:57Z", "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net", "domainName": "api.example.com", "endpointConfiguration": { "types": [ "EDGE", "REGIONAL" ] }, "regionalCertificateArn": "arn:aws:acm:us- east-1:123456789012:certificate/3d881b54-851a-478a-a887-f6502760461d", "regionalDomainName": "d-cgkq2qwgzf.execute-api.us-east-1.amazonaws.com" } For the specified custom domain name, API Gateway returns the edge-optimized API hostname as the distributionDomainName property value. You must set a DNS record to point the edge-optimized custom domain name to this distribution domain name. This enables traffic that is bound to the edge-optimized custom domain name to be routed to the edge-optimized API hostname. After the DNS record is set, you can remove the REGION endpoint type of the custom domain name. The following update-domain-name command removes the Regional endpoint type: aws apigateway update-domain-name \ --domain-name api.example.com \ Custom domain names 747 Amazon API Gateway Developer Guide --patch-operations '[ {"op":"remove", "path":"/endpointConfiguration/types", value:"REGIONAL"}, {"op":"remove", "path":"regionalCertificateArn"} ]' The output looks like the following: { "certificateArn": "arn:aws:acm:us- east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a", "certificateName": "edge-cert", "certificateUploadDate": "2017-10-16T23:22:57Z", "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net", "domainName": "api.example.com", "endpointConfiguration": { "types": "EDGE" } } IP address types for custom domain names in API Gateway When you create a custom domain name, you specify the type of IP addresses that can invoke your domain. You can choose IPv4 to allow IPv4 addresses to invoke your domain, or you can choose dualstack to allow both IPv4 and IPv6 addresses to invoke your domain. 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. You can change the IP address type by updating the endpoint configuration of your domain name. Considerations for IP address types The following considerations might impact your use of IP address types. • The default IP address type for API Gateway
|
apigateway-dg-206
|
apigateway-dg.pdf
| 206 |
IPv4 addresses to invoke your domain, or you can choose dualstack to allow both IPv4 and IPv6 addresses to invoke your domain. 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. You can change the IP address type by updating the endpoint configuration of your domain name. Considerations for IP address types The following considerations might impact your use of IP address types. • The default IP address type for API Gateway custom domain names for public APIs is IPv4. • Private custom domain names can only have a dualstack IP address type. • Your custom domain name doesn't need to have the same IP address type for all APIs mapped to it. If you disable your default API endpoint, this might affect how callers can invoke your domain. Custom domain names 748 Amazon API Gateway Developer Guide Change the IP address type of a custom domain name You can change the IP address type by updating the domain name's endpoint configuration. You can update the endpoint configuration by using the AWS Management Console, the AWS CLI, AWS CloudFormation, or an AWS SDK. AWS Management Console To change the IP address type of a custom domain name 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a public custom domain name. 3. Choose Endpoint configuration. 4. For IP address type, select either IPv4 or Dualstack. 5. Choose Save. AWS CLI The following update-domain-name command updates an API to have an IP address type of dualstack: aws apigateway update-domain-name \ --domain-name dualstack.example.com \ --patch-operations "op='replace',path='/endpointConfiguration/ ipAddressType',value='dualstack'" The output will look like the following: { "domainName": "dualstack.example.com", "certificateUploadDate": "2025-02-04T14:46:10-08:00", "regionalDomainName": "d-abcd1234.execute-api.us-east-1.amazonaws.com", "regionalHostedZoneId": "Z3LQWSYCGH4ADY", "regionalCertificateArn": "arn:aws:acm:us-east-1:111122223333:certificate/ a1b2c3d4-5678-90ab-cdef", "endpointConfiguration": { "types": [ "REGIONAL" ], "ipAddressType": "dualstack" Custom domain names 749 Amazon API Gateway }, "domainNameStatus": "AVAILABLE", "securityPolicy": "TLS_1_2", "tags": {} } Developer Guide Map API stages to a custom domain name for REST APIs You use API mappings to connect API stages to a custom domain name. This sends traffic to your APIs through your custom domain name. An API mapping specifies an API, a stage, and optionally a path to use for the mapping. For example, you can map the production stage of an API to https://api.example.com/orders. You can map HTTP and REST API stages to the same custom domain name. Before you create an API mapping, you must have an API, a stage, and a custom domain name. To learn more about creating a custom domain name, see the section called “Set up a Regional custom domain name”. Routing API requests You can configure API mappings with multiple levels, for example orders/v1/items and orders/v2/items. Note To configure API mappings with multiple levels, you must use a Regional custom domain name with the TLS 1.2 security policy. For API mappings with multiple levels, API Gateway routes requests to the API mapping that has the longest matching path. API Gateway considers only the paths configured for API mappings, and not API routes, to select the API to invoke. If no path matches the request, API Gateway sends the request to the API that you've mapped to the empty path (none). For custom domain names that use API mappings with multiple levels, API Gateway routes requests to the API mapping that has the longest matching prefix. For example, consider a custom domain name https://api.example.com with the following API mappings: Custom domain names 750 Amazon API Gateway 1. (none) mapped to API 1. 2. orders mapped to API 2. 3. orders/v1/items mapped to API 3. 4. orders/v2/items mapped to API 4. 5. orders/v2/items/categories mapped to API 5. Developer Guide Request Selected API Explanation https://api.exampl API 2 e.com/orders https://api.exampl API 3 e.com/orders/v1/it ems https://api.exampl API 4 e.com/orders/v2/it ems https://api.exampl API 3 e.com/orders/v1/it ems/123 https://api.exampl API 5 e.com/orders/v2/it ems/categories/5 https://api.exampl API 1 e.com/customers https://api.exampl API 2 e.com/ordersandmore The request exactly matches this API mapping. The request exactly matches this API mapping. The request exactly matches this API mapping. API Gateway chooses the mapping that has the longest matching path. The 123 at the end of the request doesn't affect the selection. API Gateway chooses the mapping that has the longest matching path. API Gateway uses the empty mapping as a catch-all. API Gateway chooses the mapping that has the longest matching prefix. Custom domain names 751 Amazon API Gateway Developer Guide Request Selected API Explanation For a custom domain name configured with single-le vel mappings, such as only https://api.exampl e.com/orders and https://api.exampl e.com/ , API Gateway would choose API 1, as there is no matching path with ordersandmore . Restrictions • In an API mapping, the custom domain name and mapped APIs must be in the same
|
apigateway-dg-207
|
apigateway-dg.pdf
| 207 |
doesn't affect the selection. API Gateway chooses the mapping that has the longest matching path. API Gateway uses the empty mapping as a catch-all. API Gateway chooses the mapping that has the longest matching prefix. Custom domain names 751 Amazon API Gateway Developer Guide Request Selected API Explanation For a custom domain name configured with single-le vel mappings, such as only https://api.exampl e.com/orders and https://api.exampl e.com/ , API Gateway would choose API 1, as there is no matching path with ordersandmore . Restrictions • In an API mapping, the custom domain name and mapped APIs must be in the same AWS account. • API mappings must contain only letters, numbers, and the following characters: $-_.+!*'()/. • The maximum length for the path in an API mapping is 300 characters. • You can have 200 API mappings with multiple levels for each domain name. This limit doesn't include API mapping with single levels, such as /prod. • You can only map HTTP APIs to a regional custom domain name with the TLS 1.2 security policy. • You can't map WebSocket APIs to the same custom domain name as an HTTP API or REST API. • After you create your API mappings, you must create or update your DNS provider's resource record to map to your API endpoint. • If you create an API mappings with multiple levels, API Gateway converts all header names to lowercase. Create an API mapping To create an API mapping, you must first create a custom domain name, API, and stage. For information about creating a custom domain name, see the section called “Set up a Regional custom domain name”. For example AWS Serverless Application Model templates that create all resources, see Sessions With SAM on GitHub. Custom domain names 752 Amazon API Gateway AWS Management Console Developer Guide 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Custom domain names from the main navigation pane. 3. Choose a custom domain name. 4. On the API mappings tab, choose Configure API mappings. 5. Enter the API, Stage, and Path for the mapping. 6. Choose Save. AWS CLI The following create-api-mapping command creates an API mapping. In this example, API Gateway sends requests to api.example.com/v1/orders to the specified API and stage. Note To create API mappings with multiple levels, you must use apigatewayv2. aws apigatewayv2 create-api-mapping \ --domain-name api.example.com \ --api-mapping-key v1/orders \ --api-id a1b2c3d4 \ --stage test AWS CloudFormation The following AWS CloudFormation example creates an API mapping. Note To create API mappings with multiple levels, you must use AWS::ApiGatewayV2. MyApiMapping: Type: 'AWS::ApiGatewayV2::ApiMapping' Properties: Custom domain names 753 Amazon API Gateway Developer Guide DomainName: api.example.com ApiMappingKey: 'orders/v2/items' ApiId: !Ref MyApi Stage: !Ref MyStage Choose a security policy for your REST API custom domain in API Gateway For greater security of your Amazon API Gateway custom domain, you can choose a security policy in the API Gateway console, the AWS CLI, or an AWS SDK. A security policy is a predefined combination of minimum TLS version and cipher suites offered by API Gateway. You can choose either a TLS version 1.2 or TLS version 1.0 security policy. The TLS protocol addresses network security problems such as tampering and eavesdropping between a client and server. When your clients establish a TLS handshake to your API through the custom domain, the security policy enforces the TLS version and cipher suite options your clients can choose to use. In custom domain settings, a security policy determines two settings: • The minimum TLS version that API Gateway uses to communicate with API clients • The cipher that API Gateway uses to encrypt the content that it returns to API clients If you choose a TLS 1.0 security policy, the security policy accepts TLS 1.0, TLS 1.2, and TLS 1.3 traffic. If you choose a TLS 1.2 security policy, the security policy accepts TLS 1.2 and TLS 1.3 traffic and rejects TLS 1.0 traffic. Note You can only specify a security policy for a custom domain. For an API using a default endpoint, API Gateway uses the following security policy: • For edge-optimized APIs: TLS-1-0 • For Regional APIs: TLS-1-0 • For private APIs: TLS-1-2 The ciphers for each security policy are described in the following tables on this page. Custom domain names 754 Amazon API Gateway Topics Developer Guide • How to specify a security policy for custom domains • Supported security policies, TLS protocol versions, and ciphers for edge-optimized custom domains • Supported security policies, TLS protocol versions, and ciphers for Regional custom domains • Supported TLS protocol versions and ciphers for private APIs • OpenSSL and RFC cipher names • Information about HTTP APIs and WebSocket APIs How to specify a security policy for custom domains When you create a custom domain name, you specify the security
|
apigateway-dg-208
|
apigateway-dg.pdf
| 208 |
policy are described in the following tables on this page. Custom domain names 754 Amazon API Gateway Topics Developer Guide • How to specify a security policy for custom domains • Supported security policies, TLS protocol versions, and ciphers for edge-optimized custom domains • Supported security policies, TLS protocol versions, and ciphers for Regional custom domains • Supported TLS protocol versions and ciphers for private APIs • OpenSSL and RFC cipher names • Information about HTTP APIs and WebSocket APIs How to specify a security policy for custom domains When you create a custom domain name, you specify the security policy for it. To learn how to create a custom domain, see the section called “Set up an edge-optimized custom domain name in API Gateway” or the section called “Set up a Regional custom domain name”. To change the security policy of your custom domain name, update the custom domain settings. You can update your custom domain name settings using the AWS Management Console, the AWS CLI, or an AWS SDK. When you use the API Gateway REST API or AWS CLI, specify the new TLS version, TLS_1_0 or TLS_1_2 in the securityPolicy parameter. For more information, see domainname:update in the Amazon API Gateway REST API Reference or update-domain-name in the AWS CLI Reference. The update operation may take few minutes to complete. Supported security policies, TLS protocol versions, and ciphers for edge-optimized custom domains The following table describes the security policies that can be specified for edge-optimized custom domain names. TLS protocols TLS_1_0 security policy TLS_1_2 security policy TLSv1.3 TLSv1.2 Yes Yes Yes Yes Custom domain names 755 Amazon API Gateway Developer Guide TLS protocols TLS_1_0 security policy TLS_1_2 security policy TLSv1.1 TLSv1 Yes Yes No No The following table describes the TLS ciphers that are available for each security policy. TLS ciphers TLS_1_0 security policy TLS_1_2 security policy TLS_AES_128_GCM_SHA256 TLS_AES_256_GCM_SHA384 TLS_CHACHA20_POLY1 305_SHA256 ECDHE-ECDSA-AES128-GCM- SHA256 ECDHE-ECDSA-AES128- SHA256 ECDHE-ECDSA-AES128-SHA ECDHE-ECDSA-AES256-GCM- SHA384 ECDHE-ECDSA-CHACHA20- POLY1305 ECDHE-ECDSA-AES256- SHA384 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No Yes Yes Yes Custom domain names 756 Amazon API Gateway Developer Guide TLS ciphers TLS_1_0 security policy TLS_1_2 security policy ECDHE-ECDSA-AES256-SHA ECDHE-RSA-AES128-GCM- SHA256 ECDHE-RSA-AES128-SHA256 ECDHE-RSA-AES128-SHA ECDHE-RSA-AES256-GCM- SHA384 ECDHE-RSA-CHACHA20- POLY1305 ECDHE-RSA-AES256-SHA384 ECDHE-RSA-AES256-SHA AES128-GCM-SHA256 AES256-GCM-SHA384 AES128-SHA256 AES256-SHA AES128-SHA Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No Yes Yes No Yes Yes Yes No No Yes Yes No No Custom domain names 757 Amazon API Gateway Developer Guide TLS ciphers TLS_1_0 security policy TLS_1_2 security policy DES-CBC3-SHA Yes No Supported security policies, TLS protocol versions, and ciphers for Regional custom domains The following table describes the security policies for Regional custom domain names. TLS protocols TLS_1_0 security policy TLS_1_2 security policy TLSv1.3 TLSv1.2 TLSv1.1 TLSv1 Yes Yes Yes Yes Yes Yes No No The following table describes the TLS ciphers that are available for each security policy. TLS ciphers TLS_1_0 security policy TLS_1_2 security policy TLS_AES_128_GCM_SHA256 TLS_AES_256_GCM_SHA384 TLS_CHACHA20_POLY1 305_SHA256 Yes Yes Yes Yes Yes Yes Custom domain names 758 Amazon API Gateway Developer Guide TLS ciphers TLS_1_0 security policy TLS_1_2 security policy ECDHE-ECDSA-AES128-GCM- SHA256 ECDHE-RSA-AES128-GCM- SHA256 ECDHE-ECDSA-AES128- SHA256 ECDHE-RSA-AES128-SHA256 ECDHE-ECDSA-AES128-SHA ECDHE-RSA-AES128-SHA ECDHE-ECDSA-AES256-GCM- SHA384 ECDHE-RSA-AES256-GCM- SHA384 ECDHE-ECDSA-AES256- SHA384 ECDHE-RSA-AES256-SHA384 ECDHE-RSA-AES256-SHA ECDHE-ECDSA-AES256-SHA AES128-GCM-SHA256 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No No Yes Yes Yes Yes No No Yes Custom domain names 759 Amazon API Gateway Developer Guide TLS ciphers TLS_1_0 security policy TLS_1_2 security policy AES128-SHA256 AES128-SHA AES256-GCM-SHA384 AES256-SHA256 AES256-SHA Yes Yes Yes Yes Yes Yes No Yes Yes No Supported TLS protocol versions and ciphers for private APIs The following table describes the supported TLS protocols for private APIs. Specifying a security policy for private APIs is not supported. TLS protocols TLSv1.2 TLS_1_2 security policy Yes The following table describes the TLS ciphers that are available for the TLS_1_2 security policy for private APIs. TLS ciphers ECDHE-ECDSA-AES128-GCM-SHA256 TLS_1_2 security policy Yes Custom domain names 760 Amazon API Gateway TLS ciphers ECDHE-RSA-AES128-GCM-SHA256 ECDHE-ECDSA-AES128-SHA256 ECDHE-RSA-AES128-SHA256 ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-GCM-SHA384 ECDHE-ECDSA-AES256-SHA384 ECDHE-RSA-AES256-SHA384 AES128-GCM-SHA256 AES128-SHA256 AES256-GCM-SHA384 AES256-SHA256 Developer Guide TLS_1_2 security policy Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Custom domain names 761 Amazon API Gateway OpenSSL and RFC cipher names Developer Guide OpenSSL and IETF RFC 5246 use different names for the same ciphers. The following table maps the OpenSSL name to the RFC name for each cipher. For more information, see ciphers in the OpenSSL Documentation. OpenSSL cipher name RFC cipher name TLS_AES_1 28_GCM_SH A256 TLS_AES_2 56_GCM_SH A384 TLS_CHACH A20_POLY1 305_SHA256 ECDHE-RSA- AES128-GCM- SHA256 ECDHE-RSA- AES128-SHA256 ECDHE-RSA- AES128-SHA ECDHE-RSA- AES256-GCM- SHA384 ECDHE-RSA- AES256-SHA384 TLS_AES_128_GCM_SHA256 TLS_AES_256_GCM_SHA384 TLS_CHACHA20_POLY1305_SHA256 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 Custom domain names 762 Amazon API Gateway Developer Guide OpenSSL cipher name RFC cipher name ECDHE-RSA- AES256-SHA AES128-GCM- SHA256 AES256-GCM- SHA384 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA TLS_RSA_WITH_AES_128_GCM_SHA256 TLS_RSA_WITH_AES_256_GCM_SHA384 AES128-SHA256 TLS_RSA_WITH_AES_128_CBC_SHA256
|
apigateway-dg-209
|
apigateway-dg.pdf
| 209 |
cipher names Developer Guide OpenSSL and IETF RFC 5246 use different names for the same ciphers. The following table maps the OpenSSL name to the RFC name for each cipher. For more information, see ciphers in the OpenSSL Documentation. OpenSSL cipher name RFC cipher name TLS_AES_1 28_GCM_SH A256 TLS_AES_2 56_GCM_SH A384 TLS_CHACH A20_POLY1 305_SHA256 ECDHE-RSA- AES128-GCM- SHA256 ECDHE-RSA- AES128-SHA256 ECDHE-RSA- AES128-SHA ECDHE-RSA- AES256-GCM- SHA384 ECDHE-RSA- AES256-SHA384 TLS_AES_128_GCM_SHA256 TLS_AES_256_GCM_SHA384 TLS_CHACHA20_POLY1305_SHA256 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 Custom domain names 762 Amazon API Gateway Developer Guide OpenSSL cipher name RFC cipher name ECDHE-RSA- AES256-SHA AES128-GCM- SHA256 AES256-GCM- SHA384 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA TLS_RSA_WITH_AES_128_GCM_SHA256 TLS_RSA_WITH_AES_256_GCM_SHA384 AES128-SHA256 TLS_RSA_WITH_AES_128_CBC_SHA256 AES256-SHA TLS_RSA_WITH_AES_256_CBC_SHA AES128-SHA TLS_RSA_WITH_AES_128_CBC_SHA DES-CBC3-SHA TLS_RSA_WITH_3DES_EDE_CBC_SHA Information about HTTP APIs and WebSocket APIs For more information about HTTP APIs and WebSocket APIs, see the section called “Security policy for HTTP APIs in API Gateway” and the section called “Security policy for WebSocket APIs in API Gateway”. Disable the default endpoint for REST APIs By default, clients can invoke your API by using the execute-api endpoint that API Gateway generates for your API. To ensure that clients can access your API only by using a custom domain name, disable the default execute-api endpoint. Clients can still connect to your default endpoint, but they will receive a 403 Forbidden status code. When you disable the default endpoint, it affects all stages of an API. The following procedure shows how to disable the default endpoint for a REST API. AWS Management Console 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. Custom domain names 763 Amazon API Gateway Developer Guide 3. On the main navigation pane, choose API settings. 4. Choose an API. 5. On API details, choose Edit. 6. For Default endpoint, select Inactive. 7. Choose Save changes. 8. On the main navigation pane, choose Resources. 9. Choose Deploy API. 10. Redeploy your API or create a new stage for the change to take effect. AWS CLI The following update-rest-api command disables the default endpoint: aws apigateway update-rest-api \ --rest-api-id abcdef123 \ --patch-operations op=replace,path=/disableExecuteApiEndpoint,value='True' After you disable the default endpoint, you must deploy your API for the change to take effect. The following create-deployment command creates a deployment: aws apigateway create-deployment \ --rest-api-id abcdef123 \ --stage-name dev Configure custom health checks for DNS failover for an API Gateway API You can use Amazon Route 53 health checks to control DNS failover from an API Gateway API in a primary AWS Region to one in a secondary Region. This can help mitigate impacts in the event of a Regional issue. If you use a custom domain, you can perform failover without requiring clients to change API endpoints. When you choose Evaluate Target Health for an alias record, those records fail only when the API Gateway service is unavailable in the Region. In some cases, your own API Gateway APIs can experience interruption before that time. To control DNS failover directly, configure custom Route 53 health checks for your API Gateway APIs. For this example, you use a CloudWatch alarm Custom domain names 764 Amazon API Gateway Developer Guide that helps operators control DNS failover. For more examples and other considerations when you configure failover, see Creating Disaster Recovery Mechanisms Using Route 53 and Performing Route 53 health checks on private resources in a VPC with AWS Lambda and CloudWatch. Topics • Prerequisites • Step 1: Set up resources • Step 2: Initiate failover to the secondary Region • Step 3: Test the failover • Step 4: Return to the primary region • Next steps: Customize and test regularly Prerequisites To complete this procedure, you must create and configure the following resources: • A domain name that you own. • An ACM certificate for that domain name in two AWS Regions. For more info, see the section called “Prerequisites for custom domain names”. • A Route 53 hosted zone for your domain name. For more information, see Working with hosted zones in the Amazon Route 53 Developer Guide. For more information on how to create Route 53 failover DNS records for the domain names, see Choose a routing policy in the Amazon Route 53 Developer Guide. For more information on how to monitor a CloudWatch alarm, see Monitoring a CloudWatch alarm in the Amazon Route 53 Developer Guide. Step 1: Set up resources In this example, you create the following resources to configure DNS failover for your domain name: • API Gateway APIs in two AWS Regions • API Gateway custom domain names with the same name in two AWS Regions • API Gateway API mappings that connect your API Gateway APIs to the custom domain names • Route 53 failover DNS records for the domain names Custom domain names 765 Amazon API Gateway Developer Guide • A CloudWatch alarm in the secondary Region • A Route 53
|
apigateway-dg-210
|
apigateway-dg.pdf
| 210 |
a CloudWatch alarm in the Amazon Route 53 Developer Guide. Step 1: Set up resources In this example, you create the following resources to configure DNS failover for your domain name: • API Gateway APIs in two AWS Regions • API Gateway custom domain names with the same name in two AWS Regions • API Gateway API mappings that connect your API Gateway APIs to the custom domain names • Route 53 failover DNS records for the domain names Custom domain names 765 Amazon API Gateway Developer Guide • A CloudWatch alarm in the secondary Region • A Route 53 health check based on the CloudWatch alarm in the secondary Region First, make sure that you have all of the required resources in the primary and secondary Regions. The secondary Region should contain the alarm and health check. This way, you don't depend on the primary Region to perform failover. For example AWS CloudFormation templates that create these resources, see primary.yaml and secondary.yaml. Important Before failover to the secondary Region, make sure that all required resources are available. Otherwise, your API won't be ready for traffic in the secondary Region. Step 2: Initiate failover to the secondary Region In the following example, the standby Region receives a CloudWatch metric and initiates failover. We use a custom metric that requires operator intervention to initiate failover. aws cloudwatch put-metric-data \ --metric-name Failover \ --namespace HealthCheck \ --unit Count \ --value 1 \ --region us-west-1 Replace the metric data with the corresponding data for the CloudWatch alarm you configured. Step 3: Test the failover Invoke your API and verify that you get a response from the secondary Region. If you used the example templates in step 1, the response changes from {"message": "Hello from the primary Region!"} to {"message": "Hello from the secondary Region!"} after failover. curl https://my-api.example.com {"message": "Hello from the secondary Region!"} Custom domain names 766 Amazon API Gateway Developer Guide Step 4: Return to the primary region To return to the primary Region, send a CloudWatch metric that causes the health check to pass. aws cloudwatch put-metric-data \ --metric-name Failover \ --namespace HealthCheck \ --unit Count \ --value 0 \ --region us-west-1 Replace the metric data with the corresponding data for the CloudWatch alarm you configured. Invoke your API and verify that you get a response from the primary Region. If you used the example templates in step 1, the response changes from {"message": "Hello from the secondary Region!"} to {"message": "Hello from the primary Region!"}. curl https://my-api.example.com {"message": "Hello from the primary Region!"} Next steps: Customize and test regularly This example demonstrates one way to configure DNS failover. You can use a variety of CloudWatch metrics or HTTP endpoints for the health checks that manage failover. Regularly test your failover mechanisms to make sure that they work as expected, and that operators are familiar with your failover procedures. Optimize performance of REST APIs After you've made your API available to be called, you might realize that it needs to be optimized to improve responsiveness. API Gateway provides a few strategies for optimizing your API, like response caching and payload compression. In this section, you can learn how to enable these capabilities. Topics • Cache settings for REST APIs in API Gateway • Payload compression for REST APIs in API Gateway Optimize 767 Amazon API Gateway Developer Guide Cache settings for REST APIs in API Gateway You can enable API caching in API Gateway to cache your endpoint's responses. With caching, you can reduce the number of calls made to your endpoint and also improve the latency of requests to your API. When you enable caching for a stage, API Gateway caches responses from your endpoint for a specified time-to-live (TTL) period, in seconds. API Gateway then responds to the request by looking up the endpoint response from the cache instead of making a request to your endpoint. The default TTL value for API caching is 300 seconds. The maximum TTL value is 3600 seconds. TTL=0 means caching is disabled. Note Caching is best-effort. You can use the CacheHitCount and CacheMissCount metrics in Amazon CloudWatch to monitor requests that API Gateway serves from the API cache. The maximum size of a response that can be cached is 1048576 bytes. Cache data encryption may increase the size of the response when it is being cached. This is a HIPAA Eligible Service. For more information about AWS, U.S. Health Insurance Portability and Accountability Act of 1996 (HIPAA), and using AWS services to process, store, and transmit protected health information (PHI), see HIPAA Overview. Important When you enable caching for a stage, only GET methods have caching enabled by default. This helps to ensure the safety and availability of your API. You can enable caching for other methods by overriding method settings. Important
|
apigateway-dg-211
|
apigateway-dg.pdf
| 211 |
a response that can be cached is 1048576 bytes. Cache data encryption may increase the size of the response when it is being cached. This is a HIPAA Eligible Service. For more information about AWS, U.S. Health Insurance Portability and Accountability Act of 1996 (HIPAA), and using AWS services to process, store, and transmit protected health information (PHI), see HIPAA Overview. Important When you enable caching for a stage, only GET methods have caching enabled by default. This helps to ensure the safety and availability of your API. You can enable caching for other methods by overriding method settings. Important Caching is charged by the hour based on the cache size that you select. Caching is not eligible for the AWS Free Tier. For more information, see API Gateway Pricing. Cache settings 768 Amazon API Gateway Developer Guide Enable Amazon API Gateway caching In API Gateway, you can enable caching for a specific stage. When you enable caching, you must choose a cache capacity. In general, a larger capacity gives a better performance, but also costs more. For supported cache sizes, see cacheClusterSize in the API Gateway API Reference. API Gateway enables caching by creating a dedicated cache instance. This process can take up to 4 minutes. API Gateway changes caching capacity by removing the existing cache instance and creating a new one with a modified capacity. All existing cached data is deleted. Note The cache capacity affects the CPU, memory, and network bandwidth of the cache instance. As a result, the cache capacity can affect the performance of your cache. API Gateway recommends that you run a 10-minute load test to verify that your cache capacity is appropriate for your workload. Ensure that traffic during the load test mirrors production traffic. For example, include ramp up, constant traffic, and traffic spikes. The load test should include responses that can be served from the cache, as well as unique responses that add items to the cache. Monitor the latency, 4xx, 5xx, cache hit, and cache miss metrics during the load test. Adjust your cache capacity as needed based on these metrics. For more information about load testing, see How do I select the best API Gateway cache capacity to avoid hitting a rate limit?. AWS Management Console In the API Gateway console, you configure caching on the Stages page. You provision the stage cache and specify a default method-level cache setting. If you turn on the default method- level cache, method-level caching is turned on for all GET methods on your stage, unless that method has a method override. Any additional GET methods that you deploy to your stage will have a method-level cache. To configure method-level caching setting for specific methods of your stage, you can use method overrides. For more information about method overrides, see the section called “Override stage caching for method caching”. Cache settings 769 Amazon API Gateway Developer Guide To configure API caching for a given stage: 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose Stages. 3. 4. In the Stages list for the API, choose the stage. In the Stage details section, choose Edit. 5. Under Additional settings, for Cache settings, turn on Provision API cache. This provisions a cache cluster for your stage. 6. To activate caching for your stage, turn on Default method-level caching. This turns on method-level caching for all GET methods on your stage. Any additional GET methods that you deploy to this stage will have a method-level cache. Note If you have an existing setting for a method-level cache, changing the default method-level caching setting doesn't affect that existing setting. 7. Choose Save changes. AWS CLI The following update-stage command updates a stage to provision a cache and turns on method-level caching for all GET methods on your stage: aws apigateway update-stage \ --rest-api-id a1b2c3 \ Cache settings 770 Amazon API Gateway Developer Guide --stage-name 'prod' \ --patch-operations file://patch.json The contents of patch.json are the following: [ { "op": "replace", "path": "/cacheClusterEnabled", "value": "true" }, { "op": "replace", "path": "/cacheClusterSize", "value": "0.5" }, { "op": "replace", "path": "/*/*/caching/enabled", "value": "true" } ] Note If you have an existing setting for a method-level cache, changing the default method- level caching setting doesn't affect that existing setting. Note Creating or deleting a cache takes about 4 minutes for API Gateway to complete. When a cache is created, the Cache cluster value changes from Create in progress to Active. When cache deletion is completed, the Cache cluster value changes from Delete in progress to Inactive. When you turn on method-level caching for all methods on your stage, the Default method-level caching value changes to Active. If you turn off method-level caching for all methods on your stage, the Default method-level caching value changes to Inactive. Cache settings 771
|
apigateway-dg-212
|
apigateway-dg.pdf
| 212 |
default method- level caching setting doesn't affect that existing setting. Note Creating or deleting a cache takes about 4 minutes for API Gateway to complete. When a cache is created, the Cache cluster value changes from Create in progress to Active. When cache deletion is completed, the Cache cluster value changes from Delete in progress to Inactive. When you turn on method-level caching for all methods on your stage, the Default method-level caching value changes to Active. If you turn off method-level caching for all methods on your stage, the Default method-level caching value changes to Inactive. Cache settings 771 Amazon API Gateway Developer Guide If you have an existing setting for a method-level cache, changing the status of the cache doesn't affect that setting. When you enable caching within a stage's Cache settings, only GET methods are cached. To ensure the safety and availability of your API, we recommend that you don't change this setting. However, you can enable caching for other methods by overriding method settings. If you would like to verify if caching is functioning as expected, you have two general options: • Inspect the CloudWatch metrics of CacheHitCount and CacheMissCount for your API and stage. • Put a timestamp in the response. Note Don't use the X-Cache header from the CloudFront response to determine if your API is being served from your API Gateway cache instance. Override API Gateway stage-level caching for method-level caching You can override stage-level cache settings by turning on or turning off caching for a specific method. You can also modify the TTL period or turn encryption on or off for cached responses. If you anticipate that a method that you are caching will receive sensitive data in its responses, encrypt your cache data. You might need to do this to comply with various compliance frameworks. For more information, see Amazon API Gateway controls in the AWS Security Hub User Guide. AWS Management Console If you change the default method-level caching setting in the Stage details, it doesn't affect the method-level cache settings that have overrides. If you anticipate that a method that you are caching will receive sensitive data in its responses, in Cache Settings, choose Encrypt cache data. To configure API caching for individual methods using the console: 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Cache settings 772 Amazon API Gateway 2. Choose the API. 3. Choose Stages. Developer Guide 4. 5. 6. In the Stages list for the API, expand the stage and choose a method in the API. In the Method overrides section, choose Edit. In the Method settings section, turn on or off Enable method cache or customize any other desired options. Note Caching is not active until you provision a cache cluster for your stage. 7. Choose Save. AWS CLI The following update-stage command turns off the cache only for the GET /pets method: aws apigateway update-stage / --rest-api-id a1b2c3 / --stage-name 'prod' / --patch-operations file://patch.json The contents of patch.json are the following: [{ "op": "replace", "path": "/~1pets/GET/caching/enabled", "value": "false" }] Use method or integration parameters as cache keys to index cached responses You can use a method or integration parameter as cache keys to index cached responses. This includes custom headers, URL paths, or query strings. You can specify some or all of these parameters as the cache key, but you must specify at least one value. When you have a cache key, API Gateway caches the responses from each key value separately, including when the cache key isn't present. Cache settings 773 Amazon API Gateway Note Cache keys are required when setting up caching on a resource. For example, suppose you have a request in the following format: Developer Guide GET /users?type=... HTTP/1.1 host: example.com ... In this request, type can take a value of admin or regular. If you include the type parameter as part of the cache key, the responses from GET /users?type=admin are cached separately from those from GET /users?type=regular. When a method or integration request takes more than one parameter, you can choose to include some or all of the parameters to create the cache key. For example, you can include only the type parameter in the cache key for the following request, made in the listed order within a TTL period: GET /users?type=admin&department=A HTTP/1.1 host: example.com ... The response from this request is cached and is used to serve the following request: GET /users?type=admin&department=B HTTP/1.1 host: example.com ... AWS Management Console To include a method or integration request parameter as part of a cache key in the API Gateway console, select Caching after you add the parameter. Cache settings 774 Amazon API Gateway Developer Guide AWS CLI The following put-method command creates a GET method and requires the type query string parameter: aws apigateway put-method /
|
apigateway-dg-213
|
apigateway-dg.pdf
| 213 |
cache key for the following request, made in the listed order within a TTL period: GET /users?type=admin&department=A HTTP/1.1 host: example.com ... The response from this request is cached and is used to serve the following request: GET /users?type=admin&department=B HTTP/1.1 host: example.com ... AWS Management Console To include a method or integration request parameter as part of a cache key in the API Gateway console, select Caching after you add the parameter. Cache settings 774 Amazon API Gateway Developer Guide AWS CLI The following put-method command creates a GET method and requires the type query string parameter: aws apigateway put-method / --rest-api-id a1b2c3 / --resource-id aaa111 / --http-method GET / --authorization-type "NONE" / --request-parameters "method.request.querystring.type=true" The following put-integration command creates an integration for the GET method with an HTTP endpoint and specifies that API Gateway caches the type method request parameter: aws apigateway put-integration / --rest-api-id a1b2c3 / --resource-id aaa111 / Cache settings 775 Amazon API Gateway Developer Guide --http-method GET / --type HTTP / --integration-http-method GET / --uri 'https://example.com' / --cache-key-parameters "method.request.querystring.type" To specify API Gateway cache an integration request parameter, use integration.request.location.name as the cache key parameter. Flush the API stage cache in API Gateway When API caching is enabled, you can flush your API stage's cache to ensure that your API's clients get the most recent responses from your integration endpoints. AWS Management Console To flush the API stage cache 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose an API that has a stage with a cache. 3. In the main navigation pane, choose Stages, and then choose your stage with a cache. 4. Choose the Stage actions menu, and then select Flush stage cache. AWS CLI The following flush-stage-cache command flushes the stage cache: aws apigateway flush-stage-cache \ --rest-api-id a1b2c3 \ --stage-name prod Note After the cache is flushed, responses are serviced from the integration endpoint until the cache is built up again. During this period, the number of requests sent to the integration endpoint may increase. This may temporarily increase the overall latency of your API. Cache settings 776 Amazon API Gateway Developer Guide Invalidate an API Gateway cache entry A client of your API can invalidate an existing cache entry and reload it from the integration endpoint for individual requests. The client must send a request that contains the Cache- Control: max-age=0 header. The client receives the response directly from the integration endpoint instead of the cache, provided that the client is authorized to do so. This replaces the existing cache entry with the new response, which is fetched from the integration endpoint. To grant permission for a client, attach a policy of the following format to an IAM execution role for the user. Note Cross-account cache invalidation is not supported. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:InvalidateCache" ], "Resource": [ "arn:aws:execute-api:region:account-id:api-id/stage-name/GET/resource-path- specifier" ] } ] } This policy allows the API Gateway execution service to invalidate the cache for requests on the specified resource (or resources). To specify a group of targeted resources, use a wildcard (*) character for account-id, api-id, and other entries in the ARN value of Resource. For more information on how to set permissions for the API Gateway execution service, see Control access to a REST API with IAM permissions. Cache settings 777 Amazon API Gateway Developer Guide If you don't impose an InvalidateCache policy (or choose the Require authorization check box in the console), any client can invalidate the API cache. If most or all of the clients invalidate the API cache, this could significantly increase the latency of your API. When the policy is in place, caching is enabled and authorization is required. You can specify how API Gateway handles unauthorized requests by choosing from the following options: Fail the request with 403 status code API Gateway returns a 403 Unauthorized response. To set this option using the API, use FAIL_WITH_403. Ignore cache control header; Add a warning in response header API Gateway processes the request and adds a warning header in the response. To set this option using the API, use SUCCEED_WITH_RESPONSE_HEADER. Ignore cache control header API Gateway processes the request and doesn't add a warning header in the response. To set this option using the API, use SUCCEED_WITHOUT_RESPONSE_HEADER. You can set the unauthorized request handling behavior using the API Gateway console or AWS CLI. AWS Management Console To specify how unauthorized requests are handled 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose an API that has a stage with a cache. 3. 4. 5. In the main navigation pane, choose Stages, and then choose your stage with a cache. For Stage details, choose Edit. For Unauthorized request handling, select an option. 6. Choose Continue. 7. Review your changes and choose Save changes. Cache settings
|
apigateway-dg-214
|
apigateway-dg.pdf
| 214 |
response. To set this option using the API, use SUCCEED_WITHOUT_RESPONSE_HEADER. You can set the unauthorized request handling behavior using the API Gateway console or AWS CLI. AWS Management Console To specify how unauthorized requests are handled 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose an API that has a stage with a cache. 3. 4. 5. In the main navigation pane, choose Stages, and then choose your stage with a cache. For Stage details, choose Edit. For Unauthorized request handling, select an option. 6. Choose Continue. 7. Review your changes and choose Save changes. Cache settings 778 Amazon API Gateway AWS CLI Developer Guide The following update-stage command updates a stage to handle unauthorized requests by failing the request with 403 status code: aws apigateway update-stage / --rest-api-id a1b2c3 / --stage-name 'prod' / --patch-operations 'op=replace,path=/*/*/caching/ unauthorizedCacheControlHeaderStrategy,value="FAIL_WITH_403"' AWS CloudFormation example of a stage with a cache The following AWS CloudFormation template creates an example API, provisions a 0.5 GB cache for the Prod stage, and turns on method-level caching for all GET methods. Important Caching is charged by the hour based on the cache size that you select. Caching is not eligible for the AWS Free Tier. For more information, see API Gateway Pricing. Example AWS CloudFormation template AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Name: cache-example PetsResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'pets' PetsMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref PetsResource Cache settings 779 Amazon API Gateway Developer Guide HttpMethod: GET ApiKeyRequired: true AuthorizationType: NONE Integration: Type: HTTP_PROXY IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ ApiDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: - PetsMethodGet Properties: RestApiId: !Ref Api ApiStage: Type: 'AWS::ApiGateway::Stage' Properties: StageName: Prod Description: Prod Stage with a cache RestApiId: !Ref Api DeploymentId: !Ref ApiDeployment CacheClusterEnabled: True CacheClusterSize: 0.5 MethodSettings: - ResourcePath: /* HttpMethod: '*' CachingEnabled: True Payload compression for REST APIs in API Gateway API Gateway allows your client to call your API with compressed payloads by using one of the supported content codings. By default, API Gateway supports decompression of the method request payload. However, you must configure your API to enable compression of the method response payload. To enable compression on an API, set the minimumCompressionsSize property to a non- negative integer between 0 and 10485760 (10M bytes) when you create the API or after you've created the API. To disable compression on the API, set the minimumCompressionSize to null or remove it altogether. You can enable or disable compression for an API by using the API Gateway console, the AWS CLI, or the API Gateway REST API. If you want the compression applied on a payload of any size, set the minimumCompressionSize value to zero. However, compressing data of a small size might actually increase the final data size. Content encoding 780 Amazon API Gateway Developer Guide Furthermore, compression in API Gateway and decompression in the client might increase overall latency and require more computing times. You should run test cases against your API to determine an optimal value. The client can submit an API request with a compressed payload and an appropriate Content- Encoding header for API Gateway to decompress and apply applicable mapping templates, before passing the request to the integration endpoint. After the compression is enabled and the API is deployed, the client can receive an API response with a compressed payload if it specifies an appropriate Accept-Encoding header in the method request. When the integration endpoint expects and returns uncompressed JSON payloads, any mapping template that's configured for an uncompressed JSON payload is applicable to the compressed payload. For a compressed method request payload, API Gateway decompresses the payload, applies the mapping template, and passes the mapped request to the integration endpoint. For an uncompressed integration response payload, API Gateway applies the mapping template, compresses the mapped payload, and returns the compressed payload to the client. Topics • Enable payload compression for an API in API Gateway • Call an API method with a compressed payload in API Gateway • Receive an API response with a compressed payload in API Gateway Enable payload compression for an API in API Gateway You can enable compression for an API using the API Gateway console, the AWS CLI, or an AWS SDK. For an existing API, you must deploy the API after enabling the compression in order for the change to take effect. For a new API, you can deploy the API after the API setup is complete. Note The highest-priority content encoding must be one supported by API Gateway. If it is not, compression is not applied to the response payload. Topics Content encoding 781 Amazon API Gateway Developer Guide • Enable payload compression for an API using the API Gateway console • Enable payload compression for an API using the AWS CLI • Content codings supported by
|
apigateway-dg-215
|
apigateway-dg.pdf
| 215 |
an AWS SDK. For an existing API, you must deploy the API after enabling the compression in order for the change to take effect. For a new API, you can deploy the API after the API setup is complete. Note The highest-priority content encoding must be one supported by API Gateway. If it is not, compression is not applied to the response payload. Topics Content encoding 781 Amazon API Gateway Developer Guide • Enable payload compression for an API using the API Gateway console • Enable payload compression for an API using the AWS CLI • Content codings supported by API Gateway Enable payload compression for an API using the API Gateway console The following procedure describes how to enable payload compression for an API. To enable payload compression by using the API Gateway console 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose an existing API or create a new one. 3. 4. 5. In the main navigation pane, choose API settings. In the API details section, choose Edit. Turn on Content encoding to enable payload compression. For Minimum body size, enter a number for the minimum compression size (in bytes). To turn off compression, turn off the Content encoding option. 6. Choose Save changes. Enable payload compression for an API using the AWS CLI The following create-rest-api command creates an API with payload compression: aws apigateway create-rest-api \ --name "My test API" \ --minimum-compression-size 0 The following update-rest-api command enables payload compression for an existing API: aws apigateway update-rest-api \ --rest-api-id 1234567890 \ --patch-operations op=replace,path=/minimumCompressionSize,value=0 The minimumCompressionSize property has a non-negative integer value between 0 and 10485760 (10M bytes). It measures the compression threshold. If the payload size is smaller than Content encoding 782 Amazon API Gateway Developer Guide this value, compression or decompression are not applied on the payload. Setting it to zero allows compression for any payload size. The following update-rest-api command turns off payload compression: aws apigateway update-rest-api \ --rest-api-id 1234567890 \ --patch-operations op=replace,path=/minimumCompressionSize,value= You can also set value to an empty string "" or omit the value property altogether in the preceding call. Content codings supported by API Gateway API Gateway supports the following content codings: • deflate • gzip • identity API Gateway also supports the following Accept-Encoding header format, according to the RFC 7231 specification: • Accept-Encoding:deflate,gzip • Accept-Encoding: • Accept-Encoding:* • Accept-Encoding:deflate;q=0.5,gzip;q=1.0 • Accept-Encoding:gzip;q=1.0,identity;q=0.5,*;q=0 Call an API method with a compressed payload in API Gateway To make an API request with a compressed payload, the client must set the Content-Encoding header with one of the supported content codings. Suppose that you're an API client and want to call the PetStore API method (POST /pets). Don't call the method by using the following JSON output: POST /pets Content encoding 783 Amazon API Gateway Developer Guide Host: {petstore-api-id}.execute-api.{region}.amazonaws.com Content-Length: ... { "type": "dog", "price": 249.99 } Instead, you can call the method with the same payload compressed by using the GZIP coding: POST /pets Host: {petstore-api-id}.execute-api.{region}.amazonaws.com Content-Encoding:gzip Content-Length: ... ���RPP*�,HU�RPJ�OW��e&���L,�,-y�j When API Gateway receives the request, it verifies if the specified content coding is supported. Then, it attempts to decompress the payload with the specified content coding. If the decompression is successful, it dispatches the request to the integration endpoint. If the specified coding isn't supported or the supplied payload isn't compressed with specified coding, API Gateway returns the 415 Unsupported Media Type error response. The error is not logged to CloudWatch Logs, if it occurs in the early phase of decompression before your API and stage are identified. Receive an API response with a compressed payload in API Gateway When making a request on a compression-enabled API, the client can choose to receive a compressed response payload of a specific format by specifying an Accept-Encoding header with a supported content coding. API Gateway only compresses the response payload when the following conditions are satisfied: • The incoming request has the Accept-Encoding header with a supported content coding and format. Note If the header is not set, the default value is * as defined in RFC 7231. In such a case, API Gateway does not compress the payload. Some browser or client may add Accept- Content encoding 784 Amazon API Gateway Developer Guide Encoding (for example, Accept-Encoding:gzip, deflate, br) automatically to compression-enabled requests. This can turn on the payload compression in API Gateway. Without an explicit specification of supported Accept-Encoding header values, API Gateway does not compress the payload. • The minimumCompressionSize is set on the API to enable compression. • The integration response doesn't have a Content-Encoding header. • The size of an integration response payload, after the applicable mapping template is applied, is greater than or equal to the specified minimumCompressionSize value. API Gateway applies any mapping template that's configured for the integration response before compressing the payload.
|
apigateway-dg-216
|
apigateway-dg.pdf
| 216 |
Gateway Developer Guide Encoding (for example, Accept-Encoding:gzip, deflate, br) automatically to compression-enabled requests. This can turn on the payload compression in API Gateway. Without an explicit specification of supported Accept-Encoding header values, API Gateway does not compress the payload. • The minimumCompressionSize is set on the API to enable compression. • The integration response doesn't have a Content-Encoding header. • The size of an integration response payload, after the applicable mapping template is applied, is greater than or equal to the specified minimumCompressionSize value. API Gateway applies any mapping template that's configured for the integration response before compressing the payload. If the integration response contains a Content-Encoding header, API Gateway assumes that the integration response payload is already compressed and skips the compression processing. An example is the PetStore API example and the following request: GET /pets Host: {petstore-api-id}.execute-api.{region}.amazonaws.com Accept: application/json The backend responds to the request with an uncompressed JSON payload that's similar to the following: 200 OK [ { "id": 1, "type": "dog", "price": 249.99 }, { "id": 2, "type": "cat", "price": 124.99 }, { "id": 3, Content encoding 785 Amazon API Gateway "type": "fish", "price": 0.99 } ] Developer Guide To receive this output as a compressed payload, your API client can submit a request as follows: GET /pets Host: {petstore-api-id}.execute-api.{region}.amazonaws.com Accept-Encoding:gzip The client receives the response with a Content-Encoding header and GZIP-encoded payload that are similar to the following: 200 OK Content-Encoding:gzip ... ���RP� J�)JV �:P^IeA*������+(�L �X�YZ�ku0L0B7!9��C#�&����Y��a���^�X When the response payload is compressed, only the compressed data size is billed for data transfer. Distribute your REST APIs to clients in API Gateway This section provides details about distributing your API Gateway APIs to your customers. Distributing your API includes generating SDKs for your customers to download and integrate with their client applications, documenting your API so customers know how to call it from their client applications, and making your API available as part of product offerings. Topics • Usage plans and API keys for REST APIs in API Gateway • Documentation for REST APIs in API Gateway • Generate SDKs for REST APIs in API Gateway • Sell your API Gateway APIs through AWS Marketplace Distribute 786 Amazon API Gateway Developer Guide Usage plans and API keys for REST APIs in API Gateway After you create, test, and deploy your APIs, you can use API Gateway usage plans to make them available as product offerings for your customers. You can configure usage plans and API keys to allow customers to access selected APIs, and begin throttling requests to those APIs based on defined limits and quotas. These can be set at the API, or API method level. What are usage plans and API keys? A usage plan specifies who can access one or more deployed API stages and methods—and optionally sets the target request rate to start throttling requests. The plan uses API keys to identify API clients and who can access the associated API stages for each key. API keys are alphanumeric string values that you distribute to application developer customers to grant access to your API. You can use API keys together with Lambda authorizers, IAM roles, or Amazon Cognito to control access to your APIs. API Gateway can generate API keys on your behalf, or you can import them from a CSV file. You can generate an API key in API Gateway, or import it into API Gateway from an external source. For more information, see the section called “Set up API keys using the API Gateway console”. An API key has a name and a value. (The terms "API key" and "API key value" are often used interchangeably.) The name cannot exceed 1024 characters. The value is an alphanumeric string between 20 and 128 characters, for example, apikey1234abcdefghij0123456789. Important API key values must be unique. If you try to create two API keys with different names and the same value, API Gateway considers them to be the same API key. An API key can be associated with more than one usage plan. A usage plan can be associated with more than one stage. However, a given API key can only be associated with one usage plan for each stage of your API. A throttling limit sets the target point at which request throttling should start. This can be set at the API or API method level. A quota limit sets the target maximum number of requests with a given API key that can be submitted within a specified time interval. You can configure individual API methods to require API key authorization based on usage plan configuration. Usage plans 787 Amazon API Gateway Developer Guide Throttling and quota limits apply to requests for individual API keys that are aggregated across all API stages within a usage plan. Note Usage plan throttling and quotas
|
apigateway-dg-217
|
apigateway-dg.pdf
| 217 |
A throttling limit sets the target point at which request throttling should start. This can be set at the API or API method level. A quota limit sets the target maximum number of requests with a given API key that can be submitted within a specified time interval. You can configure individual API methods to require API key authorization based on usage plan configuration. Usage plans 787 Amazon API Gateway Developer Guide Throttling and quota limits apply to requests for individual API keys that are aggregated across all API stages within a usage plan. Note Usage plan throttling and quotas are not hard limits, and are applied on a best-effort basis. In some cases, clients can exceed the quotas that you set. Don’t rely on usage plan quotas or throttling to control costs or block access to an API. Consider using AWS Budgets to monitor costs and AWS WAF to manage API requests. Steps to configure a usage plan and API keys in API Gateway The following tasks outline the required steps to configure a usage plan and API keys. For best practices, see the section called “Best practices for API keys and usage plans”. To configure a usage plan and API keys 1. Create an API and configure the method request for each API method to require an API key. Then, deploy your API to a stage. To include API methods in a usage plan, you must configure individual API methods to require an API key. For more information about how to configure a method to require an API key, see the section called “Require an API key on a method”. 2. Generate or import API keys to distribute to application developers (your customers) who will be using your API. API keys are required for your usage plan. For more information about how to generate or import API keys, see the section called “Create an API key”. 3. Create the usage plan with the desired throttle and quota limits, and then associate API stages and API keys with the usage plan. For more information about how to create the usage plan, see the section called “Create a usage plan”. Callers of the API must supply an assigned API key in the x-api-key header in requests to the API. Usage plans 788 Amazon API Gateway Developer Guide For a complete AWS CloudFormation template that creates and associates a usage plan with a new stage and an API key, see the section called “Create and configure API keys and usage plans with AWS CloudFormation”. Best practices for API keys and usage plans The following are suggested best practices to follow when using API keys and usage plans. Important • Don't use API keys for authentication or authorization to control access to your APIs. If you have multiple APIs in a usage plan, a user with a valid API key for one API in that usage plan can access all APIs in that usage plan. Instead, to control access to your API, use an IAM role, a Lambda authorizer, or an Amazon Cognito user pool. • Use API keys that API Gateway generates. API keys shouldn't include confidential information; clients typically transmit them in headers that can be logged. • If you're using a developer portal to publish your APIs, note that all your APIs in a given usage plan can be subscribed to by customers, even if you haven't made them visible to your customers. • In some cases, clients can exceed the quotas that you set. Don’t rely on usage plans to control costs. Consider using AWS Budgets to monitor costs and AWS WAF to manage API requests. • After you add an API key to a usage plan, the update operation might take a few minutes to complete. Choose an API key source in API Gateway When you associate a usage plan with an API and enable API keys on API methods, every incoming request to the API must contain an API key. API Gateway reads the key and compares it against the keys in the usage plan. If there is a match, API Gateway throttles the requests based on the plan's request limit and quota. Otherwise, it throws an InvalidKeyParameter exception. As a result, the caller receives a 403 Forbidden response. Your API Gateway API can receive API keys from one of two sources: Usage plans 789 Amazon API Gateway HEADER Developer Guide You distribute API keys to your customers and require them to pass the API key as the X-API- Key header of each incoming request. AUTHORIZER You have a Lambda authorizer return the API key as part of the authorization response. For more information on the authorization response, see the section called “Output from an API Gateway Lambda authorizer”. Note For best practices to consider, see
|
apigateway-dg-218
|
apigateway-dg.pdf
| 218 |
an InvalidKeyParameter exception. As a result, the caller receives a 403 Forbidden response. Your API Gateway API can receive API keys from one of two sources: Usage plans 789 Amazon API Gateway HEADER Developer Guide You distribute API keys to your customers and require them to pass the API key as the X-API- Key header of each incoming request. AUTHORIZER You have a Lambda authorizer return the API key as part of the authorization response. For more information on the authorization response, see the section called “Output from an API Gateway Lambda authorizer”. Note For best practices to consider, see the section called “Best practices for API keys and usage plans”. To choose an API key source for an API by using the API Gateway console 1. Sign in to the API Gateway console. 2. Choose an existing API or create a new one. 3. 4. In the main navigation pane, choose API settings. In the API details section, choose Edit. 5. Under API key source, select Header or Authorizer from the dropdown list. 6. Choose Save changes. The following update-rest-api command updates an API to set the API key source to AUTHORIZER: aws apigateway update-rest-api --rest-api-id 1234123412 --patch-operations op=replace,path=/apiKeySource,value=AUTHORIZER To have the client submit an API key, set the value to HEADER in the previous command. To choose an API key source for an API by using the API Gateway REST API, call restapi:update as follows: PATCH /restapis/fugvjdxtri/ HTTP/1.1 Usage plans 790 Amazon API Gateway Developer Guide Content-Type: application/json Host: apigateway.us-east-1.amazonaws.com X-Amz-Date: 20160603T205348Z Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160603/us-east-1/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature={sig4_hash} { "patchOperations" : [ { "op" : "replace", "path" : "/apiKeySource", "value" : "HEADER" } ] } To have an authorizer return an API key, set the value to AUTHORIZER in the previous patchOperations input. Call a method using an API key Depending on the API key source type you choose, use one of the following procedures to use header-sourced API keys or authorizer-returned API keys in method invocation: To use header-sourced API keys: 1. Create an API with desired API methods, and then deploy the API to a stage. 2. Create a new usage plan or choose an existing one. Add the deployed API stage to the usage plan. Attach an API key to the usage plan or choose an existing API key in the plan. Note the chosen API key value. 3. Set up API methods to require an API key. 4. Redeploy the API to the same stage. If you deploy the API to a new stage, make sure to update the usage plan to attach the new API stage. 5. Call the API using the API key. The following example curl command invokes the GET method on the getUsers resource of the prod stage of an API using an API key. curl -H "X-API-Key: abcd1234" 'https://b123abcde4.execute-api.us- west-2.amazonaws.com/prod/getUsers' Usage plans 791 Amazon API Gateway Developer Guide The client can now call the API methods while supplying the x-api-key header with the chosen API key as the header value. A call might look like the following: To use authorizer-sourced API keys: 1. Create an API with desired API methods, and then deploy the API to a stage. 2. Create a new usage plan or choose an existing one. Add the deployed API stage to the usage plan. Attach an API key to the usage plan or choose an existing API key in the plan. Note the chosen API key value. 3. Create a token-based Lambda authorizer. Include, usageIdentifierKey:{api-key} as a root-level property of the authorization response. For instructions on creating a token-based authorizer, see the section called “Example TOKEN authorizer Lambda function”. 4. Set up API methods to require an API key and enable the Lambda authorizer on the methods as well. 5. Redeploy the API to the same stage. If you deploy the API to a new stage, make sure to update the usage plan to attach the new API stage. The client can now call the API key-required methods without explicitly supplying any API key. The authorizer-returned API key is used automatically. Set up API keys using the API Gateway console To set up API keys, do the following: • Configure API methods to require an API key. • Create or import an API key for the API in a region. Before setting up API keys, you must have created an API and deployed it to a stage. After you create an API key value, it cannot be changed. For instructions on how to create and deploy an API by using the API Gateway console, see Develop REST APIs in API Gateway and Deploy REST APIs in API Gateway, respectively. After you create an API key, you must associate it with a usage plan. For more information, see Create, configure, and test usage plans with the
|
apigateway-dg-219
|
apigateway-dg.pdf
| 219 |
API key. • Create or import an API key for the API in a region. Before setting up API keys, you must have created an API and deployed it to a stage. After you create an API key value, it cannot be changed. For instructions on how to create and deploy an API by using the API Gateway console, see Develop REST APIs in API Gateway and Deploy REST APIs in API Gateway, respectively. After you create an API key, you must associate it with a usage plan. For more information, see Create, configure, and test usage plans with the API Gateway console. Usage plans 792 Amazon API Gateway Note Developer Guide For best practices to consider, see the section called “Best practices for API keys and usage plans”. Topics • Require an API key on a method • Create an API key • Import API keys Require an API key on a method The following procedure describes how to configure an API method to require an API key. To configure an API method to require an API key 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. In the API Gateway main navigation pane, choose Resources. 4. Under Resources, create a new method or choose an existing one. 5. On the Method request tab, under Method request settings, choose Edit. Usage plans 793 Amazon API Gateway Developer Guide 6. Select API key required. 7. Choose Save. 8. Deploy or redeploy the API for the requirement to take effect. If the API key required option is set to false and you don't execute the previous steps, any API key that's associated with an API stage isn't used for the method. Create an API key If you've already created or imported API keys for use with usage plans, you can skip this and the next procedure. To create an API key 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. Usage plans 794 Amazon API Gateway 2. Choose a REST API. 3. In the API Gateway main navigation pane, choose API keys. 4. Choose Create API key. Developer Guide 5. 6. 7. For Name, enter a name. (Optional) For Description, enter a description. For API key, choose Auto generate to have API Gateway generate the key value, or choose Custom to create your own key value. 8. Choose Save. Import API keys The following procedure describes how to import API keys to use with usage plans. To import API keys 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 API keys. 4. Choose the Actions dropdown menu, and then choose Import API keys. 5. To load a comma-separated key file, choose Choose file. You can also enter the keys in the text editor. For information about the file format, see the section called “API Gateway API key file format”. 6. Choose Fail on warnings to stop the import when there's an error, or choose Ignore warnings to continue to import valid key entries when there's an warning. 7. Choose Import to import your API keys. Usage plans 795 Amazon API Gateway Developer Guide Create, configure, and test usage plans with the API Gateway console Before creating a usage plan, make sure that you've set up the desired API keys. For more information, see Set up API keys using the API Gateway console. This section describes how to create and use a usage plan by using the API Gateway console. Topics • Migrate your API to default usage plans (if needed) • Create a usage plan • Test a usage plan • Maintain a usage plan Migrate your API to default usage plans (if needed) If you started to use API Gateway after the usage plans feature was rolled out on August 11, 2016, you will automatically have usage plans enabled for you in all supported Regions. If you started to use API Gateway before that date, you might need to migrate to default usage plans. You'll be prompted with the Enable Usage Plans option before using usage plans for the first time in the selected Region. When you enable this option, you have default usage plans created for every unique API stage that's associated with existing API keys. In the default usage plan, no throttle or quota limits are set initially, and the associations between the API keys and API stages are copied to the usage plans. The API behaves the same as before. However, you must use the UsagePlan apiStages property to associate specified API stage values (apiId and stage) with included API keys (via UsagePlanKey), instead of using the ApiKey stageKeys property. To check whether you've already migrated to default usage plans, use the get-account CLI command. In
|
apigateway-dg-220
|
apigateway-dg.pdf
| 220 |
option, you have default usage plans created for every unique API stage that's associated with existing API keys. In the default usage plan, no throttle or quota limits are set initially, and the associations between the API keys and API stages are copied to the usage plans. The API behaves the same as before. However, you must use the UsagePlan apiStages property to associate specified API stage values (apiId and stage) with included API keys (via UsagePlanKey), instead of using the ApiKey stageKeys property. To check whether you've already migrated to default usage plans, use the get-account CLI command. In the command output, the features list includes an entry of "UsagePlans" when usage plans are enabled. You can also migrate your APIs to default usage plans by using the AWS CLI as follows: To migrate to default usage plans using the AWS CLI 1. Call this CLI command: update-account. 2. For the cli-input-json parameter, use the following JSON: Usage plans 796 Developer Guide Amazon API Gateway [ { "op": "add", "path": "/features", "value": "UsagePlans" } ] Create a usage plan The following procedure describes how to create a usage plan. To create a usage plan 1. 2. 3. 4. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. In the API Gateway main navigation pane, choose Usage plans, and then choose Create usage plan. For Name, enter a name. (Optional) For Description, enter a description. 5. By default, usage plans enable throttling. Enter a Rate and a Burst for your usage plan. Choose Throttling to turn off throttling. 6. By default, usage plans enable a quota for a time period. For Requests, enter the total number of requests that a user can make in the time period of your usage plan. Choose Quota to turn off the quota. 7. Choose Create usage plan. Usage plans 797 Amazon API Gateway Developer Guide To add a stage to the usage plan 1. Select your usage plan. 2. Under the Associated stages tab, choose Add stage. 3. 4. 5. For API, select an API. For Stage, select a stage. (Optional) To turn on method-level throttling, do the following: Choose Method-level throttling, and then choose Add method. For Resource, select a resource from your API. a. b. Usage plans 798 Amazon API Gateway Developer Guide c. d. For Method, select a method from your API. Enter a Rate and a Burst for your usage plan. 6. Choose Add to usage plan. To add a key to the usage plan 1. Under the Associated API keys tab, choose Add API key. 2. a. To associate an existing key to your usage plan, select Add existing key, and then select your existing key from the dropdown menu. Usage plans 799 Amazon API Gateway Developer Guide b. To create a new API key, select Create and add new key, and then create a new key. For more information on how to create a new key, see Create an API key. 3. Choose Add API key. Test a usage plan To test the usage plan, you can use an AWS SDK, AWS CLI, or a REST API client like Postman. For an example of using Postman to test the usage plan, see Test usage plans. Maintain a usage plan Maintaining a usage plan involves monitoring the used and remaining quotas over a given time period and, if needed, extending the remaining quotas by a specified amount. The following procedures describe how to monitor quotas. To monitor used and remaining quotas 1. 2. 3. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. In the API Gateway main navigation pane, choose Usage plans. Select a usage plan. 4. Choose the Associated API keys tab to see the number of request remaining for the time period for each key. 5. (Optional) Choose Export usage data, and then choose a From date and a To date. Then choose JSON or CSV for the exported data format, and then choose Export. The following example shows an exported file. { "px1KW6...qBazOJH": [ [ 0, 5000 ], [ 0, 5000 ], [ 0, Usage plans 800 Amazon API Gateway 10 ] ] } Developer Guide The usage data in the example shows the daily usage data for an API client, as identified by the API key (px1KW6...qBazOJH), between August 1, 2016 and August 3, 2016. Each daily usage data shows used and remaining quotas. In this example, the subscriber hasn't used any allotted quotas yet, and the API owner or administrator has reduced the remaining quota from 5000 to 10 on the third day. The following procedures describe how to modify quotas. To extend the remaining quotas 1. 2. 3. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. In the API Gateway main navigation pane, choose Usage plans. Select a usage plan. 4.
|
apigateway-dg-221
|
apigateway-dg.pdf
| 221 |
usage data for an API client, as identified by the API key (px1KW6...qBazOJH), between August 1, 2016 and August 3, 2016. Each daily usage data shows used and remaining quotas. In this example, the subscriber hasn't used any allotted quotas yet, and the API owner or administrator has reduced the remaining quota from 5000 to 10 on the third day. The following procedures describe how to modify quotas. To extend the remaining quotas 1. 2. 3. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. In the API Gateway main navigation pane, choose Usage plans. Select a usage plan. 4. Choose the Associated API keys tab to see the number of request remaining for the time 5. 6. period for each key. Select an API key, and then choose Grant usage extension. Enter a number for the Remaining requests quota. You can increase the renaming requests or decrease the remaining requests for the time period of your usage plan. 7. Choose Update quota. Set up API keys using the API Gateway REST API To set up API keys, do the following: • Configure API methods to require an API key. • Create or import an API key for the API in a region. Before setting up API keys, you must have created an API and deployed it to a stage. After you create an API key value, it cannot be changed. Usage plans 801 Amazon API Gateway Developer Guide For the REST API calls to create and deploy an API, see restapi:create and deployment:create, respectively. Note For best practices to consider, see the section called “Best practices for API keys and usage plans”. Topics • Require an API key on a method • Create or import API keys Require an API key on a method To require an API key on a method, do one of the following: • Call method:put to create a method. Set apiKeyRequired to true in the request payload. • Call method:update to set apiKeyRequired to true. Create or import API keys To create or import an API key, do one of the following: • Call apikey:create to create an API key. • Call apikey:import to import an API key from a file. For the file format, see API Gateway API key file format. You cannot change the value of the new API key. To learn how to configure a usage plan, see Create, configure, and test usage plans using the API Gateway CLI and REST API. Create, configure, and test usage plans using the API Gateway CLI and REST API Before configuring a usage plan, you must have already done the following: set up methods of a selected API to require API keys, deployed or redeployed the API to a stage, and created or imported one or more API keys. For more information, see Set up API keys using the API Gateway REST API. Usage plans 802 Amazon API Gateway Developer Guide To configure a usage plan by using the API Gateway REST API, use the following instructions, assuming that you've already created the APIs to be added to the usage plan. Topics • Migrate to default usage plans • Create a usage plan • Manage a usage plan by using the AWS CLI • Test usage plans Migrate to default usage plans When creating a usage plan the first time, you can migrate existing API stages that are associated with selected API keys to a usage plan by calling account:update with the following body: { "patchOperations" : [ { "op" : "add", "path" : "/features", "value" : "UsagePlans" } ] } For more information about migrating API stages associated with API keys, see Migrate to Default Usage Plans in the API Gateway Console. Create a usage plan The following procedure describes how to create a usage plan. To create a usage plan with the REST API 1. Call usageplan:create to create a usage plan. In the payload, specify the name and description of the plan, associated API stages, rate limits, and quotas. Make note of the resultant usage plan identifier. You need it in the next step. 2. Do one of the following: a. Call usageplankey:create to add an API key to the usage plan. Specify keyId and keyType in the payload. Usage plans 803 Amazon API Gateway Developer Guide To add more API keys to the usage plan, repeat the previous call, one API key at a time. b. Call apikey:import to add one or more API keys directly to the specified usage plan. The request payload should contain API key values, the associated usage plan identifier, the Boolean flags to indicate that the keys are enabled for the usage plan, and, possibly, the API key names and descriptions. The following example of the apikey:import request adds three API keys (as identified by
|
apigateway-dg-222
|
apigateway-dg.pdf
| 222 |
plan. Specify keyId and keyType in the payload. Usage plans 803 Amazon API Gateway Developer Guide To add more API keys to the usage plan, repeat the previous call, one API key at a time. b. Call apikey:import to add one or more API keys directly to the specified usage plan. The request payload should contain API key values, the associated usage plan identifier, the Boolean flags to indicate that the keys are enabled for the usage plan, and, possibly, the API key names and descriptions. The following example of the apikey:import request adds three API keys (as identified by key, name, and description) to one usage plan (as identified by usageplanIds): POST /apikeys?mode=import&format=csv&failonwarnings=fase HTTP/1.1 Host: apigateway.us-east-1.amazonaws.com Content-Type: text/csv Authorization: ... key,name, description, enabled, usageplanIds abcdef1234ghijklmnop8901234567, importedKey_1, firstone, tRuE, n371pt abcdef1234ghijklmnop0123456789, importedKey_2, secondone, TRUE, n371pt abcdef1234ghijklmnop9012345678, importedKey_3, , true, n371pt As a result, three UsagePlanKey resources are created and added to the UsagePlan. You can also add API keys to more than one usage plan this way. To do this, change each usageplanIds column value to a comma-separated string that contains the selected usage plan identifiers, and is enclosed within a pair of quotes ("n371pt,m282qs" or 'n371pt,m282qs'). Note An API key can be associated with more than one usage plan. A usage plan can be associated with more than one stage. However, a given API key can only be associated with one usage plan for each stage of your API. Manage a usage plan by using the AWS CLI The following update-usage-plan examples add, remove, or modify the method-level throttling settings in a usage plan. Usage plans 804 Amazon API Gateway Note Developer Guide Be sure to change us-east-1 to the appropriate Region value for your API. To add or replace a rate limit for throttling an individual resource and method: aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch- operations op="replace",path="/apiStages/apiId:stage/throttle/resourcePath/httpMethod/ rateLimit",value="0.1" To add or replace a burst limit for throttling an individual resource and method: aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch- operations op="replace",path="/apiStages/apiId:stage/throttle/resourcePath/httpMethod/ burstLimit",value="1" To remove the method-level throttling settings for an individual resource and method: aws apigateway --region us-east-1 update-usage-plan --usage-plan- id planId --patch-operations op="remove",path="/apiStages/apiId:stage/ throttle/resourcePath/httpMethod",value="" To remove all method-level throttling settings for an API: aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch- operations op="remove",path="/apiStages/apiId:stage/throttle ",value="" Here is an example using the Pet Store sample API: aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch- operations op="replace",path="/apiStages/apiId:stage/throttle",value='"{\"/pets/GET\": {\"rateLimit\":1.0,\"burstLimit\":1},\"//GET\":{\"rateLimit\":1.0,\"burstLimit\":1}}"' Test usage plans As an example, let's use the PetStore API, which was created in Tutorial: Create a REST API by importing an example. Assume that the API is configured to use an API key of Hiorr45VR...c4GJc. The following steps describe how to test a usage plan. Usage plans 805 Amazon API Gateway To test your usage plan Developer Guide • Make a GET request on the Pets resource (/pets), with the ?type=...&page=... query parameters, of the API (for example, xbvxlpijch) in a usage plan: GET /testStage/pets?type=dog&page=1 HTTP/1.1 x-api-key: Hiorr45VR...c4GJc Content-Type: application/x-www-form-urlencoded Host: xbvxlpijch.execute-api.ap-southeast-1.amazonaws.com X-Amz-Date: 20160803T001845Z Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160803/ap-southeast-1/ execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-api-key, Signature={sigv4_hash} Note You must submit this request to the execute-api component of API Gateway and provide the required API key (for example, Hiorr45VR...c4GJc) in the required x- api-key header. The successful response returns a 200 OK status code and a payload that contains the requested results from the backend. If you forget to set the x-api-key header or set it with an incorrect key, you get a 403 Forbidden response. However, if you didn't configure the method to require an API key, you will likely get a 200 OK response whether you set the x- api-key header correctly or not, and the throttle and quota limits of the usage plan are bypassed. Occasionally, when an internal error occurs where API Gateway is unable to enforce usage plan throttling limits or quotas for the request, API Gateway serves the request without applying the throttling limits or quotas as specified in the usage plan. But, it logs an error message of Usage Plan check failed due to an internal error in CloudWatch. You can ignore such occasional errors. Create and configure API keys and usage plans with AWS CloudFormation You can use AWS CloudFormation to require API keys on API methods and create a usage plan for an API. The example AWS CloudFormation template does the following: Usage plans 806 Amazon API Gateway Developer Guide • Creates an API Gateway API with GET and POST methods. • Requires an API key for the GET and POST methods. This API receives keys from the X-API-KEY header of each incoming request. • Creates an API key. • Creates a usage plan to specify a monthly quota of 1,000 request each month, a throttling rate limit of 100 request each second, and a throttling burst limit of 200 request each second. • Specifies
|
apigateway-dg-223
|
apigateway-dg.pdf
| 223 |
methods and create a usage plan for an API. The example AWS CloudFormation template does the following: Usage plans 806 Amazon API Gateway Developer Guide • Creates an API Gateway API with GET and POST methods. • Requires an API key for the GET and POST methods. This API receives keys from the X-API-KEY header of each incoming request. • Creates an API key. • Creates a usage plan to specify a monthly quota of 1,000 request each month, a throttling rate limit of 100 request each second, and a throttling burst limit of 200 request each second. • Specifies a method-level throttling rate limit of 50 requests each second and a method-level throttling burst limit of 100 requests per second for the GET method. • Associates the API stage and API key with the usage plan. AWSTemplateFormatVersion: 2010-09-09 Parameters: StageName: Type: String Default: v1 Description: Name of API stage. KeyName: Type: String Default: MyKeyName Description: Name of an API key Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Name: keys-api ApiKeySourceType: HEADER PetsResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'pets' PetsMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref PetsResource HttpMethod: GET ApiKeyRequired: true AuthorizationType: NONE Usage plans 807 Amazon API Gateway Developer Guide Integration: Type: HTTP_PROXY IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ PetsMethodPost: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api ResourceId: !Ref PetsResource HttpMethod: POST ApiKeyRequired: true AuthorizationType: NONE Integration: Type: HTTP_PROXY IntegrationHttpMethod: GET Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/ ApiDeployment: Type: 'AWS::ApiGateway::Deployment' DependsOn: - PetsMethodGet Properties: RestApiId: !Ref Api StageName: !Sub '${StageName}' UsagePlan: Type: AWS::ApiGateway::UsagePlan DependsOn: - ApiDeployment Properties: Description: Example usage plan with a monthly quota of 1000 calls and method- level throttling for /pets GET ApiStages: - ApiId: !Ref Api Stage: !Sub '${StageName}' Throttle: "/pets/GET": RateLimit: 50.0 BurstLimit: 100 Quota: Limit: 1000 Period: MONTH Throttle: RateLimit: 100.0 BurstLimit: 200 UsagePlanName: "My Usage Plan" Usage plans 808 Developer Guide Amazon API Gateway ApiKey: Type: AWS::ApiGateway::ApiKey Properties: Description: API Key Name: !Sub '${KeyName}' Enabled: True UsagePlanKey: Type: AWS::ApiGateway::UsagePlanKey Properties: KeyId: !Ref ApiKey KeyType: API_KEY UsagePlanId: !Ref UsagePlan Outputs: ApiRootUrl: Description: Root Url of the API Value: !Sub 'https://${Api}.execute-api.${AWS::Region}.amazonaws.com/${StageName}' Configure a method to use API keys with an OpenAPI definition You can use an OpenAPI definition to require API keys on a method. For each method, create a security requirement object to require an API key to invoke that method. Then, define api_key in the security definition. After you create your API, add the new API stage to your usage plan. The following example creates an API and requires an API key for the POST and GET methods: OpenAPI 2.0 { "swagger" : "2.0", "info" : { "version" : "2024-03-14T20:20:12Z", "title" : "keys-api" }, "basePath" : "/v1", "schemes" : [ "https" ], "paths" : { "/pets" : { "get" : { "responses" : { }, "security" : [ { "api_key" : [ ] Usage plans 809 Amazon API Gateway } ], "x-amazon-apigateway-integration" : { "type" : "http_proxy", "httpMethod" : "GET", Developer Guide "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/", "passthroughBehavior" : "when_no_match" } }, "post" : { "responses" : { }, "security" : [ { "api_key" : [ ] } ], "x-amazon-apigateway-integration" : { "type" : "http_proxy", "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/", "passthroughBehavior" : "when_no_match" } } } }, "securityDefinitions" : { "api_key" : { "type" : "apiKey", "name" : "x-api-key", "in" : "header" } } } OpenAPI 3.0 { "openapi" : "3.0.1", "info" : { "title" : "keys-api", "version" : "2024-03-14T20:20:12Z" }, "servers" : [ { "url" : "{basePath}", "variables" : { "basePath" : { Usage plans 810 Amazon API Gateway Developer Guide "default" : "v1" } } } ], "paths" : { "/pets" : { "get" : { "security" : [ { "api_key" : [ ] } ], "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/", "passthroughBehavior" : "when_no_match", "type" : "http_proxy" } }, "post" : { "security" : [ { "api_key" : [ ] } ], "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/", "passthroughBehavior" : "when_no_match", "type" : "http_proxy" } } } }, "components" : { "securitySchemes" : { "api_key" : { "type" : "apiKey", "name" : "x-api-key", "in" : "header" } } } } Usage plans 811 Amazon API Gateway Developer Guide API Gateway API key file format API Gateway can import API keys from external files of a comma-separated value (CSV) format, and then associate the imported keys with one or more usage plans. The imported file must contain the Name and Key columns. The column header names aren't case sensitive, and columns can be in any order, as shown in the following example: Key,name apikey1234abcdefghij0123456789,MyFirstApiKey A Key value must be between 20 and 128 characters. A Name value cannot exceed 1024 characters. An API key file can also have the Description, Enabled, or UsagePlanIds column, as shown in the following example: Name,key,description,Enabled,usageplanIds MyFirstApiKey,apikey1234abcdefghij0123456789,An imported key,TRUE,c7y23b When a key
|
apigateway-dg-224
|
apigateway-dg.pdf
| 224 |
can import API keys from external files of a comma-separated value (CSV) format, and then associate the imported keys with one or more usage plans. The imported file must contain the Name and Key columns. The column header names aren't case sensitive, and columns can be in any order, as shown in the following example: Key,name apikey1234abcdefghij0123456789,MyFirstApiKey A Key value must be between 20 and 128 characters. A Name value cannot exceed 1024 characters. An API key file can also have the Description, Enabled, or UsagePlanIds column, as shown in the following example: Name,key,description,Enabled,usageplanIds MyFirstApiKey,apikey1234abcdefghij0123456789,An imported key,TRUE,c7y23b When a key is associated with more than one usage plan, the UsagePlanIds value is a comma- separated string of the usage plan IDs, enclosed with a pair of double or single quotes, as shown in the following example: Enabled,Name,key,UsageplanIds true,MyFirstApiKey,apikey1234abcdefghij0123456789,"c7y23b,glvrsr" Unrecognized columns are permitted, but are ignored. The default value is an empty string or a true Boolean value. The same API key can be imported multiple times, with the most recent version overwriting the previous one. Two API keys are identical if they have the same key value. Note For best practices to consider, see the section called “Best practices for API keys and usage plans”. Usage plans 812 Amazon API Gateway Developer Guide Documentation for REST APIs in API Gateway To help customers understand and use your API, you should document the API. To help you document your API, API Gateway lets you add and update the help content for individual API entities as an integral part of your API development process. API Gateway stores the source content and enables you to archive different versions of the documentation. You can associate a documentation version with an API stage, export a stage-specific documentation snapshot to an external OpenAPI file, and distribute the file as a publication of the documentation. To document your API, you can call the API Gateway REST API, use one of the AWS SDKs, use the AWS CLI for API Gateway, or use the API Gateway console. In addition, you can import or export the documentation parts that are defined in an external OpenAPI file. To share API documentation with developers, you can use a developer portal. For an example, see Integrating ReadMe with API Gateway to Keep Your Developer Hub Up to Date or How to Streamline API Development on Amazon API Gateway Using SmartBear’s SwaggerHub on the AWS Partner Network (APN) blog. Topics • Representation of API documentation in API Gateway • Document an API using the API Gateway console • Publish API documentation using the API Gateway console • Document an API using the API Gateway REST API • Publish API documentation using the API Gateway REST API • Import API documentation • Control access to API documentation in API Gateway Representation of API documentation in API Gateway API Gateway API documentation consists of individual documentation parts associated with specific API entities that include API, resource, method, request, response, message parameters (i.e., path, query, header), as well as authorizers and models. In API Gateway, a documentation part is represented by a DocumentationPart resource. The API documentation as a whole is represented by the DocumentationParts collection. API documentation 813 Amazon API Gateway Developer Guide Documenting an API involves creating DocumentationPart instances, adding them to the DocumentationParts collection, and maintaining versions of the documentation parts as your API evolves. Topics • Documentation parts • Documentation versions Documentation parts A DocumentationPart resource is a JSON object that stores the documentation content applicable to an individual API entity. Its properties field contains the documentation content as a map of key-value pairs. Its location property identifies the associated API entity. The shape of a content map is determined by you, the API developer. The value of a key-value pair can be a string, number, boolean, object, or array. The shape of the location object depends on the targeted entity type. The DocumentationPart resource supports content inheritance: the documentation content of an API entity is applicable to children of that API entity. For more information about the definition of child entities and content inheritance, see Inherit Content from an API Entity of More General Specification. Location of a documentation part The location property of a DocumentationPart instance identifies an API entity to which the associated content applies. The API entity can be an API Gateway REST API resource, such as RestApi, Resource, Method, MethodResponse, Authorizer, or Model. The entity can also be a message parameter, such as a URL path parameter, a query string parameter, a request or response header parameter, a request or response body, or response status code. To specify an API entity, set the type attribute of the location object to be one of API, AUTHORIZER, MODEL, RESOURCE, METHOD, PATH_PARAMETER, QUERY_PARAMETER, REQUEST_HEADER, REQUEST_BODY, RESPONSE, RESPONSE_HEADER, or RESPONSE_BODY. Depending
|
apigateway-dg-225
|
apigateway-dg.pdf
| 225 |
location property of a DocumentationPart instance identifies an API entity to which the associated content applies. The API entity can be an API Gateway REST API resource, such as RestApi, Resource, Method, MethodResponse, Authorizer, or Model. The entity can also be a message parameter, such as a URL path parameter, a query string parameter, a request or response header parameter, a request or response body, or response status code. To specify an API entity, set the type attribute of the location object to be one of API, AUTHORIZER, MODEL, RESOURCE, METHOD, PATH_PARAMETER, QUERY_PARAMETER, REQUEST_HEADER, REQUEST_BODY, RESPONSE, RESPONSE_HEADER, or RESPONSE_BODY. Depending on the type of an API entity, you might specify other location attributes, including method, name, path, and statusCode. Not all of these attributes are valid for a given API entity. For example, type, path, name, and statusCode are valid attributes of the RESPONSE entity; only API documentation 814 Amazon API Gateway Developer Guide type and path are valid location attributes of the RESOURCE entity. It is an error to include an invalid field in the location of a DocumentationPart for a given API entity. Not all valid location fields are required. For example, type is both the valid and required location field of all API entities. However, method, path, and statusCode are valid but not required attributes for the RESPONSE entity. When not explicitly specified, a valid location field assumes its default value. The default path value is /, i.e., the root resource of an API. The default value of method, or statusCode is *, meaning any method, or status code values, respectively. Content of a documentation part The properties value is encoded as a JSON string. The properties value contains any information you choose to meet your documentation requirements. For example, the following is a valid content map: { "info": { "description": "My first API with Amazon API Gateway." }, "x-custom-info" : "My custom info, recognized by OpenAPI.", "my-info" : "My custom info not recognized by OpenAPI." } Although API Gateway accepts any valid JSON string as the content map, the content attributes are treated as two categories: those that can be recognized by OpenAPI and those that cannot. In the preceding example, info, description, and x-custom-info are recognized by OpenAPI as a standard OpenAPI object, property, or extension. In contrast, my-info is not compliant with the OpenAPI specification. API Gateway propagates OpenAPI-compliant content attributes into the API entity definitions from the associated DocumentationPart instances. API Gateway does not propagate the non-compliant content attributes into the API entity definitions. As another example, here is DocumentationPart targeted for a Resource entity: { "location" : { "type" : "RESOURCE", "path": "/pets" }, "properties" : { "summary" : "The /pets resource represents a collection of pets in PetStore.", API documentation 815 Amazon API Gateway Developer Guide "description": "... a child resource under the root...", } } Here, both type and path are valid fields to identify the target of the RESOURCE type. For the root resource (/), you can omit the path field. { "location" : { "type" : "RESOURCE" }, "properties" : { "description" : "The root resource with the default path specification." } } This is the same as the following DocumentationPart instance: { "location" : { "type" : "RESOURCE", "path": "/" }, "properties" : { "description" : "The root resource with an explicit path specification" } } Inherit content from an API entity of more general specifications The default value of an optional location field provides a patterned description of an API entity. Using the default value in the location object, you can add a general description in the properties map to a DocumentationPart instance with this type of location pattern. API Gateway extracts the applicable OpenAPI documentation attributes from the DocumentationPart of the generic API entity and injects them into a specific API entity with the location fields matching the general location pattern, or matching the exact value, unless the specific entity already has a DocumentationPart instance associated with it. This behavior is also known as content inheritance from an API entity of more general specifications. Content inheritance does not apply to certain API entity types. See the table below for details. API documentation 816 Amazon API Gateway Developer Guide When an API entity matches more than one DocumentationPart's location pattern, the entity will inherit the documentation part with the location fields of the highest precedence and specificities. The order of precedence is path > statusCode. For matching with the path field, API Gateway chooses the entity with the most specific path value. The following table shows this with a few examples. Case path statusCod name Remarks 1 /pets e * id 2 /pets 200 id Documenta tion associate d with this location pattern will be inherited by entities matching the location pattern. Documenta tion associate d
|
apigateway-dg-226
|
apigateway-dg.pdf
| 226 |
Gateway Developer Guide When an API entity matches more than one DocumentationPart's location pattern, the entity will inherit the documentation part with the location fields of the highest precedence and specificities. The order of precedence is path > statusCode. For matching with the path field, API Gateway chooses the entity with the most specific path value. The following table shows this with a few examples. Case path statusCod name Remarks 1 /pets e * id 2 /pets 200 id Documenta tion associate d with this location pattern will be inherited by entities matching the location pattern. Documenta tion associate d with this location pattern will be API documentation 817 Amazon API Gateway Developer Guide Case path statusCod name Remarks e inherited by entities matching the location pattern when both Case 1 and Case 2 are matched, because Case 2 is more specific than Case 1. API documentation 818 Amazon API Gateway Developer Guide Case path statusCod name Remarks e * id 3 /pets/ petId Documenta tion associate d with this location pattern will be inherited by entities matching the location pattern when Cases 1, 2, and 3 are matched, because Case 3 has a higher precedenc e than Case 2 API documentation 819 Amazon API Gateway Developer Guide Case path statusCod name Remarks e and is more specific than Case 1. Here is another example to contrast a more generic DocumentationPart instance to a more specific one. The following general error message of "Invalid request error" is injected into the OpenAPI definitions of the 400 error responses, unless overridden. { "location" : { "type" : "RESPONSE", "statusCode": "400" }, "properties" : { "description" : "Invalid request error." }" } With the following overwrite, the 400 responses to any methods on the /pets resource has a description of "Invalid petId specified" instead. { "location" : { "type" : "RESPONSE", "path": "/pets", "statusCode": "400" }, "properties" : "{ "description" : "Invalid petId specified." }" } API documentation 820 Amazon API Gateway Developer Guide Valid location fields of DocumentationPart The following table shows the valid and required fields as well as applicable default values of a DocumentationPart resource that is associated with a given type of API entities. Valid location fields { "location": { "type": "API" }, ... } { "location": { "type": "RESOURCE ", "path": "resource_path " }, ... } { "location": { "type": "METHOD", "path": "resource_path ", "method": "http_verb " }, ... } { API entity API Resource Method Query parameter API documentation Required location fields Default field values Inheritable content type N/A No type The default value No of path is /. type The default values of path and method are / and *, respectiv ely. Yes, matching path by prefix and matching method of any values. type The default values of path Yes, matching 821 Amazon API Gateway Developer Guide API entity Valid location fields Required location fields Default field values Inheritable content and method are / and *, respectiv ely. path by prefix and matching method by exact values. "location": { "type": "QUERY_PA RAMETER", "path": "resource_path ", "method": "HTTP_verb ", "name": "query_parameter_na me " }, ... } Request body { "location": { "type": "REQUEST_ BODY", "path": "resource_path ", "method": "http_verb " }, ... } type The default values of path, and method are /and *, respectiv ely. Yes, matching path by prefix, and matching method by exact values. API documentation 822 Amazon API Gateway Developer Guide API entity Valid location fields Required location fields Default field values Inheritable content type, name The default values of path and method are / and *, respectiv ely. type, name The default values of path and method are / and *, respectiv ely. Yes, matching path by prefix and matching method by exact values. Yes, matching path by prefix and matching method by exact values. Request header { "location": { parameter "type": "REQUEST_ HEADER", "path": "resource_path ", "method": "HTTP_verb ", "name": "header_name " }, ... } Request path { "location": { parameter "type": "PATH_PAR AMETER", "path": "resource/{path_para meter_name }", "method": "HTTP_verb ", "name": "path_parameter_name " }, ... } API documentation 823 Amazon API Gateway Developer Guide API entity Response Valid location fields { "location": { "type": "RESPONSE ", "path": "resource_path ", "method": "http_verb ", "statusCode": "status_code " }, ... } Response header { "location": { "type": "RESPONSE _HEADER", "path": "resource_path ", "method": "http_verb ", "statusCode": "status_code ", "name": "header_name " }, ... } Default field values Inheritable content Required location fields type The default values of path, method, and statusCode are /, * and *, respectively. type, name The default values of path, method and statusCode are /, * and *, respectively. Yes, matching path by prefix and matching method and statusCod e by exact values. Yes, matching path by prefix and matching method, and statusCod e by exact values. API documentation
|
apigateway-dg-227
|
apigateway-dg.pdf
| 227 |
"http_verb ", "statusCode": "status_code " }, ... } Response header { "location": { "type": "RESPONSE _HEADER", "path": "resource_path ", "method": "http_verb ", "statusCode": "status_code ", "name": "header_name " }, ... } Default field values Inheritable content Required location fields type The default values of path, method, and statusCode are /, * and *, respectively. type, name The default values of path, method and statusCode are /, * and *, respectively. Yes, matching path by prefix and matching method and statusCod e by exact values. Yes, matching path by prefix and matching method, and statusCod e by exact values. API documentation 824 Amazon API Gateway Developer Guide API entity Valid location fields Response body { "location": { Required location fields type "type": "RESPONSE _BODY", "path": "resource_path ", "method": "http_verb ", "statusCode": "status_code " }, ... } Default field values Inheritable content The default values of path, method and statusCode are /, * and *, respectively. Yes, matching path by prefix and matching method, and statusCod e by exact values. Authorize r { "location": { type N/A No "type": "AUTHORIZ ER", "name": "authorizer_name " }, ... } Model { "location": { "type": "MODEL", type N/A No "name": "model_name " }, ... } API documentation 825 Amazon API Gateway Documentation versions Developer Guide A documentation version is a snapshot of the DocumentationParts collection of an API and is tagged with a version identifier. Publishing the documentation of an API involves creating a documentation version, associating it with an API stage, and exporting that stage-specific version of the API documentation to an external OpenAPI file. In API Gateway, a documentation snapshot is represented as a DocumentationVersion resource. As you update an API, you create new versions of the API. In API Gateway, you maintain all the documentation versions using the DocumentationVersions collection. Document an API using the API Gateway console In this section, we describe how to create and maintain documentation parts of an API using the API Gateway console. A prerequisite for creating and editing the documentation of an API is that you must have already created the API. In this section, we use the PetStore API as an example. To create an API using the API Gateway console, follow the instructions in Tutorial: Create a REST API by importing an example. Topics • Document the API entity • Document a RESOURCE entity • Document a METHOD entity • Document a QUERY_PARAMETER entity • Document a PATH_PARAMETER entity • Document a REQUEST_HEADER entity • Document a REQUEST_BODY entity • Document a RESPONSE entity • Document a RESPONSE_HEADER entity • Document a RESPONSE_BODY entity • Document a MODEL entity • Document an AUTHORIZER entity API documentation 826 Amazon API Gateway Document the API entity Developer Guide To add a new documentation part for the API entity, do the following: 1. In the main navigation pane, choose Documentation, and then choose Create documentation part. 2. For Documentation type, select API. If a documentation part was not created for the API, you get the documentation part's properties map editor. Enter the following properties map in the text editor. { "info": { "description": "Your first API Gateway API.", "contact": { "name": "John Doe", "email": "john.doe@api.com" } } } Note You do not need to encode the properties map into a JSON string. The API Gateway console stringifies the JSON object for you. 3. Choose Create documentation part. To add a new documentation part for the API entity in the Resources pane, do the following: 1. In the main navigation pane, choose Resources. 2. Choose the API actions menu, and then choose Update API documentation. API documentation 827 Amazon API Gateway Developer Guide To edit an existing documentation part, do the following: 1. 2. In the Documentation pane, choose the Resources and methods tab. Select the name of your API, and then on the API card, choose Edit. Document a RESOURCE entity To add a new documentation part for a RESOURCE entity, do the following: 1. 2. 3. 4. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Resource. For Path, enter a path. Enter a description in the text editor, for example: { "description": "The PetStore's root resource." } 5. Choose Create documentation part. You can create documentation for an unlisted resource. 6. If required, repeat these steps to add or edit another documentation part. To add a new documentation part for a RESOURCE entity in the Resources pane, do the following: 1. In the main navigation pane, choose Resources. 2. Choose the resource, and then choose Update documentation. API documentation 828 Amazon API Gateway Developer Guide To edit an existing documentation part, do the following: 1. 2. In the Documentation pane, choose the Resources and methods tab. Select the resource containing your documentation part, and then choose Edit.
|
apigateway-dg-228
|
apigateway-dg.pdf
| 228 |
5. Choose Create documentation part. You can create documentation for an unlisted resource. 6. If required, repeat these steps to add or edit another documentation part. To add a new documentation part for a RESOURCE entity in the Resources pane, do the following: 1. In the main navigation pane, choose Resources. 2. Choose the resource, and then choose Update documentation. API documentation 828 Amazon API Gateway Developer Guide To edit an existing documentation part, do the following: 1. 2. In the Documentation pane, choose the Resources and methods tab. Select the resource containing your documentation part, and then choose Edit. Document a METHOD entity To add a new documentation part for a METHOD entity, do the following: 1. 2. 3. 4. 5. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Method. For Path, enter a path. For Method, select an HTTP verb. Enter a description in the text editor, for example: { "tags" : [ "pets" ], "summary" : "List all pets" } 6. Choose Create documentation part. You can create documentation for an unlisted method. 7. If required, repeat these steps to add or edit another documentation part. To add a new documentation part for a METHOD entity in the Resources pane, do the following: 1. In the main navigation pane, choose Resources. 2. Choose the method, and then choose Update documentation. API documentation 829 Amazon API Gateway Developer Guide To edit an existing documentation part, do the following: 1. In the Documentation pane, choose the Resources and methods tab. 2. You can select the method or select the resource containing the method, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a QUERY_PARAMETER entity To add a new documentation part for a QUERY_PARAMETER entity, do the following: 1. 2. 3. 4. 5. 6. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Query parameter. For Path, enter a path. For Method, select an HTTP verb. For Name, enter a name. Enter a description in the text editor. 7. Choose Create documentation part. You can create documentation for an unlisted query parameter. API documentation 830 Amazon API Gateway Developer Guide 8. If required, repeat these steps to add or edit another documentation part. To edit an existing documentation part, do the following: 1. In the Documentation pane, choose the Resources and methods tab. 2. You can select the query parameter or select the resource containing the query parameter, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a PATH_PARAMETER entity To add a new documentation part for a PATH_PARAMETER entity, do the following: 1. 2. 3. 4. 5. 6. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Path parameter. For Path, enter a path. For Method, select an HTTP verb. For Name, enter a name. Enter a description in the text editor. 7. Choose Create documentation part. You can create documentation for an unlisted path parameter. 8. If required, repeat these steps to add or edit another documentation part. To edit an existing documentation part, do the following: 1. In the Documentation pane, choose the Resources and methods tab. 2. You can select the path parameter or select the resource containing the path parameter, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a REQUEST_HEADER entity To add a new documentation part for a REQUEST_HEADER entity, do the following: API documentation 831 Amazon API Gateway Developer Guide 1. 2. 3. 4. 5. 6. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Request header. For Path, enter a path for the request header. For Method, select an HTTP verb. For Name, enter a name. Enter a description in the text editor. 7. Choose Create documentation part. You can create documentation for an unlisted request header. 8. If required, repeat these steps to add or edit another documentation part. To edit an existing documentation part, do the following: 1. In the Documentation pane, choose the Resources and methods tab. 2. You can select the request header or select the resource containing the request header, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a REQUEST_BODY entity To add a new documentation part for a REQUEST_BODY entity, do the following: 1. 2. 3. 4. 5. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Request body. For Path, enter a path for the request body. For Method, select an HTTP verb. Enter a description in the text
|
apigateway-dg-229
|
apigateway-dg.pdf
| 229 |
pane, choose the Resources and methods tab. 2. You can select the request header or select the resource containing the request header, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a REQUEST_BODY entity To add a new documentation part for a REQUEST_BODY entity, do the following: 1. 2. 3. 4. 5. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Request body. For Path, enter a path for the request body. For Method, select an HTTP verb. Enter a description in the text editor. 6. Choose Create documentation part. You can create documentation for an unlisted request body. 7. If required, repeat these steps to add or edit another documentation part. To edit an existing documentation part, do the following: API documentation 832 Amazon API Gateway Developer Guide 1. In the Documentation pane, choose the Resources and methods tab. 2. You can select the request body or select the resource containing the request body, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a RESPONSE entity To add a new documentation part for a RESPONSE entity, do the following: 1. 2. 3. 4. 5. 6. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Response (status code). For Path, enter a path for the response. For Method, select an HTTP verb. For Status code, enter an HTTP status code. Enter a description in the text editor. 7. Choose Create documentation part. You can create documentation for an unlisted response status code. 8. If required, repeat these steps to add or edit another documentation part. To edit an existing documentation part, do the following: 1. In the Documentation pane, choose the Resources and methods tab. 2. You can select the response status code or select the resource containing the response status code, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a RESPONSE_HEADER entity To add a new documentation part for a RESPONSE_HEADER entity, do the following: 1. In the main navigation pane, choose Documentation, and then choose Create documentation part. 2. For Documentation type, select Response header. API documentation 833 Amazon API Gateway Developer Guide 3. 4. 5. 6. For Path, enter a path for the response header. For Method, select an HTTP verb. For Status code, enter an HTTP status code. Enter a description in the text editor. 7. Choose Create documentation part. You can create documentation for an unlisted response header. 8. If required, repeat these steps to add or edit another documentation part. To edit an existing documentation part, do the following: 1. In the Documentation pane, choose the Resources and methods tab. 2. You can select the response header or select the resource containing the response header, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a RESPONSE_BODY entity To add a new documentation part for a RESPONSE_BODY entity, do the following: 1. 2. 3. 4. 5. 6. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Response body. For Path, enter a path for the response body. For Method, select an HTTP verb. For Status code, enter an HTTP status code. Enter a description in the text editor. 7. Choose Create documentation part. You can create documentation for an unlisted response body. 8. If required, repeat these steps to add or edit another documentation part. To edit an existing documentation part, do the following: 1. In the Documentation pane, choose the Resources and methods tab. API documentation 834 Amazon API Gateway Developer Guide 2. You can select the response body or select the resource containing the response body, and then use the search bar to find and select your documentation part. 3. Choose Edit. Document a MODEL entity Documenting a MODEL entity involves creating and managing DocumentPart instances for the model and each of the model's properties'. For example, for the Error model that comes with every API by default has the following schema definition, { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "Error Schema", "type" : "object", "properties" : { "message" : { "type" : "string" } } } and requires two DocumentationPart instances, one for the Model and the other for its message property: { "location": { "type": "MODEL", "name": "Error" }, "properties": { "title": "Error Schema", "description": "A description of the Error model" } } and { "location": { "type": "MODEL", "name": "Error.message" }, API documentation 835 Amazon API Gateway "properties": { "description": "An error message." } } Developer Guide When the API is exported, the DocumentationPart's properties will override the values in the original schema. To
|
apigateway-dg-230
|
apigateway-dg.pdf
| 230 |
"http://json-schema.org/draft-04/schema#", "title" : "Error Schema", "type" : "object", "properties" : { "message" : { "type" : "string" } } } and requires two DocumentationPart instances, one for the Model and the other for its message property: { "location": { "type": "MODEL", "name": "Error" }, "properties": { "title": "Error Schema", "description": "A description of the Error model" } } and { "location": { "type": "MODEL", "name": "Error.message" }, API documentation 835 Amazon API Gateway "properties": { "description": "An error message." } } Developer Guide When the API is exported, the DocumentationPart's properties will override the values in the original schema. To add a new documentation part for a MODEL entity, do the following: 1. 2. 3. 4. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Model. For Name, enter a name for the model. Enter a description in the text editor. 5. Choose Create documentation part. You can create documentation for unlisted models. 6. If required, repeat these steps to add or edit a documentation part to other models. To add a new documentation part for a MODEL entity in the Models pane, do the following: 1. In the main navigation pane, choose Models. 2. Choose the model, and then choose Update documentation. To edit an existing documentation part, do the following: API documentation 836 Amazon API Gateway Developer Guide 1. In the Documentation pane, choose the Models tab. 2. Use the search bar or select the model, and then choose Edit. Document an AUTHORIZER entity To add a new documentation part for an AUTHORIZER entity, do the following: 1. 2. 3. 4. In the main navigation pane, choose Documentation, and then choose Create documentation part. For Documentation type, select Authorizer. For Name, enter the name of your authorizer. Enter a description in the text editor. Specify a value for the valid location field for the authorizer. 5. Choose Create documentation part. You can create documentation for unlisted authorizers. 6. If required, repeat these steps to add or edit a documentation part to other authorizers. To edit an existing documentation part, do the following: 1. In the Documentation pane, choose the Authorizers tab. 2. Use the search bar or select the authorizer, and then choose Edit. Publish API documentation using the API Gateway console The following procedure describes how to publish a documentation version. To publish a documentation version using the API Gateway console 1. In the main navigation pane, choose Documentation. 2. Choose Publish documentation. 3. Set up the publication: a. b. c. For Stage, select a stage. For Version, enter a version identifier, e.g., 1.0.0. (Optional) For Description, enter a description. 4. Choose Publish. API documentation 837 Amazon API Gateway Developer Guide You can now proceed to download the published documentation by exporting the documentation to an external OpenAPI file. To learn more, see the section called “Export a REST API”. Document an API using the API Gateway REST API In this section, we describe how to create and maintain documentation parts of an API using the API Gateway REST API. Before creating and editing the documentation of an API, first create the API. In this section, we use the PetStore API as an example. To create an API using the API Gateway console, follow the instructions in Tutorial: Create a REST API by importing an example. Topics • Document the API entity • Document a RESOURCE entity • Document a METHOD entity • Document a QUERY_PARAMETER entity • Document a PATH_PARAMETER entity • Document a REQUEST_BODY entity • Document a REQUEST_HEADER entity • Document a RESPONSE entity • Document a RESPONSE_HEADER entity • Document an AUTHORIZER entity • Document a MODEL entity • Update documentation parts • List documentation parts Document the API entity To add documentation for an API, add a DocumentationPart resource for the API entity: POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ API documentation 838 Amazon API Gateway Developer Guide Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "API" }, "properties": "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API Gateway.\"\n\t}\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { ... "id": "s2e5xf", "location": { "path": null, "method": null, "name": null, "statusCode": null, "type": "API" }, "properties": "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API Gateway.\"\n\t}\n}" } If the documentation part has already been added, a 409 Conflict response returns, containing the error message of Documentation part already exists for the specified location: type 'API'." In this case, you must call the documentationpart:update operation. PATCH /restapis/4wk1k4onj3/documentation/parts/part_id HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { API documentation 839 Amazon API Gateway Developer Guide "patchOperations" : [ { "op" : "replace", "path"
|
apigateway-dg-231
|
apigateway-dg.pdf
| 231 |
For example: { ... "id": "s2e5xf", "location": { "path": null, "method": null, "name": null, "statusCode": null, "type": "API" }, "properties": "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API Gateway.\"\n\t}\n}" } If the documentation part has already been added, a 409 Conflict response returns, containing the error message of Documentation part already exists for the specified location: type 'API'." In this case, you must call the documentationpart:update operation. PATCH /restapis/4wk1k4onj3/documentation/parts/part_id HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { API documentation 839 Amazon API Gateway Developer Guide "patchOperations" : [ { "op" : "replace", "path" : "/properties", "value" : "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API Gateway.\"\n\t}\n}" } ] } The successful response returns a 200 OK status code with the payload containing the updated DocumentationPart instance in the payload. Document a RESOURCE entity To add documentation for the root resource of an API, add a DocumentationPart resource targeted for the corresponding Resource resource: POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "RESOURCE", }, "properties" : "{\n\t\"description\" : \"The PetStore root resource.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, API documentation 840 Amazon API Gateway "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo" Developer Guide } }, "id": "p76vqo", "location": { "path": "/", "method": null, "name": null, "statusCode": null, "type": "RESOURCE" }, "properties": "{\n\t\"description\" : \"The PetStore root resource.\"\n}" } When the resource path is not specified, the resource is assumed to be the root resource. You can add "path": "/" to properties to make the specification explicit. To create documentation for a child resource of an API, add a DocumentationPart resource targeted for the corresponding Resource resource: POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "RESOURCE", "path" : "/pets" }, "properties": "{\n\t\"description\" : \"A child resource under the root of PetStore.\"\n}" } API documentation 841 Amazon API Gateway Developer Guide If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/qcht86" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/qcht86" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/qcht86" } }, "id": "qcht86", "location": { "path": "/pets", "method": null, "name": null, "statusCode": null, "type": "RESOURCE" }, "properties": "{\n\t\"description\" : \"A child resource under the root of PetStore. \"\n}" } To add documentation for a child resource specified by a path parameter, add a DocumentationPart resource targeted for the Resource resource: POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret API documentation 842 Amazon API Gateway Developer Guide { "location" : { "type" : "RESOURCE", "path" : "/pets/{petId}" }, "properties": "{\n\t\"description\" : \"A child resource specified by the petId path parameter.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb" } }, "id": "k6fpwb", "location": { "path": "/pets/{petId}", "method": null, "name": null, "statusCode": null, "type": "RESOURCE" }, "properties": "{\n\t\"description\" : \"A child resource specified by the petId path parameter.\"\n}" } API documentation 843 Amazon API Gateway Note Developer Guide The DocumentationPart instance of a RESOURCE entity cannot be inherited by any of its child resources. Document a METHOD entity To add documentation for a method of an API, add a DocumentationPart resource targeted for the corresponding Method resource: POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "METHOD", "path" : "/pets", "method" : "GET" }, "properties": "{\n\t\"summary\" : \"List all pets.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, API documentation 844 Amazon API Gateway Developer Guide "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" } }, "id": "o64jbj", "location": { "path": "/pets", "method": "GET", "name": null, "statusCode": null, "type": "METHOD" }, "properties": "{\n\t\"summary\" : \"List all pets.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }
|
apigateway-dg-232
|
apigateway-dg.pdf
| 232 |
documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, API documentation 844 Amazon API Gateway Developer Guide "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" } }, "id": "o64jbj", "location": { "path": "/pets", "method": "GET", "name": null, "statusCode": null, "type": "METHOD" }, "properties": "{\n\t\"summary\" : \"List all pets.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" } }, "id": "o64jbj", "location": { "path": "/pets", "method": "GET", API documentation 845 Amazon API Gateway "name": null, "statusCode": null, "type": "METHOD" }, "properties": "{\n\t\"summary\" : \"List all pets.\"\n}" } Developer Guide If the location.method field is not specified in the preceding request, it is assumed to be ANY method that is represented by a wild card * character. To update the documentation content of a METHOD entity, call the documentationpart:update operation, supplying a new properties map: PATCH /restapis/4wk1k4onj3/documentation/parts/part_id HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "patchOperations" : [ { "op" : "replace", "path" : "/properties", "value" : "{\n\t\"tags\" : [ \"pets\" ], \n\t\"summary\" : \"List all pets.\"\n}" } ] } The successful response returns a 200 OK status code with the payload containing the updated DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" API documentation 846 Amazon API Gateway }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj" Developer Guide } }, "id": "o64jbj", "location": { "path": "/pets", "method": "GET", "name": null, "statusCode": null, "type": "METHOD" }, "properties": "{\n\t\"tags\" : [ \"pets\" ], \n\t\"summary\" : \"List all pets.\"\n}" } Document a QUERY_PARAMETER entity To add documentation for a request query parameter, add a DocumentationPart resource targeted for the QUERY_PARAMETER type, with the valid fields of path and name. POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "QUERY_PARAMETER", "path" : "/pets", "method" : "GET", "name" : "page" }, "properties": "{\n\t\"description\" : \"Page number of results to return.\"\n}" } API documentation 847 Amazon API Gateway Developer Guide If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w" } }, "id": "h9ht5w", "location": { "path": "/pets", "method": "GET", "name": "page", "statusCode": null, "type": "QUERY_PARAMETER" }, "properties": "{\n\t\"description\" : \"Page number of results to return.\"\n}" } The documentation part's properties map of a QUERY_PARAMETER entity can be inherited by one of its child QUERY_PARAMETER entities. For example, if you add a treats resource after / pets/{petId}, enable the GET method on /pets/{petId}/treats, and expose the page query parameter, this child query parameter inherits the DocumentationPart's properties map from the like-named query parameter of the GET /pets method, unless you explicitly add a DocumentationPart resource to the page query parameter of the GET /pets/{petId}/ treats method. API documentation 848 Amazon API Gateway Developer Guide Document a PATH_PARAMETER entity To add documentation for a path parameter, add a DocumentationPart resource for the PATH_PARAMETER entity. POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "PATH_PARAMETER", "path" : "/pets/{petId}", "method" : "*", "name" : "petId" }, "properties": "{\n\t\"description\" : \"The id of the pet to retrieve.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog" } API documentation 849 Amazon API Gateway }, "id": "ckpgog", "location": { "path": "/pets/{petId}", "method": "*", "name": "petId", "statusCode": null, "type": "PATH_PARAMETER" }, Developer Guide "properties": "{\n \"description\" : \"The id of the pet to retrieve\"\n}" } Document a REQUEST_BODY entity To add documentation for a request body, add a DocumentationPart resource for the request body. POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "REQUEST_BODY", "path" : "/pets", "method" : "POST" }, "properties": "{\n\t\"description\" : \"A Pet object to be added to PetStore.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", API documentation 850 Amazon API Gateway "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1" }, "documentationpart:update": {
|
apigateway-dg-233
|
apigateway-dg.pdf
| 233 |
add a DocumentationPart resource for the request body. POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "REQUEST_BODY", "path" : "/pets", "method" : "POST" }, "properties": "{\n\t\"description\" : \"A Pet object to be added to PetStore.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", API documentation 850 Amazon API Gateway "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1" Developer Guide } }, "id": "kgmfr1", "location": { "path": "/pets", "method": "POST", "name": null, "statusCode": null, "type": "REQUEST_BODY" }, "properties": "{\n\t\"description\" : \"A Pet object to be added to PetStore.\"\n}" } Document a REQUEST_HEADER entity To add documentation for a request header, add a DocumentationPart resource for the request header. POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "REQUEST_HEADER", "path" : "/pets", "method" : "GET", "name" : "x-my-token" }, API documentation 851 Amazon API Gateway Developer Guide "properties": "{\n\t\"description\" : \"A custom token used to authorization the method invocation.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf" } }, "id": "h0m3uf", "location": { "path": "/pets", "method": "GET", "name": "x-my-token", "statusCode": null, "type": "REQUEST_HEADER" }, "properties": "{\n\t\"description\" : \"A custom token used to authorization the method invocation.\"\n}" } Document a RESPONSE entity To add documentation for a response of a status code, add a DocumentationPart resource targeted for the corresponding MethodResponse resource. POST /restapis/restapi_id/documentation/parts HTTP/1.1 API documentation 852 Amazon API Gateway Developer Guide Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location": { "path": "/", "method": "*", "name": null, "statusCode": "200", "type": "RESPONSE" }, "properties": "{\n \"description\" : \"Successful operation.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/lattew" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/lattew" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/lattew" } }, "id": "lattew", "location": { "path": "/", "method": "*", "name": null, "statusCode": "200", "type": "RESPONSE" }, "properties": "{\n \"description\" : \"Successful operation.\"\n}" } API documentation 853 Amazon API Gateway Developer Guide Document a RESPONSE_HEADER entity To add documentation for a response header, add a DocumentationPart resource for the response header. POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret "location": { "path": "/", "method": "GET", "name": "Content-Type", "statusCode": "200", "type": "RESPONSE_HEADER" }, "properties": "{\n \"description\" : \"Media type of request\"\n}" If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7" } }, API documentation 854 Amazon API Gateway "id": "fev7j7", "location": { "path": "/", "method": "GET", "name": "Content-Type", "statusCode": "200", "type": "RESPONSE_HEADER" }, Developer Guide "properties": "{\n \"description\" : \"Media type of request\"\n}" } The documentation of this Content-Type response header is the default documentation for the Content-Type headers of any responses of the API. Document an AUTHORIZER entity To add documentation for an API authorizer, add a DocumentationPart resource targeted for the specified authorizer. POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "AUTHORIZER", "name" : "myAuthorizer" }, "properties": "{\n\t\"description\" : \"Authorizes invocations of configured methods.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { API documentation 855 Amazon API Gateway Developer Guide "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3" } }, "id": "pw3qw3", "location": { "path": null, "method": null, "name": "myAuthorizer", "statusCode": null, "type": "AUTHORIZER" }, "properties": "{\n\t\"description\" : \"Authorizes invocations of configured methods. \"\n}" } Note The DocumentationPart instance of an AUTHORIZER entity cannot be inherited by any of its child resources. Document a MODEL entity Documenting a MODEL entity involves creating and managing DocumentPart instances for the model and each of the model's properties'. For example, for the Error model that comes with every API by default has the following schema definition, { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "Error Schema", API documentation 856 Amazon API Gateway Developer Guide "type" : "object", "properties" : { "message" : { "type" : "string" }
|
apigateway-dg-234
|
apigateway-dg.pdf
| 234 |
"type": "AUTHORIZER" }, "properties": "{\n\t\"description\" : \"Authorizes invocations of configured methods. \"\n}" } Note The DocumentationPart instance of an AUTHORIZER entity cannot be inherited by any of its child resources. Document a MODEL entity Documenting a MODEL entity involves creating and managing DocumentPart instances for the model and each of the model's properties'. For example, for the Error model that comes with every API by default has the following schema definition, { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "Error Schema", API documentation 856 Amazon API Gateway Developer Guide "type" : "object", "properties" : { "message" : { "type" : "string" } } } and requires two DocumentationPart instances, one for the Model and the other for its message property: { "location": { "type": "MODEL", "name": "Error" }, "properties": { "title": "Error Schema", "description": "A description of the Error model" } } and { "location": { "type": "MODEL", "name": "Error.message" }, "properties": { "description": "An error message." } } When the API is exported, the DocumentationPart's properties will override the values in the original schema. To add documentation for an API model, add a DocumentationPart resource targeted for the specified model. POST /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ API documentation 857 Amazon API Gateway Developer Guide Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "location" : { "type" : "MODEL", "name" : "Pet" }, "properties": "{\n\t\"description\" : \"Data structure of a Pet object.\"\n}" } If successful, the operation returns a 201 Created response containing the newly created DocumentationPart instance in the payload. For example: { "_links": { "curies": { "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi- documentationpart-{rel}.html", "name": "documentationpart", "templated": true }, "self": { "href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq" }, "documentationpart:delete": { "href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq" }, "documentationpart:update": { "href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq" } }, "id": "lkn4uq", "location": { "path": null, "method": null, "name": "Pet", "statusCode": null, "type": "MODEL" }, "properties": "{\n\t\"description\" : \"Data structure of a Pet object.\"\n}" } API documentation 858 Amazon API Gateway Developer Guide Repeat the same step to create a DocumentationPart instance for any of the model's properties. Note The DocumentationPart instance of a MODEL entity cannot be inherited by any of its child resources. Update documentation parts To update the documentation parts of any type of API entities, submit a PATCH request on a DocumentationPart instance of a specified part identifier to replace the existing properties map with a new one. PATCH /restapis/4wk1k4onj3/documentation/parts/part_id HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "patchOperations" : [ { "op" : "replace", "path" : "RESOURCE_PATH", "value" : "NEW_properties_VALUE_AS_JSON_STRING" } ] } The successful response returns a 200 OK status code with the payload containing the updated DocumentationPart instance in the payload. You can update multiple documentation parts in a single PATCH request. List documentation parts To list the documentation parts of any type of API entities, submit a GET request on a DocumentationParts collection. GET /restapis/restapi_id/documentation/parts HTTP/1.1 Host: apigateway.region.amazonaws.com API documentation 859 Amazon API Gateway Developer Guide Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret The successful response returns a 200 OK status code with the payload containing the available DocumentationPart instances in the payload. Publish API documentation using the API Gateway REST API To publish the documentation for an API, create, update, or get a documentation snapshot, and then associate the documentation snapshot with an API stage. When creating a documentation snapshot, you can also associate it with an API stage at the same time. Topics • Create a documentation snapshot and associate it with an API stage • Create a documentation snapshot • Update a documentation snapshot • Get a documentation snapshot • Associate a documentation snapshot with an API stage • Download a documentation snapshot associated with a stage Create a documentation snapshot and associate it with an API stage To create a snapshot of an API's documentation parts and associate it with an API stage at the same time, submit the following POST request: POST /restapis/restapi_id/documentation/versions HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "documentationVersion" : "1.0.0", "stageName": "prod", API documentation 860 Amazon API Gateway Developer Guide "description" : "My API Documentation v1.0.0" } If successful, the operation returns a 200 OK response, containing the newly created DocumentationVersion instance as the payload. Alternatively, you can create a documentation snapshot without associating it with an API stage first and then call restapi:update to associate the snapshot with a specified API stage. You can also update or query an existing documentation snapshot and then update its stage association. We show the steps in the next four sections. Create a documentation snapshot To create a snapshot of an API's documentation parts, create a new DocumentationVersion resource and add it to the DocumentationVersions collection of the API: POST /restapis/restapi_id/documentation/versions HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "documentationVersion" : "1.0.0", "description"
|
apigateway-dg-235
|
apigateway-dg.pdf
| 235 |
you can create a documentation snapshot without associating it with an API stage first and then call restapi:update to associate the snapshot with a specified API stage. You can also update or query an existing documentation snapshot and then update its stage association. We show the steps in the next four sections. Create a documentation snapshot To create a snapshot of an API's documentation parts, create a new DocumentationVersion resource and add it to the DocumentationVersions collection of the API: POST /restapis/restapi_id/documentation/versions HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "documentationVersion" : "1.0.0", "description" : "My API Documentation v1.0.0" } If successful, the operation returns a 200 OK response, containing the newly created DocumentationVersion instance as the payload. Update a documentation snapshot You can only update a documentation snapshot by modifying the description property of the corresponding DocumentationVersion resource. The following example shows how to update the description of the documentation snapshot as identified by its version identifier, version, e.g., 1.0.0. PATCH /restapis/restapi_id/documentation/versions/version HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json API documentation 861 Amazon API Gateway X-Amz-Date: YYYYMMDDTttttttZ Developer Guide Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "patchOperations": [{ "op": "replace", "path": "/description", "value": "My API for testing purposes." }] } If successful, the operation returns a 200 OK response, containing the updated DocumentationVersion instance as the payload. Get a documentation snapshot To get a documentation snapshot, submit a GET request against the specified DocumentationVersion resource. The following example shows how to get a documentation snapshot of a given version identifier, 1.0.0. GET /restapis/<restapi_id>/documentation/versions/1.0.0 HTTP/1.1 Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret Associate a documentation snapshot with an API stage To publish the API documentation, associate a documentation snapshot with an API stage. You must have already created an API stage before associating the documentation version with the stage. To associate a documentation snapshot with an API stage using the API Gateway REST API, call the stage:update operation to set the desired documentation version on the stage.documentationVersion property: PATCH /restapis/RESTAPI_ID/stages/STAGE_NAME Host: apigateway.region.amazonaws.com API documentation 862 Amazon API Gateway Developer Guide Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "patchOperations": [{ "op": "replace", "path": "/documentationVersion", "value": "VERSION_IDENTIFIER" }] } Download a documentation snapshot associated with a stage After a version of the documentation parts is associated with a stage, you can export the documentation parts together with the API entity definitions, to an external file, using the API Gateway console, the API Gateway REST API, one of its SDKs, or the AWS CLI for API Gateway. The process is the same as for exporting the API. The exported file format can be JSON or YAML. Using the API Gateway REST API, you can also explicitly set the extension=documentation,integrations,authorizers query parameter to include the API documentation parts, API integrations and authorizers in an API export. By default, documentation parts are included, but integrations and authorizers are excluded, when you export an API. The default output from an API export is suited for distribution of the documentation. To export the API documentation in an external JSON OpenAPI file using the API Gateway REST API, submit the following GET request: GET /restapis/restapi_id/stages/stage_name/exports/swagger?extensions=documentation HTTP/1.1 Accept: application/json Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret Here, the x-amazon-apigateway-documentation object contains the documentation parts and the API entity definitions contains the documentation properties API documentation 863 Amazon API Gateway Developer Guide supported by OpenAPI. The output does not include details of integration or Lambda authorizers (formerly known as custom authorizers). To include both details, set extensions=integrations,authorizers,documentation. To include details of integrations but not of authorizers, set extensions=integrations,documentation. You must set the Accept:application/json header in the request to output the result in a JSON file. To produce the YAML output, change the request header to Accept:application/ yaml. As an example, we will look at an API that exposes a simple GET method on the root resource (/). This API has four API entities defined in an OpenAPI definition file, one for each of the API, MODEL, METHOD, and RESPONSE types. A documentation part has been added to each of the API, METHOD, and RESPONSE entities. Calling the preceding documentation-exporting command, we get the following output, with the documentation parts listed within the x-amazon-apigateway- documentation object as an extension to a standard OpenAPI file. OpenAPI 3.0 { "openapi": "3.0.0", "info": { "description": "API info description", "version": "2016-11-22T22:39:14Z", "title": "doc", "x-bar": "API info x-bar" }, "paths": { "/": { "get": { "description": "Method description.", "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, API documentation 864 Amazon API Gateway Developer Guide "x-example": "x- Method example" }, "x-bar": "resource x-bar" } }, "x-amazon-apigateway-documentation": { "version": "1.0.0", "createdDate": "2016-11-22T22:41:40Z", "documentationParts": [ { "location": { "type":
|
apigateway-dg-236
|
apigateway-dg.pdf
| 236 |
the following output, with the documentation parts listed within the x-amazon-apigateway- documentation object as an extension to a standard OpenAPI file. OpenAPI 3.0 { "openapi": "3.0.0", "info": { "description": "API info description", "version": "2016-11-22T22:39:14Z", "title": "doc", "x-bar": "API info x-bar" }, "paths": { "/": { "get": { "description": "Method description.", "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } }, API documentation 864 Amazon API Gateway Developer Guide "x-example": "x- Method example" }, "x-bar": "resource x-bar" } }, "x-amazon-apigateway-documentation": { "version": "1.0.0", "createdDate": "2016-11-22T22:41:40Z", "documentationParts": [ { "location": { "type": "API" }, "properties": { "description": "API description", "foo": "API foo", "x-bar": "API x-bar", "info": { "description": "API info description", "version": "API info version", "foo": "API info foo", "x-bar": "API info x-bar" } } }, { "location": { "type": "METHOD", "method": "GET" }, "properties": { "description": "Method description.", "x-example": "x- Method example", "foo": "Method foo", "info": { "version": "method info version", "description": "method info description", "foo": "method info foo" } } }, { "location": { "type": "RESOURCE" API documentation 865 Amazon API Gateway }, Developer Guide "properties": { "description": "resource description", "foo": "resource foo", "x-bar": "resource x-bar", "info": { "description": "resource info description", "version": "resource info version", "foo": "resource info foo", "x-bar": "resource info x-bar" } } } ] }, "x-bar": "API x-bar", "servers": [ { "url": "https://rznaap68yi.execute-api.ap-southeast-1.amazonaws.com/ {basePath}", "variables": { "basePath": { "default": "/test" } } } ], "components": { "schemas": { "Empty": { "type": "object", "title": "Empty Schema" } } } } OpenAPI 2.0 { "swagger" : "2.0", "info" : { "description" : "API info description", API documentation 866 Amazon API Gateway Developer Guide "version" : "2016-11-22T22:39:14Z", "title" : "doc", "x-bar" : "API info x-bar" }, "host" : "rznaap68yi.execute-api.ap-southeast-1.amazonaws.com", "basePath" : "/test", "schemes" : [ "https" ], "paths" : { "/" : { "get" : { "description" : "Method description.", "produces" : [ "application/json" ], "responses" : { "200" : { "description" : "200 response", "schema" : { "$ref" : "#/definitions/Empty" } } }, "x-example" : "x- Method example" }, "x-bar" : "resource x-bar" } }, "definitions" : { "Empty" : { "type" : "object", "title" : "Empty Schema" } }, "x-amazon-apigateway-documentation" : { "version" : "1.0.0", "createdDate" : "2016-11-22T22:41:40Z", "documentationParts" : [ { "location" : { "type" : "API" }, "properties" : { "description" : "API description", "foo" : "API foo", "x-bar" : "API x-bar", "info" : { "description" : "API info description", API documentation 867 Amazon API Gateway Developer Guide "version" : "API info version", "foo" : "API info foo", "x-bar" : "API info x-bar" } } }, { "location" : { "type" : "METHOD", "method" : "GET" }, "properties" : { "description" : "Method description.", "x-example" : "x- Method example", "foo" : "Method foo", "info" : { "version" : "method info version", "description" : "method info description", "foo" : "method info foo" } } }, { "location" : { "type" : "RESOURCE" }, "properties" : { "description" : "resource description", "foo" : "resource foo", "x-bar" : "resource x-bar", "info" : { "description" : "resource info description", "version" : "resource info version", "foo" : "resource info foo", "x-bar" : "resource info x-bar" } } } ] }, "x-bar" : "API x-bar" } For an OpenAPI-compliant attribute defined in the properties map of a documentation part, API Gateway inserts the attribute into the associated API entity definition. An attribute of API documentation 868 Amazon API Gateway Developer Guide x-something is a standard OpenAPI extension. This extension gets propagated into the API entity definition. For example, see the x-example attribute for the GET method. An attribute like foo is not part of the OpenAPI specification and is not injected into its associated API entity definitions. If a documentation-rendering tool (e.g., OpenAPI UI) parses the API entity definitions to extract documentation attributes, any non OpenAPI-compliant properties attributes of a DocumentationPart' instance are not available for the tool. However, if a documentation- rendering tool parses the x-amazon-apigateway-documentation object to get content, or if the tool calls restapi:documentation-parts and documenationpart:by-id to retrieve documentation parts from API Gateway, all the documentation attributes are available for the tool to display. To export the documentation with API entity definitions containing integration details to a JSON OpenAPI file, submit the following GET request: GET /restapis/restapi_id/stages/stage_name/exports/swagger? extensions=integrations,documentation HTTP/1.1 Accept: application/json Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret To export the documentation with API entity definitions containing details of integrations and authorizers to a YAML OpenAPI file, submit the following GET request: GET /restapis/restapi_id/stages/stage_name/exports/swagger? extensions=integrations,authorizers,documentation HTTP/1.1 Accept: application/yaml Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret To use the API Gateway console to export and download the published documentation of an API, follow the instructions in Export REST API using the API Gateway console. API documentation 869 Amazon API
|
apigateway-dg-237
|
apigateway-dg.pdf
| 237 |
OpenAPI file, submit the following GET request: GET /restapis/restapi_id/stages/stage_name/exports/swagger? extensions=integrations,documentation HTTP/1.1 Accept: application/json Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret To export the documentation with API entity definitions containing details of integrations and authorizers to a YAML OpenAPI file, submit the following GET request: GET /restapis/restapi_id/stages/stage_name/exports/swagger? extensions=integrations,authorizers,documentation HTTP/1.1 Accept: application/yaml Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret To use the API Gateway console to export and download the published documentation of an API, follow the instructions in Export REST API using the API Gateway console. API documentation 869 Amazon API Gateway Developer Guide Import API documentation As with importing API entity definitions, you can import documentation parts from an external OpenAPI file into an API in API Gateway. You specify the to-be-imported documentation parts within the x-amazon-apigateway-documentation object extension in a valid OpenAPI definition file. Importing documentation does not alter the existing API entity definitions. You have an option to merge the newly specified documentation parts into existing documentation parts in API Gateway or to overwrite the existing documentation parts. In the MERGE mode, a new documentation part defined in the OpenAPI file is added to the DocumentationParts collection of the API. If an imported DocumentationPart already exists, an imported attribute replaces the existing one if the two are different. Other existing documentation attributes remain unaffected. In the OVERWRITE mode, the entire DocumentationParts collection is replaced according to the imported OpenAPI definition file. Importing documentation parts using the API Gateway REST API To import API documentation using the API Gateway REST API, call the documentationpart:import operation. The following example shows how to overwrite existing documentation parts of an API with a single GET / method, returning a 200 OK response when successful. OpenAPI 3.0 PUT /restapis/<restapi_id>/documentation/parts&mode=overwrite&failonwarnings=true Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "openapi": "3.0.0", "info": { "description": "description", "version": "1", "title": "doc" }, "paths": { "/": { "get": { "description": "Method description.", API documentation 870 Amazon API Gateway Developer Guide "responses": { "200": { "description": "200 response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Empty" } } } } } } } }, "x-amazon-apigateway-documentation": { "version": "1.0.3", "documentationParts": [ { "location": { "type": "API" }, "properties": { "description": "API description", "info": { "description": "API info description 4", "version": "API info version 3" } } }, { "location": { "type": "METHOD", "method": "GET" }, "properties": { "description": "Method description." } }, { "location": { "type": "MODEL", "name": "Empty" }, API documentation 871 Amazon API Gateway Developer Guide "properties": { "title": "Empty Schema" } }, { "location": { "type": "RESPONSE", "method": "GET", "statusCode": "200" }, "properties": { "description": "200 response" } } ] }, "servers": [ { "url": "/" } ], "components": { "schemas": { "Empty": { "type": "object", "title": "Empty Schema" } } } } OpenAPI 2.0 PUT /restapis/<restapi_id>/documentation/parts&mode=overwrite&failonwarnings=true Host: apigateway.region.amazonaws.com Content-Type: application/json X-Amz-Date: YYYYMMDDTttttttZ Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/ apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret { "swagger": "2.0", API documentation 872 Developer Guide Amazon API Gateway "info": { "description": "description", "version": "1", "title": "doc" }, "host": "", "basePath": "/", "schemes": [ "https" ], "paths": { "/": { "get": { "description": "Method description.", "produces": [ "application/json" ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Empty" } } } } } }, "definitions": { "Empty": { "type": "object", "title": "Empty Schema" } }, "x-amazon-apigateway-documentation": { "version": "1.0.3", "documentationParts": [ { "location": { "type": "API" }, "properties": { "description": "API description", "info": { API documentation 873 Amazon API Gateway Developer Guide "description": "API info description 4", "version": "API info version 3" } } }, { "location": { "type": "METHOD", "method": "GET" }, "properties": { "description": "Method description." } }, { "location": { "type": "MODEL", "name": "Empty" }, "properties": { "title": "Empty Schema" } }, { "location": { "type": "RESPONSE", "method": "GET", "statusCode": "200" }, "properties": { "description": "200 response" } } ] } } When successful, this request returns a 200 OK response containing the imported DocumentationPartId in the payload. { "ids": [ API documentation 874 Amazon API Gateway "kg3mth", "796rtf", "zhek4p", "5ukm9s" ] } Developer Guide In addition, you can also call restapi:import or restapi:put, supplying the documentation parts in the x-amazon-apigateway-documentation object as part of the input OpenAPI file of the API definition. To exclude the documentation parts from the API import, set ignore=documentation in the request query parameters. Importing documentation parts using the API Gateway console The following instructions describe how to import documentation parts. To use the console to import documentation parts of an API from an external file 1. In the main navigation pane, choose Documentation. 2. Choose Import. 3. If you have existing documentation, select to either Overwrite or Merge your new documentation. 4. Choose Choose file to load a file from a drive, or enter file contents into the file view.
|
apigateway-dg-238
|
apigateway-dg.pdf
| 238 |
input OpenAPI file of the API definition. To exclude the documentation parts from the API import, set ignore=documentation in the request query parameters. Importing documentation parts using the API Gateway console The following instructions describe how to import documentation parts. To use the console to import documentation parts of an API from an external file 1. In the main navigation pane, choose Documentation. 2. Choose Import. 3. If you have existing documentation, select to either Overwrite or Merge your new documentation. 4. Choose Choose file to load a file from a drive, or enter file contents into the file view. For an example, see the payload of the example request in Importing documentation parts using the API Gateway REST API. 5. Choose how to handle warnings on import. Select either Fail on warnings or Ignore warnings. For more information, see the section called “Errors and warnings from importing your API into API Gateway”. 6. Choose Import. Control access to API documentation in API Gateway If you have a dedicated documentation team to write and edit your API documentation, you can configure separate access permissions for your developers (for API development) and for your writers or editors (for content development). This is especially appropriate when a third-party vendor is involved in creating the documentation for you. API documentation 875 Amazon API Gateway Developer Guide To grant your documentation team the access to create, update, and publish your API documentation, you can assign the documentation team an IAM role with the following IAM policy, where account_id is the AWS account ID of your documentation team. { "Version": "2012-10-17", "Statement": [ { "Sid": "StmtDocPartsAddEditViewDelete", "Effect": "Allow", "Action": [ "apigateway:GET", "apigateway:PUT", "apigateway:POST", "apigateway:PATCH", "apigateway:DELETE" ], "Resource": [ "arn:aws:apigateway::account_id:/restapis/*/documentation/*" ] } ] } For information on setting permissions to access API Gateway resources, see the section called “How Amazon API Gateway works with IAM”. Generate SDKs for REST APIs in API Gateway To call your REST API in a platform- or language-specific way, you must generate the platform- or language-specific SDK of the API. You generate your SDK after you create, test, and deploy your API to a stage. Currently, API Gateway supports generating an SDK for an API in Java, JavaScript, Java for Android, Objective-C or Swift for iOS, and Ruby. This section explains how to generate an SDK of an API Gateway API. It also demonstrates how to use the generated SDK in a Java app, a Java for Android app, Objective-C and Swift for iOS apps, and a JavaScript app. To facilitate the discussion, we use this API Gateway API, which exposes this Simple Calculator Lambda function. SDK generation 876 Amazon API Gateway Developer Guide Before proceeding, create or import the API and deploy it at least once in API Gateway. For instructions, see Deploy REST APIs in API Gateway. Topics • Simple calculator Lambda function • Simple calculator API in API Gateway • Simple calculator API OpenAPI definition • Generate the Java SDK of an API in API Gateway • Generate the Android SDK of an API in API Gateway • Generate the iOS SDK of an API in API Gateway • Generate the JavaScript SDK of a REST API in API Gateway • Generate the Ruby SDK of an API in API Gateway • Generate SDKs for an API using AWS CLI commands in API Gateway Simple calculator Lambda function As an illustration, we will use a Node.js Lambda function that performs the binary operations of addition, subtraction, multiplication and division. Topics • Simple calculator Lambda function input format • Simple calculator Lambda function output format • Simple calculator Lambda function implementation Simple calculator Lambda function input format This function takes an input of the following format: { "a": "Number", "b": "Number", "op": "string"} where op can be any of (+, -, *, /, add, sub, mul, div). Simple calculator Lambda function output format When an operation succeeds, it returns the result of the following format: SDK generation 877 Amazon API Gateway Developer Guide { "a": "Number", "b": "Number", "op": "string", "c": "Number"} where c holds the result of the calculation. Simple calculator Lambda function implementation The implementation of the Lambda function is as follows: export const handler = async function (event, context) { console.log("Received event:", JSON.stringify(event)); if ( event.a === undefined || event.b === undefined || event.op === undefined ) { return "400 Invalid Input"; } const res = {}; res.a = Number(event.a); res.b = Number(event.b); res.op = event.op; if (isNaN(event.a) || isNaN(event.b)) { return "400 Invalid Operand"; } switch (event.op) { case "+": case "add": res.c = res.a + res.b; break; case "-": case "sub": res.c = res.a - res.b; break; case "*": case "mul": res.c = res.a * res.b; break; case "/": case "div": if (res.b == 0) { return "400 Divide by Zero"; SDK generation 878
|
apigateway-dg-239
|
apigateway-dg.pdf
| 239 |
function (event, context) { console.log("Received event:", JSON.stringify(event)); if ( event.a === undefined || event.b === undefined || event.op === undefined ) { return "400 Invalid Input"; } const res = {}; res.a = Number(event.a); res.b = Number(event.b); res.op = event.op; if (isNaN(event.a) || isNaN(event.b)) { return "400 Invalid Operand"; } switch (event.op) { case "+": case "add": res.c = res.a + res.b; break; case "-": case "sub": res.c = res.a - res.b; break; case "*": case "mul": res.c = res.a * res.b; break; case "/": case "div": if (res.b == 0) { return "400 Divide by Zero"; SDK generation 878 Developer Guide Amazon API Gateway } else { res.c = res.a / res.b; } break; default: return "400 Invalid Operator"; } return res; }; Simple calculator API in API Gateway Our simple calculator API exposes three methods (GET, POST, GET) to invoke the the section called “Simple calculator Lambda function”. A graphical representation of this API is shown as follows: SDK generation 879 Amazon API Gateway Developer Guide SDK generation 880 Amazon API Gateway Developer Guide These three methods show different ways to supply the input for the backend Lambda function to perform the same operation: • The GET /?a=...&b=...&op=... method uses the query parameters to specify the input. • The POST / method uses a JSON payload of {"a":"Number", "b":"Number", "op":"string"} to specify the input. • The GET /{a}/{b}/{op} method uses the path parameters to specify the input. If not defined, API Gateway generates the corresponding SDK method name by combining the HTTP method and path parts. The root path part (/) is referred to as Api Root. For example, the default Java SDK method name for the API method of GET /?a=...&b=...&op=... is getABOp, the default SDK method name for POST / is postApiRoot, and the default SDK method name for GET /{a}/{b}/{op} is getABOp. Individual SDKs may customize the convention. Consult the documentation in the generated SDK source for SDK specific method names. You can, and should, override the default SDK method names by specifying the operationName property on each API method. You can do so when creating the API method or updating the API method using the API Gateway REST API. In the API Swagger definition, you can set the operationId to achieve the same result. Before showing how to call these methods using an SDK generated by API Gateway for this API, let's recall briefly how to set them up. For detailed instructions, see Develop REST APIs in API Gateway. If you're new to API Gateway, see Choose an AWS Lambda integration tutorial first. Create models for input and output To specify strongly typed input in the SDK, we create an Input model for the API. To describe the response body data type, we create an Output model and a Result model. To create models for the input, output, and result 1. In the main navigation pane, choose Models. 2. Choose Create model. 3. 4. For Name, enter input. 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. SDK generation 881 Amazon API Gateway Developer Guide 5. For Model schema, enter the following model: { "$schema" : "$schema": "http://json-schema.org/draft-04/schema#", "type":"object", "properties":{ "a":{"type":"number"}, "b":{"type":"number"}, "op":{"type":"string"} }, "title":"Input" } 6. Choose Create model. 7. Repeat the following steps to create an Output model and a Result model. For the Output model, enter the following for the Model schema: { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "c": {"type":"number"} }, "title": "Output" } For the Result model, enter the following for the Model schema. Replace the API ID abc123 with your API ID. { "$schema": "http://json-schema.org/draft-04/schema#", "type":"object", "properties":{ "input":{ "$ref":"https://apigateway.amazonaws.com/restapis/abc123/models/Input" }, "output":{ "$ref":"https://apigateway.amazonaws.com/restapis/abc123/models/Output" } }, "title":"Result" SDK generation 882 Amazon API Gateway } Set up GET / method query parameters Developer Guide For the GET /?a=..&b=..&op=.. method, the query parameters are declared in Method Request: To set up GET / URL query string parameters 1. In the Method request section for the GET method on the root (/) resource, choose Edit. 2. Choose URL query string parameters and do the following: a. b. c. Choose Add query string. For Name, enter a. Keep Required and Caching turned off. d. Keep Caching turned off. Repeat the same steps and create a query string named b and a query string named op. 3. Choose Save. Set up data model for the payload as input to the backend For the POST / method, we create the Input model and add it to the method request to define the shape of input data. To set up the data model for the payload as input to the backend 1. In the Method request section, for the POST method on the root (/) resource choose
|
apigateway-dg-240
|
apigateway-dg.pdf
| 240 |
Name, enter a. Keep Required and Caching turned off. d. Keep Caching turned off. Repeat the same steps and create a query string named b and a query string named op. 3. Choose Save. Set up data model for the payload as input to the backend For the POST / method, we create the Input model and add it to the method request to define the shape of input data. To set up the data model for the payload as input to the backend 1. In the Method request section, for the POST method on the root (/) resource choose Edit. 2. Choose Request body. 3. Choose Add model. 4. 5. For Content type, enter application/json. For Model, select Input. 6. Choose Save. SDK generation 883 Amazon API Gateway Developer Guide With this model, your API customers can call the SDK to specify the input by instantiating an Input object. Without this model, your customers would be required to create dictionary object to represent the JSON input to the Lambda function. Set up data model for the result output from the backend For all three methods, we create the Result model and add it to the method's Method Response to define the shape of output returned by the Lambda function. To set up the data model for the result output from the backend 1. Select the /{a}/{b}/{op} resource, and then choose the GET method. 2. On the Method response tab, under Response 200, choose Edit. 3. Under Response body, choose Add model. 4. 5. For Content type, enter application/json. For Model, select Result. 6. Choose Save. With this model, your API customers can parse a successful output by reading properties of a Result object. Without this model, customers would be required to create dictionary object to represent the JSON output. Simple calculator API OpenAPI definition The following is the OpenAPI definition of the simple calculator API. You can import it into your account. However, you need to reset the resource-based permissions on the Lambda function after the import. To do so, re-select the Lambda function that you created in your account from the Integration Request in the API Gateway console. This will cause the API Gateway console to reset the required permissions. Alternatively, you can use AWS Command Line Interface for Lambda command of add-permission. OpenAPI 2.0 { "swagger": "2.0", "info": { "version": "2016-09-29T20:27:30Z", "title": "SimpleCalc" }, SDK generation 884 Amazon API Gateway Developer Guide "host": "t6dve4zn25.execute-api.us-west-2.amazonaws.com", "basePath": "/demo", "schemes": [ "https" ], "paths": { "/": { "get": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "op", "in": "query", "required": false, "type": "string" }, { "name": "a", "in": "query", "required": false, "type": "string" }, { "name": "b", "in": "query", "required": false, "type": "string" } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Result" } } }, "x-amazon-apigateway-integration": { "requestTemplates": { SDK generation 885 Amazon API Gateway Developer Guide "application/json": "#set($inputRoot = $input.path('$'))\n{\n \"a\" : $input.params('a'),\n \"b\" : $input.params('b'),\n \"op\" : \"$input.params('op')\"\n}" }, "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", "passthroughBehavior": "when_no_templates", "httpMethod": "POST", "responses": { "default": { "statusCode": "200", "responseTemplates": { "application/json": "#set($inputRoot = $input.path('$'))\n{\n \"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" : \"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}" } } }, "type": "aws" } }, "post": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "in": "body", "name": "Input", "required": true, "schema": { "$ref": "#/definitions/Input" } } ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Result" } SDK generation 886 Amazon API Gateway } Developer Guide }, "x-amazon-apigateway-integration": { "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", "passthroughBehavior": "when_no_match", "httpMethod": "POST", "responses": { "default": { "statusCode": "200", "responseTemplates": { "application/json": "#set($inputRoot = $input.path('$'))\n{\n \"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" : \"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}" } } }, "type": "aws" } } }, "/{a}": { "x-amazon-apigateway-any-method": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "a", "in": "path", "required": true, "type": "string" } ], "responses": { "404": { "description": "404 response" } }, "x-amazon-apigateway-integration": { "requestTemplates": { SDK generation 887 Amazon API Gateway Developer Guide "application/json": "{\"statusCode\": 200}" }, "passthroughBehavior": "when_no_match", "responses": { "default": { "statusCode": "404", "responseTemplates": { "application/json": "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }" } } }, "type": "mock" } } }, "/{a}/{b}": { "x-amazon-apigateway-any-method": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "a", "in": "path", "required": true, "type": "string" }, { "name": "b", "in": "path", "required": true, "type": "string" } ], "responses": { "404": { "description": "404 response" } }, "x-amazon-apigateway-integration": { SDK generation 888 Amazon API Gateway Developer Guide "requestTemplates": { "application/json": "{\"statusCode\": 200}" }, "passthroughBehavior": "when_no_match", "responses": { "default": { "statusCode": "404", "responseTemplates": { "application/json": "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }" } } },
|
apigateway-dg-241
|
apigateway-dg.pdf
| 241 |
"404", "responseTemplates": { "application/json": "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }" } } }, "type": "mock" } } }, "/{a}/{b}": { "x-amazon-apigateway-any-method": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "a", "in": "path", "required": true, "type": "string" }, { "name": "b", "in": "path", "required": true, "type": "string" } ], "responses": { "404": { "description": "404 response" } }, "x-amazon-apigateway-integration": { SDK generation 888 Amazon API Gateway Developer Guide "requestTemplates": { "application/json": "{\"statusCode\": 200}" }, "passthroughBehavior": "when_no_match", "responses": { "default": { "statusCode": "404", "responseTemplates": { "application/json": "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }" } } }, "type": "mock" } } }, "/{a}/{b}/{op}": { "get": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "parameters": [ { "name": "a", "in": "path", "required": true, "type": "string" }, { "name": "b", "in": "path", "required": true, "type": "string" }, { "name": "op", "in": "path", "required": true, "type": "string" } SDK generation 889 Amazon API Gateway Developer Guide ], "responses": { "200": { "description": "200 response", "schema": { "$ref": "#/definitions/Result" } } }, "x-amazon-apigateway-integration": { "requestTemplates": { "application/json": "#set($inputRoot = $input.path('$'))\n{\n \"a\" : $input.params('a'),\n \"b\" : $input.params('b'),\n \"op\" : \"$input.params('op')\"\n}" }, "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", "passthroughBehavior": "when_no_templates", "httpMethod": "POST", "responses": { "default": { "statusCode": "200", "responseTemplates": { "application/json": "#set($inputRoot = $input.path('$'))\n{\n \"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" : \"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}" } } }, "type": "aws" } } } }, "definitions": { "Input": { "type": "object", "properties": { "a": { "type": "number" }, "b": { "type": "number" }, SDK generation 890 Amazon API Gateway Developer Guide "op": { "type": "string" } }, "title": "Input" }, "Output": { "type": "object", "properties": { "c": { "type": "number" } }, "title": "Output" }, "Result": { "type": "object", "properties": { "input": { "$ref": "#/definitions/Input" }, "output": { "$ref": "#/definitions/Output" } }, "title": "Result" } } } OpenAPI 3.0 { "openapi" : "3.0.1", "info" : { "title" : "SimpleCalc", "version" : "2016-09-29T20:27:30Z" }, "servers" : [ { "url" : "https://t6dve4zn25.execute-api.us-west-2.amazonaws.com/{basePath}", "variables" : { "basePath" : { "default" : "demo" SDK generation 891 Developer Guide Amazon API Gateway } } } ], "paths" : { "/{a}/{b}" : { "x-amazon-apigateway-any-method" : { "parameters" : [ { "name" : "a", "in" : "path", "required" : true, "schema" : { "type" : "string" } }, { "name" : "b", "in" : "path", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "404" : { "description" : "404 response", "content" : { } } }, "x-amazon-apigateway-integration" : { "type" : "mock", "responses" : { "default" : { "statusCode" : "404", "responseTemplates" : { "application/json" : "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }" } } }, "requestTemplates" : { "application/json" : "{\"statusCode\": 200}" }, "passthroughBehavior" : "when_no_match" } } SDK generation 892 Amazon API Gateway }, Developer Guide "/{a}/{b}/{op}" : { "get" : { "parameters" : [ { "name" : "a", "in" : "path", "required" : true, "schema" : { "type" : "string" } }, { "name" : "b", "in" : "path", "required" : true, "schema" : { "type" : "string" } }, { "name" : "op", "in" : "path", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response", "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/Result" } } } } }, "x-amazon-apigateway-integration" : { "type" : "aws", "httpMethod" : "POST", "uri" : "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:111122223333:function:Calc/invocations", "responses" : { "default" : { SDK generation 893 Amazon API Gateway Developer Guide "statusCode" : "200", "responseTemplates" : { "application/json" : "#set($inputRoot = $input.path('$'))\n{\n \"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" : \"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}" } } }, "requestTemplates" : { "application/json" : "#set($inputRoot = $input.path('$'))\n{\n \"a\" : $input.params('a'),\n \"b\" : $input.params('b'),\n \"op\" : \"$input.params('op')\"\n}" }, "passthroughBehavior" : "when_no_templates" } } }, "/" : { "get" : { "parameters" : [ { "name" : "op", "in" : "query", "schema" : { "type" : "string" } }, { "name" : "a", "in" : "query", "schema" : { "type" : "string" } }, { "name" : "b", "in" : "query", "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response", "content" : { "application/json" : { "schema" : { SDK generation 894 Amazon API Gateway Developer Guide "$ref" : "#/components/schemas/Result" } } } } }, "x-amazon-apigateway-integration" : { "type" : "aws", "httpMethod" : "POST", "uri" : "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:111122223333:function:Calc/invocations", "responses" : { "default" : { "statusCode" : "200", "responseTemplates" : { "application/json" : "#set($inputRoot = $input.path('$'))\n{\n \"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" : \"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}" } } }, "requestTemplates" : { "application/json" : "#set($inputRoot = $input.path('$'))\n{\n \"a\" :
|
apigateway-dg-242
|
apigateway-dg.pdf
| 242 |
} ], "responses" : { "200" : { "description" : "200 response", "content" : { "application/json" : { "schema" : { SDK generation 894 Amazon API Gateway Developer Guide "$ref" : "#/components/schemas/Result" } } } } }, "x-amazon-apigateway-integration" : { "type" : "aws", "httpMethod" : "POST", "uri" : "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:111122223333:function:Calc/invocations", "responses" : { "default" : { "statusCode" : "200", "responseTemplates" : { "application/json" : "#set($inputRoot = $input.path('$'))\n{\n \"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" : \"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}" } } }, "requestTemplates" : { "application/json" : "#set($inputRoot = $input.path('$'))\n{\n \"a\" : $input.params('a'),\n \"b\" : $input.params('b'),\n \"op\" : \"$input.params('op')\"\n}" }, "passthroughBehavior" : "when_no_templates" } }, "post" : { "requestBody" : { "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/Input" } } }, "required" : true }, "responses" : { "200" : { "description" : "200 response", "content" : { SDK generation 895 Amazon API Gateway Developer Guide "application/json" : { "schema" : { "$ref" : "#/components/schemas/Result" } } } } }, "x-amazon-apigateway-integration" : { "type" : "aws", "httpMethod" : "POST", "uri" : "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/ arn:aws:lambda:us-west-2:111122223333:function:Calc/invocations", "responses" : { "default" : { "statusCode" : "200", "responseTemplates" : { "application/json" : "#set($inputRoot = $input.path('$'))\n{\n \"input\" : {\n \"a\" : $inputRoot.a,\n \"b\" : $inputRoot.b,\n \"op\" : \"$inputRoot.op\"\n },\n \"output\" : {\n \"c\" : $inputRoot.c\n }\n}" } } }, "passthroughBehavior" : "when_no_match" } } }, "/{a}" : { "x-amazon-apigateway-any-method" : { "parameters" : [ { "name" : "a", "in" : "path", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "404" : { "description" : "404 response", "content" : { } } }, "x-amazon-apigateway-integration" : { SDK generation 896 Amazon API Gateway Developer Guide "type" : "mock", "responses" : { "default" : { "statusCode" : "404", "responseTemplates" : { "application/json" : "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }" } } }, "requestTemplates" : { "application/json" : "{\"statusCode\": 200}" }, "passthroughBehavior" : "when_no_match" } } } }, "components" : { "schemas" : { "Input" : { "title" : "Input", "type" : "object", "properties" : { "a" : { "type" : "number" }, "b" : { "type" : "number" }, "op" : { "type" : "string" } } }, "Output" : { "title" : "Output", "type" : "object", "properties" : { "c" : { "type" : "number" } } }, SDK generation 897 Amazon API Gateway Developer Guide "Result" : { "title" : "Result", "type" : "object", "properties" : { "input" : { "$ref" : "#/components/schemas/Input" }, "output" : { "$ref" : "#/components/schemas/Output" } } } } } } Generate the Java SDK of an API in API Gateway The following procedure shows how to generate the Java SDK of an API in API Gateway. To generate the Java SDK of an API in API Gateway 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose Stages. 4. In the Stages pane, select the name of the stage. 5. Open the Stage actions menu, and then choose Generate SDK. 6. For Platform, choose the Java platform and do the following: a. b. For Service Name, specify the name of your SDK. For example, SimpleCalcSdk. This becomes the name of your SDK client class. The name corresponds to the <name> tag under <project> in the pom.xml file, which is in the SDK's project folder. Do not include hyphens. For Java Package Name, specify a package name for your SDK. For example, examples.aws.apig.simpleCalc.sdk. This package name is used as the namespace of your SDK library. Do not include hyphens. c. For Java Build System, enter maven or gradle to specify the build system. SDK generation 898 Amazon API Gateway Developer Guide d. e. f. For Java Group Id, enter a group identifier for your SDK project. For example, enter my-apig-api-examples. This identifier corresponds to the <groupId> tag under <project> in the pom.xml file, which is in the SDK's project folder. For Java Artifact Id, enter an artifact identifier for your SDK project. For example, enter simple-calc-sdk. This identifier corresponds to the <artifactId> tag under <project> in the pom.xml file, which is in the SDK's project folder. For Java Artifact Version, enter a version identifier string. For example, 1.0.0. This version identifier corresponds to the <version> tag under <project> in the pom.xml file, which is in the SDK's project folder. g. For Source Code License Text, enter the license text of your source code, if any. 7. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by API Gateway. Follow the instructions in Use a Java SDK generated by API Gateway for a REST API to use the generated SDK. Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included.
|
apigateway-dg-243
|
apigateway-dg.pdf
| 243 |
string. For example, 1.0.0. This version identifier corresponds to the <version> tag under <project> in the pom.xml file, which is in the SDK's project folder. g. For Source Code License Text, enter the license text of your source code, if any. 7. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by API Gateway. Follow the instructions in Use a Java SDK generated by API Gateway for a REST API to use the generated SDK. Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. Generate the Android SDK of an API in API Gateway The following procedure shows how to generate the Android SDK of an API in API Gateway. To generate the Android SDK of an API in API Gateway 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose Stages. 4. In the Stages pane, select the name of the stage. 5. Open the Stage actions menu, and then choose Generate SDK. 6. For Platform, choose the Android platform and do the following: a. b. For Group ID, enter the unique identifier for the corresponding project. This is used in the pom.xml file (for example, com.mycompany). For Invoker package, enter the namespace for the generated client classes (for example, com.mycompany.clientsdk). SDK generation 899 Amazon API Gateway Developer Guide c. d. For Artifact ID, enter the name of the compiled .jar file without the version. This is used in the pom.xml file (for example, aws-apigateway-api-sdk). For Artifact version, enter the artifact version number for the generated client. This is used in the pom.xml file and should follow a major.minor.patch pattern (for example, 1.0.0). 7. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by API Gateway. Follow the instructions in Use an Android SDK generated by API Gateway for a REST API to use the generated SDK. Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. Generate the iOS SDK of an API in API Gateway The following procedure shows how to generate the iOS SDK of an API in API Gateway. To generate the iOS SDK of an API in API Gateway 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose Stages. 4. In the Stages pane, select the name of the stage. 5. Open the Stage actions menu, and then choose Generate SDK. 6. For Platform, choose the iOS (Objective-C) or iOS (Swift) platform and do the following: • Type a unique prefix in the Prefix box. The effect of prefix is as follows: if you assign, for example, SIMPLE_CALC as the prefix for the SDK of the SimpleCalc API with input, output, and result models, the generated SDK will contain the SIMPLE_CALCSimpleCalcClient class that encapsulates the API, including the method requests/responses. In addition, the generated SDK will contain the SIMPLE_CALCinput, SIMPLE_CALCoutput, and SIMPLE_CALCresult classes to represent the input, output, and results, respectively, to represent the request input and response output. For more information, see Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift. SDK generation 900 Amazon API Gateway Developer Guide 7. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by API Gateway. Follow the instructions in Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift to use the generated SDK. Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. Generate the JavaScript SDK of a REST API in API Gateway The following procedure shows how to generate the JaveScript SDK of an API in API Gateway. To generate the JavaScript SDK of an API in API Gateway 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. 2. Choose a REST API. 3. Choose Stages. 4. In the Stages pane, select the name of the stage. 5. Open the Stage actions menu, and then choose Generate SDK. 6. For Platform, choose the JavaScript platform. 7. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by API Gateway. Follow the instructions in Use a JavaScript SDK generated by API Gateway for a REST API to use the generated SDK. Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. Generate the Ruby SDK of an API in API Gateway The following procedure shows how to generate the Ruby SDK of an API in API Gateway. To generate the Ruby SDK of an API in API Gateway 1. Sign in to the API Gateway console at
|
apigateway-dg-244
|
apigateway-dg.pdf
| 244 |
then follow the on-screen directions to download the SDK generated by API Gateway. Follow the instructions in Use a JavaScript SDK generated by API Gateway for a REST API to use the generated SDK. Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. Generate the Ruby SDK of an API in API Gateway The following procedure shows how to generate the Ruby SDK of an API in API Gateway. To generate the Ruby SDK of an API in API Gateway 1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway. SDK generation 901 Amazon API Gateway 2. Choose a REST API. 3. Choose Stages. 4. In the Stages pane, select the name of the stage. 5. Open the Stage actions menu, and then choose Generate SDK. 6. For Platform, choose the Ruby platform and do the following: Developer Guide a. For Service Name, specify the name of your SDK. For example, SimpleCalc. This is used to generate the Ruby Gem namespace of your API. The name must be all letters, (a-zA- Z), without any other special characters or numbers. b. For Ruby Gem Name, specify the name of the Ruby Gem to contain the generated SDK source code for your API. By default, it is the lower-cased service name plus the -sdk suffix—for example, simplecalc-sdk. c. For Ruby Gem Version, specify a version number for the generated Ruby Gem. By default, it is set to 1.0.0. 7. Choose Generate SDK, and then follow the on-screen directions to download the SDK generated by API Gateway. Follow the instructions in Use a Ruby SDK generated by API Gateway for a REST API to use the generated SDK. Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. Generate SDKs for an API using AWS CLI commands in API Gateway You can use AWS CLI to generate and download an SDK of an API for a supported platform by calling the get-sdk command. We demonstrate this for some of the supported platforms in the following. Topics • Generate and download the Java for Android SDK using the AWS CLI • Generate and download the JavaScript SDK using the AWS CLI • Generate and download the Ruby SDK using the AWS CLI SDK generation 902 Amazon API Gateway Developer Guide Generate and download the Java for Android SDK using the AWS CLI To generate and download a Java for Android SDK generated by API Gateway of an API (udpuvvzbkc) at a given stage (test), call the command as follows: aws apigateway get-sdk \ --rest-api-id udpuvvzbkc \ --stage-name test \ --sdk-type android \ --parameters groupId='com.mycompany',\ invokerPackage='com.mycompany.myApiSdk',\ artifactId='myApiSdk',\ artifactVersion='0.0.1' \ ~/apps/myApi/myApi-android-sdk.zip The last input of ~/apps/myApi/myApi-android-sdk.zip is the path to the downloaded SDK file named myApi-android-sdk.zip. Generate and download the JavaScript SDK using the AWS CLI To generate and download a JavaScript SDK generated by API Gateway of an API (udpuvvzbkc) at a given stage (test), call the command as follows: aws apigateway get-sdk \ --rest-api-id udpuvvzbkc \ --stage-name test \ --sdk-type javascript \ ~/apps/myApi/myApi-js-sdk.zip The last input of ~/apps/myApi/myApi-js-sdk.zip is the path to the downloaded SDK file named myApi-js-sdk.zip. Generate and download the Ruby SDK using the AWS CLI To generate and download a Ruby SDK of an API (udpuvvzbkc) at a given stage (test), call the command as follows: aws apigateway get-sdk \ --rest-api-id udpuvvzbkc \ --stage-name test \ --sdk-type ruby \ SDK generation 903 Amazon API Gateway Developer Guide --parameters service.name=myApiRubySdk,ruby.gem-name=myApi,ruby.gem- version=0.01 \ ~/apps/myApi/myApi-ruby-sdk.zip The last input of ~/apps/myApi/myApi-ruby-sdk.zip is the path to the downloaded SDK file named myApi-ruby-sdk.zip. Next, we show how to use the generated SDK to call the underlying API. For more information, see Invoke REST APIs in API Gateway. Sell your API Gateway APIs through AWS Marketplace After you build, test, and deploy your APIs, you can package them in an API Gateway usage plan and sell the plan as a Software as a Service (SaaS) product through AWS Marketplace. API buyers subscribing to your product offering are billed by AWS Marketplace based on the number of requests made to the usage plan. To sell your APIs on AWS Marketplace, you must set up the sales channel to integrate AWS Marketplace with API Gateway. Generally speaking, this involves listing your product on AWS Marketplace, setting up an IAM role with appropriate policies to allow API Gateway to send usage metrics to AWS Marketplace, associating an AWS Marketplace product with an API Gateway usage plan, and associating an AWS Marketplace buyer with an API Gateway API key. Details are discussed in the following sections. For more information about selling your API as a SaaS product on AWS Marketplace, see the AWS Marketplace User Guide. Topics • Initialize AWS Marketplace
|
apigateway-dg-245
|
apigateway-dg.pdf
| 245 |
AWS Marketplace, you must set up the sales channel to integrate AWS Marketplace with API Gateway. Generally speaking, this involves listing your product on AWS Marketplace, setting up an IAM role with appropriate policies to allow API Gateway to send usage metrics to AWS Marketplace, associating an AWS Marketplace product with an API Gateway usage plan, and associating an AWS Marketplace buyer with an API Gateway API key. Details are discussed in the following sections. For more information about selling your API as a SaaS product on AWS Marketplace, see the AWS Marketplace User Guide. Topics • Initialize AWS Marketplace integration with API Gateway • Handle customer subscription to usage plans Initialize AWS Marketplace integration with API Gateway The following tasks are for one-time initialization of AWS Marketplace integration with API Gateway, which enables you to sell your APIs as a SaaS product. Sell your APIs as SaaS 904 Amazon API Gateway Developer Guide List a product on AWS Marketplace To list your usage plan as a SaaS product, submit a product load form through AWS Marketplace. The product must contain a dimension named apigateway of the requests type. This dimension defines the price-per-request and is used by API Gateway to meter requests to your APIs. Create the metering role Create an IAM role named ApiGatewayMarketplaceMeteringRole with the following execution policy and trust policy. This role allows API Gateway to send usage metrics to AWS Marketplace on your behalf. Execution policy of the metering role { "Version": "2012-10-17", "Statement": [ { "Action": [ "aws-marketplace:BatchMeterUsage", "aws-marketplace:ResolveCustomer" ], "Resource": "*", "Effect": "Allow" } ] } Trusted relationship policy of the metering role { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "apigateway.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } Sell your APIs as SaaS 905 Amazon API Gateway Developer Guide Associate usage plan with AWS Marketplace product When you list a product on AWS Marketplace, you receive an AWS Marketplace product code. To integrate API Gateway with AWS Marketplace, associate your usage plan with the AWS Marketplace product code. You enable the association by setting the API Gateway UsagePlan's productCode field to your AWS Marketplace product code, using the API Gateway console, the API Gateway REST API, the AWS CLI for API Gateway, or AWS SDK for API Gateway. The following code example uses the API Gateway REST API: PATCH /usageplans/USAGE_PLAN_ID Host: apigateway.region.amazonaws.com Authorization: ... { "patchOperations" : [{ "path" : "/productCode", "value" : "MARKETPLACE_PRODUCT_CODE", "op" : "replace" }] } Handle customer subscription to usage plans The following tasks are handled by your developer portal application. When a customer subscribes to your product through AWS Marketplace, AWS Marketplace forwards a POST request to the SaaS subscriptions URL that you registered when listing your product on AWS Marketplace. The POST request comes with an x-amzn-marketplace-token parameter containing buyer information. Follow the instructions in SaaS customer onboarding to handle this redirect in your developer portal application. Responding to a customer's subscribing request, AWS Marketplace sends a subscribe-success notification to an Amazon SNS topic that you can subscribe to. (See SaaS customer onboarding). To accept the customer subscription request, you handle the subscribe-success notification by creating or retrieving an API Gateway API key for the customer, associating the customer's AWS Marketplace-provisioned customerId with the API keys, and then adding the API key to your usage plan. Sell your APIs as SaaS 906 Amazon API Gateway Developer Guide When the customer's subscription request completes, the developer portal application should present the customer with the associated API key and inform the customer that the API key must be included in the x-api-key header in requests to the APIs. When a customer cancels a subscription to a usage plan, AWS Marketplace sends an unsubscribe-success notification to the SNS topic. To complete the process of unsubscribing the customer, you handle the unsubscribe-success notification by removing the customer's API keys from the usage plan. Authorize a customer to access a usage plan To authorize access to your usage plan for a given customer, use the API Gateway API to fetch or create an API key for the customer and add the API key to the usage plan. The following example shows how to call the API Gateway REST API to create a new API key with a specific AWS Marketplace customerId value (MARKETPLACE_CUSTOMER_ID). POST apikeys HTTP/1.1 Host: apigateway.region.amazonaws.com Authorization: ... { "name" : "my_api_key", "description" : "My API key", "enabled" : "false", "stageKeys" : [ { "restApiId" : "uycll6xg9a", "stageName" : "prod" } ], "customerId" : "MARKETPLACE_CUSTOMER_ID" } The following example shows how to get an API key with a specific AWS Marketplace customerId value (MARKETPLACE_CUSTOMER_ID). GET apikeys?customerId=MARKETPLACE_CUSTOMER_ID HTTP/1.1 Host: apigateway.region.amazonaws.com Authorization: ... To add an API key to a usage plan, create a UsagePlanKey with the API key for the relevant usage plan. The following example shows how
|
apigateway-dg-246
|
apigateway-dg.pdf
| 246 |
to create a new API key with a specific AWS Marketplace customerId value (MARKETPLACE_CUSTOMER_ID). POST apikeys HTTP/1.1 Host: apigateway.region.amazonaws.com Authorization: ... { "name" : "my_api_key", "description" : "My API key", "enabled" : "false", "stageKeys" : [ { "restApiId" : "uycll6xg9a", "stageName" : "prod" } ], "customerId" : "MARKETPLACE_CUSTOMER_ID" } The following example shows how to get an API key with a specific AWS Marketplace customerId value (MARKETPLACE_CUSTOMER_ID). GET apikeys?customerId=MARKETPLACE_CUSTOMER_ID HTTP/1.1 Host: apigateway.region.amazonaws.com Authorization: ... To add an API key to a usage plan, create a UsagePlanKey with the API key for the relevant usage plan. The following example shows how to accomplish this using the API Gateway REST API, Sell your APIs as SaaS 907 Amazon API Gateway Developer Guide where n371pt is the usage plan ID and q5ugs7qjjh is an example API keyId returned from the preceding examples. POST /usageplans/n371pt/keys HTTP/1.1 Host: apigateway.region.amazonaws.com Authorization: ... { "keyId": "q5ugs7qjjh", "keyType": "API_KEY" } Associate a customer with an API key You must update the ApiKey's customerId field to the AWS Marketplace customer ID of the customer. This associates the API key with the AWS Marketplace customer, which enables metering and billing for the buyer. The following code example calls the API Gateway REST API to do that. PATCH /apikeys/q5ugs7qjjh Host: apigateway.region.amazonaws.com Authorization: ... { "patchOperations" : [{ "path" : "/customerId", "value" : "MARKETPLACE_CUSTOMER_ID", "op" : "replace" }] } Protect your REST APIs in API Gateway API Gateway provides a number of ways to protect your API from certain threats, like malicious users or spikes in traffic. You can protect your API using strategies like generating SSL certificates, configuring a web application firewall, setting throttling targets, and only allowing access to your API from a Virtual Private Cloud (VPC). In this section you can learn how to enable these capabilities using API Gateway. Topics • How to turn on mutual TLS authentication for your REST APIs in API Gateway Protect 908 Amazon API Gateway Developer Guide • Generate and configure an SSL certificate for backend authentication in API Gateway • Use AWS WAF to protect your REST APIs in API Gateway • Throttle requests to your REST APIs for better throughput in API Gateway • Private REST APIs in API Gateway How to turn on mutual TLS authentication for your REST APIs in API Gateway Mutual TLS authentication requires two-way authentication between the client and the server. With mutual TLS, clients must present X.509 certificates to verify their identity to access your API. Mutual TLS is a common requirement for Internet of Things (IoT) and business-to-business applications. You can use mutual TLS along with other authorization and authentication operations that API Gateway supports. API Gateway forwards the certificates that clients provide to Lambda authorizers and to backend integrations. Important By default, clients can invoke your API by using the execute-api endpoint that API Gateway generates for your API. To ensure that clients can access your API only by using a custom domain name with mutual TLS, disable the default execute-api endpoint. To learn more, see the section called “Disable the default endpoint”. Topics • Prerequisites for mutual TLS • Configuring mutual TLS for a custom domain name • Invoke an API by using a custom domain name that requires mutual TLS • Updating your truststore • Disable mutual TLS • Troubleshoot mutual TLS for your REST API Mutual TLS 909 Amazon API Gateway Developer Guide Prerequisites for mutual TLS To configure mutual TLS you need: • A Regional custom domain name • At least one certificate configured in AWS Certificate Manager for your custom domain name • A truststore configured and uploaded to Amazon S3 Custom domain names To enable mutual TLS for a REST API, you must configure a custom domain name for your API. You can enable mutual TLS for a custom domain name, and then provide the custom domain name to clients. To access an API by using a custom domain name that has mutual TLS enabled, clients must present certificates that you trust in API requests. You can find more information at the section called “Custom domain names”. Using AWS Certificate Manager issued certificates You can request a publicly trusted certificate directly from ACM or import public or self-signed certificates. To setup a certificate in ACM, go to ACM. If you would like to import a certificate, continue reading in the following section. Using an imported or AWS Private Certificate Authority certificate To use a certificate imported into ACM or a certificate from AWS Private Certificate Authority with mutual TLS, API Gateway needs an ownershipVerificationCertificate issued by ACM. This ownership certificate is only used to verify that you have permissions to use the domain name. It is not used for the TLS handshake. If you don't already have a ownershipVerificationCertificate, go to https://console.aws.amazon.com/acm/ to set one up. You
|
apigateway-dg-247
|
apigateway-dg.pdf
| 247 |
self-signed certificates. To setup a certificate in ACM, go to ACM. If you would like to import a certificate, continue reading in the following section. Using an imported or AWS Private Certificate Authority certificate To use a certificate imported into ACM or a certificate from AWS Private Certificate Authority with mutual TLS, API Gateway needs an ownershipVerificationCertificate issued by ACM. This ownership certificate is only used to verify that you have permissions to use the domain name. It is not used for the TLS handshake. If you don't already have a ownershipVerificationCertificate, go to https://console.aws.amazon.com/acm/ to set one up. You will need to keep this certificate valid for the lifetime of your domain name. If a certificate expires and auto-renew fails, all updates to the domain name will be locked. You will need to update the ownershipVerificationCertificateArn with a valid ownershipVerificationCertificate before you can make any other changes. The ownershipVerificationCertificate cannot be used as a server certificate for another mutual TLS domain in API Gateway. If a certificate is directly re-imported into ACM, the issuer must stay the same. Mutual TLS 910 Amazon API Gateway Configuring your truststore Developer Guide Truststores are text files with a .pem file extension. They are a trusted list of certificates from Certificate Authorities. To use mutual TLS, create a truststore of X.509 certificates that you trust to access your API. You must include the complete chain of trust, starting from the issuing CA certificate, up to the root CA certificate, in your truststore. API Gateway accepts client certificates issued by any CA present in the chain of trust. The certificates can be from public or private certificate authorities. Certificates can have a maximum chain length of four. You can also provide self-signed certificates. The following algorithms are supported in the truststore: • SHA-256 or stronger • RSA-2048 or stronger • ECDSA-256 or ECDSA-384 API Gateway validates a number of certificate properties. You can use Lambda authorizers to perform additional checks when a client invokes an API, including checking whether a certificate has been revoked. API Gateway validates the following properties: Validation X.509 syntax Integrity Validity Name chaining / key chaining Description The certificate must meet X.509 syntax requirements. The certificate's content must not have been altered from that signed by the certificate authority from the truststore. The certificate's validity period must be current. The names and subjects of certificates must form an unbroken chain. Certificates can have a maximum chain length of four. Mutual TLS 911 Amazon API Gateway Developer Guide Upload the truststore to an Amazon S3 bucket in a single file The following is an example of what a .pem file might look like. Example certificates.pem -----BEGIN CERTIFICATE----- <Certificate contents> -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- <Certificate contents> -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- <Certificate contents> -----END CERTIFICATE----- ... The following cp AWS CLI command uploads certificates.pem to your Amazon S3 bucket: aws s3 cp certificates.pem s3://bucket-name Configuring mutual TLS for a custom domain name To configure mutual TLS for a REST API, you must use a Regional custom domain name for your API, with a TLS_1_2 security policy. For more information about choosing a security policy, see the section called “Choose a security policy”. Note Mutual TLS isn't supported for private APIs. After you've uploaded your truststore to Amazon S3, you can configure your custom domain name to use mutual TLS. The following create-domain-name creates a custom domain name with mutual TLS: aws apigateway create-domain-name --region us-east-2 \ --domain-name api.example.com \ --regional-certificate-arn arn:aws:acm:us- east-2:123456789012:certificate/123456789012-1234-1234-1234-12345678 \ --endpoint-configuration types=REGIONAL \ Mutual TLS 912 Amazon API Gateway Developer Guide --security-policy TLS_1_2 \ --mutual-tls-authentication truststoreUri=s3://bucket-name/key-name After you create the domain name, you must configure DNS records and basepath mappings for API operations. To learn more, see Set up a Regional custom domain name in API Gateway. Invoke an API by using a custom domain name that requires mutual TLS To invoke an API with mutual TLS enabled, clients must present a trusted certificate in the API request. When a client attempts to invoke your API, API Gateway looks for the client certificate's issuer in your truststore. For API Gateway to proceed with the request, the certificate's issuer and the complete chain of trust up to the root CA certificate must be in your truststore. The following example curl command sends a request to api.example.com, that includes my- cert.pem in the request. my-key.key is the private key for the certificate. curl -v --key ./my-key.key --cert ./my-cert.pem api.example.com Your API is invoked only if your truststore trusts the certificate. The following conditions will cause API Gateway to fail the TLS handshake and deny the request with a 403 status code. If your certificate: • isn't trusted • is expired • doesn't use a supported algorithm Note API Gateway doesn't verify if a certificate has been revoked. Updating your truststore To update
|
apigateway-dg-248
|
apigateway-dg.pdf
| 248 |
must be in your truststore. The following example curl command sends a request to api.example.com, that includes my- cert.pem in the request. my-key.key is the private key for the certificate. curl -v --key ./my-key.key --cert ./my-cert.pem api.example.com Your API is invoked only if your truststore trusts the certificate. The following conditions will cause API Gateway to fail the TLS handshake and deny the request with a 403 status code. If your certificate: • isn't trusted • is expired • doesn't use a supported algorithm Note API Gateway doesn't verify if a certificate has been revoked. Updating your truststore To update the certificates in your truststore, upload a new certificate bundle to Amazon S3. Then, you can update your custom domain name to use the updated certificate. Use Amazon S3 versioning to maintain multiple versions of your truststore. When you update your custom domain name to use a new truststore version, API Gateway returns warnings if certificates are invalid. Mutual TLS 913 Amazon API Gateway Developer Guide API Gateway produces certificate warnings only when you update your domain name. API Gateway doesn’t notify you if a previously uploaded certificate expires. The following update-domain-name command updates a custom domain name to use a new truststore version: aws apigateway update-domain-name \ --domain-name api.example.com \ --patch-operations op='replace',path='/mutualTlsAuthentication/ truststoreVersion',value='abcdef123' Disable mutual TLS The following update-domain-name disables mutual TLS: aws apigateway update-domain-name \ --domain-name api.example.com \ --patch-operations op='replace',path='/mutualTlsAuthentication/ truststoreUri',value='' Troubleshoot mutual TLS for your REST API The following provides troubleshooting advice for errors and issues that you might encounter when turning on mutual TLS. Troubleshooting certificate warnings When creating a custom domain name with mutual TLS, API Gateway returns warnings if certificates in the truststore are not valid. This can also occur when updating a custom domain name to use a new truststore. The warnings indicate the issue with the certificate and the subject of the certificate that produced the warning. Mutual TLS is still enabled for your API, but some clients might not be able to access your API. You'll need to decode the certificates in your truststore in order to identify which certificate produced the warning. You can use tools such as openssl to decode the certificates and identify their subjects. The following command displays the contents of a certificate, including its subject: openssl x509 -in certificate.crt -text -noout Mutual TLS 914 Amazon API Gateway Developer Guide Update or remove the certificates that produced warnings, and then upload a new truststore to Amazon S3. After uploading the new truststore, update your custom domain name to use the new truststore. Troubleshooting domain name conflicts The error "The certificate subject <certSubject> conflicts with an existing certificate from a different issuer." means multiple Certificate Authorities have issued a certificate for this domain. For each subject in the certificate, there can only be one issuer in API Gateway for mutual TLS domains. You will need to get all of your certificates for that subject through a single issuer. If the problem is with a certificate you don't have control of but you can prove ownership of the domain name, contact Support to open a ticket. Troubleshooting domain name status messages PENDING_CERTIFICATE_REIMPORT: This means you reimported a certificate to ACM and it failed validation because the new certificate has a SAN (subject alternative name) that is not covered by the ownershipVerificationCertificate or the subject or SANs in the certificate don't cover the domain name. Something might be configured incorrectly or an invalid certificate was imported. You need to reimport a valid certificate into ACM. For more information about validation see Validating domain ownership. PENDING_OWNERSHIP_VERIFICATION: This means your previously verified certificate has expired and ACM was unable to auto-renew it. You will need to renew the certificate or request a new certificate. More information about certificate renewal can be found at ACM's troubleshooting managed certificate renewal guide. Troubleshoot incorrect returned certificate When migrating a dedicated certificate from a fully qualified domain name (FQDN) to a wildcard customer domain name, API Gateway might return the certificate for the FQDN instead of the wildcard domain name. The following command displays which certificate is being returned by API Gateway: openssl s_client -connect hostname:port If the resulting certificate is for the FQDN, contact Support to open a ticket. Mutual TLS 915 Amazon API Gateway Developer Guide Generate and configure an SSL certificate for backend authentication in API Gateway You can use API Gateway to generate an SSL certificate and then use its public key in the backend to verify that HTTP requests to your backend system are from API Gateway. This allows your HTTP backend to control and accept only requests that originate from Amazon API Gateway, even if the backend is publicly accessible. Note Some backend servers might not support SSL client authentication as API Gateway does and could return an SSL certificate
|
apigateway-dg-249
|
apigateway-dg.pdf
| 249 |
to open a ticket. Mutual TLS 915 Amazon API Gateway Developer Guide Generate and configure an SSL certificate for backend authentication in API Gateway You can use API Gateway to generate an SSL certificate and then use its public key in the backend to verify that HTTP requests to your backend system are from API Gateway. This allows your HTTP backend to control and accept only requests that originate from Amazon API Gateway, even if the backend is publicly accessible. Note Some backend servers might not support SSL client authentication as API Gateway does and could return an SSL certificate error. For a list of incompatible backend servers, see the section called “Important notes”. The SSL certificates that are generated by API Gateway are self-signed, and only the public key of a certificate is visible in the API Gateway console or through the APIs. Topics • Generate a client certificate using the API Gateway console • Configure an API to use SSL certificates • Test invoke to verify the client certificate configuration • Configure a backend HTTPS server to verify the client certificate • Rotate an expiring client certificate • API Gateway-supported certificate authorities for HTTP and HTTP proxy integrations in API Gateway Generate a client certificate using the API Gateway console 1. Open the API Gateway console at https://console.aws.amazon.com/apigateway/. 2. Choose a REST or WebSocket API. 3. 4. 5. In the main navigation pane, choose Client certificates. From the Client certificates page, choose Generate certificate. (Optional) For Description, enter a description. Client certificates 916 Amazon API Gateway Developer Guide 6. Choose Generate certificate to generate the certificate. API Gateway generates a new certificate and returns the new certificate GUID, along with the PEM-encoded public key. You're now ready to configure an API to use the certificate. Configure an API to use SSL certificates These instructions assume that you already completed Generate a client certificate using the API Gateway console. 1. In the API Gateway console, create or open an REST or WebSocket API for which you want to use the client certificate. Make sure that the API has been deployed to a stage. 2. 3. 4. In the main navigation pane, choose Stages. In the Stage details section, choose Edit. For Client certificate, select a certificate. 5. Choose Save changes. If the API has been deployed previously in the API Gateway console, you'll need to redeploy it for the changes to take effect. For more information, see the section called “Create a deployment”. After a certificate is selected for the API and saved, API Gateway uses the certificate for all calls to HTTP integrations in your API. Test invoke to verify the client certificate configuration 1. Choose a REST API method. Choose the Test tab. You might need to choose the right arrow button to show the Test tab. 2. For Client certificate, select a certificate. 3. Choose Test. API Gateway presents the chosen SSL certificate for the HTTP backend to authenticate the API. Configure a backend HTTPS server to verify the client certificate These instructions assume that you already completed Generate a client certificate using the API Gateway console and downloaded a copy of the client certificate. You can download a client Client certificates 917 Amazon API Gateway Developer Guide certificate by calling clientcertificate:by-id of the API Gateway REST API or get-client- certificate of AWS CLI. Before configuring a backend HTTPS server to verify the client SSL certificate of API Gateway, you must have obtained the PEM-encoded private key and a server-side certificate that is provided by a trusted certificate authority. If the server domain name is myserver.mydomain.com, the server certificate's CNAME value must be myserver.mydomain.com or *.mydomain.com. Supported certificate authorities include Let's Encrypt or one of the section called “Supported certificate authorities for HTTP and HTTP proxy integration”. As an example, suppose that the client certificate file is apig-cert.pem and the server private key and certificate files are server-key.pem and server-cert.pem, respectively. For a Node.js server in the backend, you can configure the server similar to the following: var fs = require('fs'); var https = require('https'); var options = { key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-cert.pem'), ca: fs.readFileSync('apig-cert.pem'), requestCert: true, rejectUnauthorized: true }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(443); For a node-express app, you can use the client-certificate-auth modules to authenticate client requests with PEM-encoded certificates. For other HTTPS server, see the documentation for the server. Rotate an expiring client certificate The client certificate generated by API Gateway is valid for 365 days. You must rotate the certificate before a client certificate on an API stage expires to avoid any downtime for the API. Client certificates 918 Amazon API Gateway Developer Guide Rotate an expiring client certificate using the AWS Management Console The following procedure shows how to rotate a client certificate in the console for
|
apigateway-dg-250
|
apigateway-dg.pdf
| 250 |
res.end("hello world\n"); }).listen(443); For a node-express app, you can use the client-certificate-auth modules to authenticate client requests with PEM-encoded certificates. For other HTTPS server, see the documentation for the server. Rotate an expiring client certificate The client certificate generated by API Gateway is valid for 365 days. You must rotate the certificate before a client certificate on an API stage expires to avoid any downtime for the API. Client certificates 918 Amazon API Gateway Developer Guide Rotate an expiring client certificate using the AWS Management Console The following procedure shows how to rotate a client certificate in the console for a previously deployed API. 1. 2. In the main navigation pane, choose Client certificates. From the Client certificates pane, choose Generate certificate. 3. Open the API for which you want to use the client certificate. 4. Choose Stages under the selected API and then choose a stage. 5. 6. 7. In the Stage details section, choose Edit. For Client certificate, select the new certificate. To save the settings, choose Save changes. You need to redeploy the API for the changes to take effect. For more information, see the section called “Create a deployment”. Rotate an expiring client certificate using the AWS CLI You can check the expiration date of certificate by calling clientCertificate:by-id of the API Gateway REST API or the AWS CLI command of get-client-certificate and inspecting the returned expirationDate property. To rotate a client certificate, do the following: 1. Generate a new client certificate by calling clientcertificate:generate of the API Gateway REST API or the AWS CLI command of generate-client-certificate. In this tutorial, we assume that the new client certificate ID is ndiqef. 2. Update the backend server to include the new client certificate. Don't remove the existing client certificate yet. Some servers might require a restart to finish the update. Consult the server documentation to see if you must restart the server during the update. 3. Update the API stage to use the new client certificate by calling stage:update of the API Gateway REST API, with the new client certificate ID (ndiqef): PATCH /restapis/{restapi-id}/stages/stage1 HTTP/1.1 Content-Type: application/json Client certificates 919 Amazon API Gateway Developer Guide Host: apigateway.us-east-1.amazonaws.com X-Amz-Date: 20170603T200400Z Authorization: AWS4-HMAC-SHA256 Credential=... { "patchOperations" : [ { "op" : "replace", "path" : "/clientCertificateId", "value" : "ndiqef" } ] } You can also use the update-stage command. If you are using a WebSocket API, use the apigatewayv2 update-stage command . 4. Update the backend server to remove the old certificate. 5. Delete the old certificate from API Gateway by calling the clientcertificate:delete of the API Gateway REST API, specifying the clientCertificateId (a1b2c3) of the old certificate: DELETE /clientcertificates/a1b2c3 You can also call the delete-client-certificate command: aws apigateway delete-client-certificate --client-certificate-id a1b2c3 API Gateway-supported certificate authorities for HTTP and HTTP proxy integrations in API Gateway The following list shows the certificate authorities supported by API Gateway for HTTP, HTTP proxy, and private integrations. Alias name: accvraiz1 SHA1: 93:05:7A:88:15:C6:4F:CE:88:2F:FA:91:16:52:28:78:BC:53:64:17 SHA256: 9A:6E:C0:12:E1:A7:DA:9D:BE:34:19:4D:47:8A:D7:C0:DB:18:22:FB:07:1D:F1:29:81:49:6E:D1:04:38:41:13 Alias name: acraizfnmtrcm SHA1: EC:50:35:07:B2:15:C4:95:62:19:E2:A8:9A:5B:42:99:2C:4C:2C:20 Client certificates 920 Amazon API Gateway SHA256: Developer Guide EB:C5:57:0C:29:01:8C:4D:67:B1:AA:12:7B:AF:12:F7:03:B4:61:1E:BC:17:B7:DA:B5:57:38:94:17:9B:93:FA Alias name: actalis SHA1: F3:73:B3:87:06:5A:28:84:8A:F2:F3:4A:CE:19:2B:DD:C7:8E:9C:AC SHA256: 55:92:60:84:EC:96:3A:64:B9:6E:2A:BE:01:CE:0B:A8:6A:64:FB:FE:BC:C7:AA:B5:AF:C1:55:B3:7F:D7:60:66 Alias name: actalisauthenticationrootca SHA1: F3:73:B3:87:06:5A:28:84:8A:F2:F3:4A:CE:19:2B:DD:C7:8E:9C:AC SHA256: 55:92:60:84:EC:96:3A:64:B9:6E:2A:BE:01:CE:0B:A8:6A:64:FB:FE:BC:C7:AA:B5:AF:C1:55:B3:7F:D7:60:66 Alias name: addtrustclass1ca SHA1: CC:AB:0E:A0:4C:23:01:D6:69:7B:DD:37:9F:CD:12:EB:24:E3:94:9D SHA256: 8C:72:09:27:9A:C0:4E:27:5E:16:D0:7F:D3:B7:75:E8:01:54:B5:96:80:46:E3:1F:52:DD:25:76:63:24:E9:A7 Alias name: addtrustexternalca SHA1: 02:FA:F3:E2:91:43:54:68:60:78:57:69:4D:F5:E4:5B:68:85:18:68 SHA256: 68:7F:A4:51:38:22:78:FF:F0:C8:B1:1F:8D:43:D5:76:67:1C:6E:B2:BC:EA:B4:13:FB:83:D9:65:D0:6D:2F:F2 Alias name: addtrustqualifiedca SHA1: 4D:23:78:EC:91:95:39:B5:00:7F:75:8F:03:3B:21:1E:C5:4D:8B:CF SHA256: 80:95:21:08:05:DB:4B:BC:35:5E:44:28:D8:FD:6E:C2:CD:E3:AB:5F:B9:7A:99:42:98:8E:B8:F4:DC:D0:60:16 Alias name: affirmtrustcommercial SHA1: F9:B5:B6:32:45:5F:9C:BE:EC:57:5F:80:DC:E9:6E:2C:C7:B2:78:B7 SHA256: 03:76:AB:1D:54:C5:F9:80:3C:E4:B2:E2:01:A0:EE:7E:EF:7B:57:B6:36:E8:A9:3C:9B:8D:48:60:C9:6F:5F:A7 Alias name: affirmtrustcommercialca SHA1: F9:B5:B6:32:45:5F:9C:BE:EC:57:5F:80:DC:E9:6E:2C:C7:B2:78:B7 SHA256: 03:76:AB:1D:54:C5:F9:80:3C:E4:B2:E2:01:A0:EE:7E:EF:7B:57:B6:36:E8:A9:3C:9B:8D:48:60:C9:6F:5F:A7 Alias name: affirmtrustnetworking SHA1: 29:36:21:02:8B:20:ED:02:F5:66:C5:32:D1:D6:ED:90:9F:45:00:2F SHA256: 0A:81:EC:5A:92:97:77:F1:45:90:4A:F3:8D:5D:50:9F:66:B5:E2:C5:8F:CD:B5:31:05:8B:0E:17:F3:F0:B4:1B Alias name: affirmtrustnetworkingca SHA1: 29:36:21:02:8B:20:ED:02:F5:66:C5:32:D1:D6:ED:90:9F:45:00:2F SHA256: 0A:81:EC:5A:92:97:77:F1:45:90:4A:F3:8D:5D:50:9F:66:B5:E2:C5:8F:CD:B5:31:05:8B:0E:17:F3:F0:B4:1B Alias name: affirmtrustpremium SHA1: D8:A6:33:2C:E0:03:6F:B1:85:F6:63:4F:7D:6A:06:65:26:32:28:27 SHA256: 70:A7:3F:7F:37:6B:60:07:42:48:90:45:34:B1:14:82:D5:BF:0E:69:8E:CC:49:8D:F5:25:77:EB:F2:E9:3B:9A Alias name: affirmtrustpremiumca SHA1: D8:A6:33:2C:E0:03:6F:B1:85:F6:63:4F:7D:6A:06:65:26:32:28:27 Client certificates 921 Amazon API Gateway SHA256: Developer Guide 70:A7:3F:7F:37:6B:60:07:42:48:90:45:34:B1:14:82:D5:BF:0E:69:8E:CC:49:8D:F5:25:77:EB:F2:E9:3B:9A Alias name: affirmtrustpremiumecc SHA1: B8:23:6B:00:2F:1D:16:86:53:01:55:6C:11:A4:37:CA:EB:FF:C3:BB SHA256: BD:71:FD:F6:DA:97:E4:CF:62:D1:64:7A:DD:25:81:B0:7D:79:AD:F8:39:7E:B4:EC:BA:9C:5E:84:88:82:14:23 Alias name: affirmtrustpremiumeccca SHA1: B8:23:6B:00:2F:1D:16:86:53:01:55:6C:11:A4:37:CA:EB:FF:C3:BB SHA256: BD:71:FD:F6:DA:97:E4:CF:62:D1:64:7A:DD:25:81:B0:7D:79:AD:F8:39:7E:B4:EC:BA:9C:5E:84:88:82:14:23 Alias name: amazon-ca-g4-acm1 SHA1: F2:0D:28:B6:29:C2:2C:5E:84:05:E6:02:4D:97:FE:8F:A0:84:93:A0 SHA256: B0:11:A4:F7:29:6C:74:D8:2B:F5:62:DF:87:D7:28:C7:1F:B5:8C:F4:E6:73:F2:78:FC:DA:F3:FF:83:A6:8C:87 Alias name: amazon-ca-g4-acm2 SHA1: A7:E6:45:32:1F:7A:B7:AD:C0:70:EA:73:5F:AB:ED:C3:DA:B4:D0:C8 SHA256: D7:A8:7C:69:95:D0:E2:04:2A:32:70:A7:E2:87:FE:A7:E8:F4:C1:70:62:F7:90:C3:EB:BB:53:F2:AC:39:26:BE Alias name: amazon-ca-g4-acm3 SHA1: 7A:DB:56:57:5F:D6:EE:67:85:0A:64:BB:1C:E9:E4:B0:9A:DB:9D:07 SHA256: 6B:EB:9D:20:2E:C2:00:70:BD:D2:5E:D3:C0:C8:33:2C:B4:78:07:C5:82:94:4E:7E:23:28:22:71:A4:8E:0E:C2 Alias name: amazon-ca-g4-legacy SHA1: EA:E7:DE:F9:0A:BE:9F:0B:68:CE:B7:24:0D:80:74:03:BF:6E:B1:6E SHA256: CD:72:C4:7F:B4:AD:28:A4:67:2B:E1:86:47:D4:40:E9:3B:16:2D:95:DB:3C:2F:94:BB:81:D9:09:F7:91:24:5E Alias name: amazon-root-ca-ecc-384-1 SHA1: F9:5E:4A:AB:9C:2D:57:61:63:3D:B2:57:B4:0F:24:9E:7B:E2:23:7D SHA256: C6:BD:E5:66:C2:72:2A:0E:96:E9:C1:2C:BF:38:92:D9:55:4D:29:03:57:30:72:40:7F:4E:70:17:3B:3C:9B:63 Alias name: amazon-root-ca-rsa-2k-1 SHA1: 8A:9A:AC:27:FC:86:D4:50:23:AD:D5:63:F9:1E:AE:2C:AF:63:08:6C SHA256: 0F:8F:33:83:FB:70:02:89:49:24:E1:AA:B0:D7:FB:5A:BF:98:DF:75:8E:0F:FE:61:86:92:BC:F0:75:35:CC:80 Alias name: amazon-root-ca-rsa-4k-1 SHA1: EC:BD:09:61:F5:7A:B6:A8:76:BB:20:8F:14:05:ED:7E:70:ED:39:45 SHA256: 36:AE:AD:C2:6A:60:07:90:6B:83:A3:73:2D:D1:2B:D4:00:5E:C7:F2:76:11:99:A9:D4:DA:63:2F:59:B2:8B:CF Alias name: amazon1 SHA1: 8D:A7:F9:65:EC:5E:FC:37:91:0F:1C:6E:59:FD:C1:CC:6A:6E:DE:16 SHA256: 8E:CD:E6:88:4F:3D:87:B1:12:5B:A3:1A:C3:FC:B1:3D:70:16:DE:7F:57:CC:90:4F:E1:CB:97:C6:AE:98:19:6E Alias name: amazon2 SHA1: 5A:8C:EF:45:D7:A6:98:59:76:7A:8C:8B:44:96:B5:78:CF:47:4B:1A Client certificates 922 Amazon API Gateway SHA256: Developer Guide 1B:A5:B2:AA:8C:65:40:1A:82:96:01:18:F8:0B:EC:4F:62:30:4D:83:CE:C4:71:3A:19:C3:9C:01:1E:A4:6D:B4 Alias name: amazon3 SHA1: 0D:44:DD:8C:3C:8C:1A:1A:58:75:64:81:E9:0F:2E:2A:FF:B3:D2:6E SHA256: 18:CE:6C:FE:7B:F1:4E:60:B2:E3:47:B8:DF:E8:68:CB:31:D0:2E:BB:3A:DA:27:15:69:F5:03:43:B4:6D:B3:A4 Alias name: amazon4 SHA1: F6:10:84:07:D6:F8:BB:67:98:0C:C2:E2:44:C2:EB:AE:1C:EF:63:BE SHA256: E3:5D:28:41:9E:D0:20:25:CF:A6:90:38:CD:62:39:62:45:8D:A5:C6:95:FB:DE:A3:C2:2B:0B:FB:25:89:70:92 Alias name: amazonrootca1 SHA1: 8D:A7:F9:65:EC:5E:FC:37:91:0F:1C:6E:59:FD:C1:CC:6A:6E:DE:16 SHA256: 8E:CD:E6:88:4F:3D:87:B1:12:5B:A3:1A:C3:FC:B1:3D:70:16:DE:7F:57:CC:90:4F:E1:CB:97:C6:AE:98:19:6E Alias name: amazonrootca2 SHA1: 5A:8C:EF:45:D7:A6:98:59:76:7A:8C:8B:44:96:B5:78:CF:47:4B:1A SHA256: 1B:A5:B2:AA:8C:65:40:1A:82:96:01:18:F8:0B:EC:4F:62:30:4D:83:CE:C4:71:3A:19:C3:9C:01:1E:A4:6D:B4 Alias name: amazonrootca3 SHA1: 0D:44:DD:8C:3C:8C:1A:1A:58:75:64:81:E9:0F:2E:2A:FF:B3:D2:6E SHA256: 18:CE:6C:FE:7B:F1:4E:60:B2:E3:47:B8:DF:E8:68:CB:31:D0:2E:BB:3A:DA:27:15:69:F5:03:43:B4:6D:B3:A4 Alias name: amazonrootca4 SHA1: F6:10:84:07:D6:F8:BB:67:98:0C:C2:E2:44:C2:EB:AE:1C:EF:63:BE SHA256: E3:5D:28:41:9E:D0:20:25:CF:A6:90:38:CD:62:39:62:45:8D:A5:C6:95:FB:DE:A3:C2:2B:0B:FB:25:89:70:92 Alias name: amzninternalinfoseccag3 SHA1: B9:B1:CA:38:F7:BF:9C:D2:D4:95:E7:B6:5E:75:32:9B:A8:78:2E:F6 SHA256: 81:03:0B:C7:E2:54:DA:7B:F8:B7:45:DB:DD:41:15:89:B5:A3:81:86:FB:4B:29:77:1F:84:0A:18:D9:67:6D:68 Alias name: amzninternalrootca SHA1: A7:B7:F6:15:8A:FF:1E:C8:85:13:38:BC:93:EB:A2:AB:A4:09:EF:06 SHA256: 0E:DE:63:C1:DC:7A:8E:11:F1:AB:BC:05:4F:59:EE:49:9D:62:9A:2F:DE:9C:A7:16:32:A2:64:29:3E:8B:66:AA Alias name: aolrootca1 SHA1: 39:21:C1:15:C1:5D:0E:CA:5C:CB:5B:C4:F0:7D:21:D8:05:0B:56:6A SHA256: 77:40:73:12:C6:3A:15:3D:5B:C0:0B:4E:51:75:9C:DF:DA:C2:37:DC:2A:33:B6:79:46:E9:8E:9B:FA:68:0A:E3 Alias name: aolrootca2 SHA1: 85:B5:FF:67:9B:0C:79:96:1F:C8:6E:44:22:00:46:13:DB:17:92:84 SHA256: 7D:3B:46:5A:60:14:E5:26:C0:AF:FC:EE:21:27:D2:31:17:27:AD:81:1C:26:84:2D:00:6A:F3:73:06:CC:80:BD Alias name: atostrustedroot2011 SHA1: 2B:B1:F5:3E:55:0C:1D:C5:F1:D4:E6:B7:6A:46:4B:55:06:02:AC:21 Client certificates 923 Amazon API Gateway SHA256: Developer Guide F3:56:BE:A2:44:B7:A9:1E:B3:5D:53:CA:9A:D7:86:4A:CE:01:8E:2D:35:D5:F8:F9:6D:DF:68:A6:F4:1A:A4:74 Alias name: autoridaddecertificacionfirmaprofesionalcifa62634068 SHA1: AE:C5:FB:3F:C8:E1:BF:C4:E5:4F:03:07:5A:9A:E8:00:B7:F7:B6:FA SHA256: 04:04:80:28:BF:1F:28:64:D4:8F:9A:D4:D8:32:94:36:6A:82:88:56:55:3F:3B:14:30:3F:90:14:7F:5D:40:EF Alias name: baltimorecodesigningca SHA1: 30:46:D8:C8:88:FF:69:30:C3:4A:FC:CD:49:27:08:7C:60:56:7B:0D SHA256: A9:15:45:DB:D2:E1:9C:4C:CD:F9:09:AA:71:90:0D:18:C7:35:1C:89:B3:15:F0:F1:3D:05:C1:3A:8F:FB:46:87 Alias name: baltimorecybertrustca SHA1: D4:DE:20:D0:5E:66:FC:53:FE:1A:50:88:2C:78:DB:28:52:CA:E4:74 SHA256: 16:AF:57:A9:F6:76:B0:AB:12:60:95:AA:5E:BA:DE:F2:2A:B3:11:19:D6:44:AC:95:CD:4B:93:DB:F3:F2:6A:EB Alias name: baltimorecybertrustroot SHA1: D4:DE:20:D0:5E:66:FC:53:FE:1A:50:88:2C:78:DB:28:52:CA:E4:74 SHA256: 16:AF:57:A9:F6:76:B0:AB:12:60:95:AA:5E:BA:DE:F2:2A:B3:11:19:D6:44:AC:95:CD:4B:93:DB:F3:F2:6A:EB Alias name: buypassclass2ca SHA1: 49:0A:75:74:DE:87:0A:47:FE:58:EE:F6:C7:6B:EB:C6:0B:12:40:99 SHA256: 9A:11:40:25:19:7C:5B:B9:5D:94:E6:3D:55:CD:43:79:08:47:B6:46:B2:3C:DF:11:AD:A4:A0:0E:FF:15:FB:48 Alias name: buypassclass2rootca SHA1: 49:0A:75:74:DE:87:0A:47:FE:58:EE:F6:C7:6B:EB:C6:0B:12:40:99
|
apigateway-dg-251
|
apigateway-dg.pdf
| 251 |
5A:8C:EF:45:D7:A6:98:59:76:7A:8C:8B:44:96:B5:78:CF:47:4B:1A SHA256: 1B:A5:B2:AA:8C:65:40:1A:82:96:01:18:F8:0B:EC:4F:62:30:4D:83:CE:C4:71:3A:19:C3:9C:01:1E:A4:6D:B4 Alias name: amazonrootca3 SHA1: 0D:44:DD:8C:3C:8C:1A:1A:58:75:64:81:E9:0F:2E:2A:FF:B3:D2:6E SHA256: 18:CE:6C:FE:7B:F1:4E:60:B2:E3:47:B8:DF:E8:68:CB:31:D0:2E:BB:3A:DA:27:15:69:F5:03:43:B4:6D:B3:A4 Alias name: amazonrootca4 SHA1: F6:10:84:07:D6:F8:BB:67:98:0C:C2:E2:44:C2:EB:AE:1C:EF:63:BE SHA256: E3:5D:28:41:9E:D0:20:25:CF:A6:90:38:CD:62:39:62:45:8D:A5:C6:95:FB:DE:A3:C2:2B:0B:FB:25:89:70:92 Alias name: amzninternalinfoseccag3 SHA1: B9:B1:CA:38:F7:BF:9C:D2:D4:95:E7:B6:5E:75:32:9B:A8:78:2E:F6 SHA256: 81:03:0B:C7:E2:54:DA:7B:F8:B7:45:DB:DD:41:15:89:B5:A3:81:86:FB:4B:29:77:1F:84:0A:18:D9:67:6D:68 Alias name: amzninternalrootca SHA1: A7:B7:F6:15:8A:FF:1E:C8:85:13:38:BC:93:EB:A2:AB:A4:09:EF:06 SHA256: 0E:DE:63:C1:DC:7A:8E:11:F1:AB:BC:05:4F:59:EE:49:9D:62:9A:2F:DE:9C:A7:16:32:A2:64:29:3E:8B:66:AA Alias name: aolrootca1 SHA1: 39:21:C1:15:C1:5D:0E:CA:5C:CB:5B:C4:F0:7D:21:D8:05:0B:56:6A SHA256: 77:40:73:12:C6:3A:15:3D:5B:C0:0B:4E:51:75:9C:DF:DA:C2:37:DC:2A:33:B6:79:46:E9:8E:9B:FA:68:0A:E3 Alias name: aolrootca2 SHA1: 85:B5:FF:67:9B:0C:79:96:1F:C8:6E:44:22:00:46:13:DB:17:92:84 SHA256: 7D:3B:46:5A:60:14:E5:26:C0:AF:FC:EE:21:27:D2:31:17:27:AD:81:1C:26:84:2D:00:6A:F3:73:06:CC:80:BD Alias name: atostrustedroot2011 SHA1: 2B:B1:F5:3E:55:0C:1D:C5:F1:D4:E6:B7:6A:46:4B:55:06:02:AC:21 Client certificates 923 Amazon API Gateway SHA256: Developer Guide F3:56:BE:A2:44:B7:A9:1E:B3:5D:53:CA:9A:D7:86:4A:CE:01:8E:2D:35:D5:F8:F9:6D:DF:68:A6:F4:1A:A4:74 Alias name: autoridaddecertificacionfirmaprofesionalcifa62634068 SHA1: AE:C5:FB:3F:C8:E1:BF:C4:E5:4F:03:07:5A:9A:E8:00:B7:F7:B6:FA SHA256: 04:04:80:28:BF:1F:28:64:D4:8F:9A:D4:D8:32:94:36:6A:82:88:56:55:3F:3B:14:30:3F:90:14:7F:5D:40:EF Alias name: baltimorecodesigningca SHA1: 30:46:D8:C8:88:FF:69:30:C3:4A:FC:CD:49:27:08:7C:60:56:7B:0D SHA256: A9:15:45:DB:D2:E1:9C:4C:CD:F9:09:AA:71:90:0D:18:C7:35:1C:89:B3:15:F0:F1:3D:05:C1:3A:8F:FB:46:87 Alias name: baltimorecybertrustca SHA1: D4:DE:20:D0:5E:66:FC:53:FE:1A:50:88:2C:78:DB:28:52:CA:E4:74 SHA256: 16:AF:57:A9:F6:76:B0:AB:12:60:95:AA:5E:BA:DE:F2:2A:B3:11:19:D6:44:AC:95:CD:4B:93:DB:F3:F2:6A:EB Alias name: baltimorecybertrustroot SHA1: D4:DE:20:D0:5E:66:FC:53:FE:1A:50:88:2C:78:DB:28:52:CA:E4:74 SHA256: 16:AF:57:A9:F6:76:B0:AB:12:60:95:AA:5E:BA:DE:F2:2A:B3:11:19:D6:44:AC:95:CD:4B:93:DB:F3:F2:6A:EB Alias name: buypassclass2ca SHA1: 49:0A:75:74:DE:87:0A:47:FE:58:EE:F6:C7:6B:EB:C6:0B:12:40:99 SHA256: 9A:11:40:25:19:7C:5B:B9:5D:94:E6:3D:55:CD:43:79:08:47:B6:46:B2:3C:DF:11:AD:A4:A0:0E:FF:15:FB:48 Alias name: buypassclass2rootca SHA1: 49:0A:75:74:DE:87:0A:47:FE:58:EE:F6:C7:6B:EB:C6:0B:12:40:99 SHA256: 9A:11:40:25:19:7C:5B:B9:5D:94:E6:3D:55:CD:43:79:08:47:B6:46:B2:3C:DF:11:AD:A4:A0:0E:FF:15:FB:48 Alias name: buypassclass3ca SHA1: DA:FA:F7:FA:66:84:EC:06:8F:14:50:BD:C7:C2:81:A5:BC:A9:64:57 SHA256: ED:F7:EB:BC:A2:7A:2A:38:4D:38:7B:7D:40:10:C6:66:E2:ED:B4:84:3E:4C:29:B4:AE:1D:5B:93:32:E6:B2:4D Alias name: buypassclass3rootca SHA1: DA:FA:F7:FA:66:84:EC:06:8F:14:50:BD:C7:C2:81:A5:BC:A9:64:57 SHA256: ED:F7:EB:BC:A2:7A:2A:38:4D:38:7B:7D:40:10:C6:66:E2:ED:B4:84:3E:4C:29:B4:AE:1D:5B:93:32:E6:B2:4D Alias name: cadisigrootr2 SHA1: B5:61:EB:EA:A4:DE:E4:25:4B:69:1A:98:A5:57:47:C2:34:C7:D9:71 SHA256: E2:3D:4A:03:6D:7B:70:E9:F5:95:B1:42:20:79:D2:B9:1E:DF:BB:1F:B6:51:A0:63:3E:AA:8A:9D:C5:F8:07:03 Alias name: camerfirmachambersca SHA1: 78:6A:74:AC:76:AB:14:7F:9C:6A:30:50:BA:9E:A8:7E:FE:9A:CE:3C SHA256: 06:3E:4A:FA:C4:91:DF:D3:32:F3:08:9B:85:42:E9:46:17:D8:93:D7:FE:94:4E:10:A7:93:7E:E2:9D:96:93:C0 Alias name: camerfirmachamberscommerceca SHA1: 6E:3A:55:A4:19:0C:19:5C:93:84:3C:C0:DB:72:2E:31:30:61:F0:B1 Client certificates 924 Amazon API Gateway SHA256: Developer Guide 0C:25:8A:12:A5:67:4A:EF:25:F2:8B:A7:DC:FA:EC:EE:A3:48:E5:41:E6:F5:CC:4E:E6:3B:71:B3:61:60:6A:C3 Alias name: camerfirmachambersignca SHA1: 4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C SHA256: 13:63:35:43:93:34:A7:69:80:16:A0:D3:24:DE:72:28:4E:07:9D:7B:52:20:BB:8F:BD:74:78:16:EE:BE:BA:CA Alias name: certigna SHA1: B1:2E:13:63:45:86:A4:6F:1A:B2:60:68:37:58:2D:C4:AC:FD:94:97 SHA256: E3:B6:A2:DB:2E:D7:CE:48:84:2F:7A:C5:32:41:C7:B7:1D:54:14:4B:FB:40:C1:1F:3F:1D:0B:42:F5:EE:A1:2D Alias name: certignarootca SHA1: 2D:0D:52:14:FF:9E:AD:99:24:01:74:20:47:6E:6C:85:27:27:F5:43 SHA256: D4:8D:3D:23:EE:DB:50:A4:59:E5:51:97:60:1C:27:77:4B:9D:7B:18:C9:4D:5A:05:95:11:A1:02:50:B9:31:68 Alias name: certplusclass2primaryca SHA1: 74:20:74:41:72:9C:DD:92:EC:79:31:D8:23:10:8D:C2:81:92:E2:BB SHA256: 0F:99:3C:8A:EF:97:BA:AF:56:87:14:0E:D5:9A:D1:82:1B:B4:AF:AC:F0:AA:9A:58:B5:D5:7A:33:8A:3A:FB:CB Alias name: certplusclass3pprimaryca SHA1: 21:6B:2A:29:E6:2A:00:CE:82:01:46:D8:24:41:41:B9:25:11:B2:79 SHA256: CC:C8:94:89:37:1B:AD:11:1C:90:61:9B:EA:24:0A:2E:6D:AD:D9:9F:9F:6E:1D:4D:41:E5:8E:D6:DE:3D:02:85 Alias name: certsignrootca SHA1: FA:B7:EE:36:97:26:62:FB:2D:B0:2A:F6:BF:03:FD:E8:7C:4B:2F:9B SHA256: EA:A9:62:C4:FA:4A:6B:AF:EB:E4:15:19:6D:35:1C:CD:88:8D:4F:53:F3:FA:8A:E6:D7:C4:66:A9:4E:60:42:BB Alias name: certsignrootcag2 SHA1: 26:F9:93:B4:ED:3D:28:27:B0:B9:4B:A7:E9:15:1D:A3:8D:92:E5:32 SHA256: 65:7C:FE:2F:A7:3F:AA:38:46:25:71:F3:32:A2:36:3A:46:FC:E7:02:09:51:71:07:02:CD:FB:B6:EE:DA:33:05 Alias name: certum2 SHA1: D3:DD:48:3E:2B:BF:4C:05:E8:AF:10:F5:FA:76:26:CF:D3:DC:30:92 SHA256: B6:76:F2:ED:DA:E8:77:5C:D3:6C:B0:F6:3C:D1:D4:60:39:61:F4:9E:62:65:BA:01:3A:2F:03:07:B6:D0:B8:04 Alias name: certumca SHA1: 62:52:DC:40:F7:11:43:A2:2F:DE:9E:F7:34:8E:06:42:51:B1:81:18 SHA256: D8:E0:FE:BC:1D:B2:E3:8D:00:94:0F:37:D2:7D:41:34:4D:99:3E:73:4B:99:D5:65:6D:97:78:D4:D8:14:36:24 Alias name: certumtrustednetworkca SHA1: 07:E0:32:E0:20:B7:2C:3F:19:2F:06:28:A2:59:3A:19:A7:0F:06:9E SHA256: 5C:58:46:8D:55:F5:8E:49:7E:74:39:82:D2:B5:00:10:B6:D1:65:37:4A:CF:83:A7:D4:A3:2D:B7:68:C4:40:8E Alias name: certumtrustednetworkca2 SHA1: D3:DD:48:3E:2B:BF:4C:05:E8:AF:10:F5:FA:76:26:CF:D3:DC:30:92 Client certificates 925 Amazon API Gateway SHA256: Developer Guide B6:76:F2:ED:DA:E8:77:5C:D3:6C:B0:F6:3C:D1:D4:60:39:61:F4:9E:62:65:BA:01:3A:2F:03:07:B6:D0:B8:04 Alias name: cfcaevroot SHA1: E2:B8:29:4B:55:84:AB:6B:58:C2:90:46:6C:AC:3F:B8:39:8F:84:83 SHA256: 5C:C3:D7:8E:4E:1D:5E:45:54:7A:04:E6:87:3E:64:F9:0C:F9:53:6D:1C:CC:2E:F8:00:F3:55:C4:C5:FD:70:FD Alias name: chambersofcommerceroot2008 SHA1: 78:6A:74:AC:76:AB:14:7F:9C:6A:30:50:BA:9E:A8:7E:FE:9A:CE:3C SHA256: 06:3E:4A:FA:C4:91:DF:D3:32:F3:08:9B:85:42:E9:46:17:D8:93:D7:FE:94:4E:10:A7:93:7E:E2:9D:96:93:C0 Alias name: chunghwaepkirootca SHA1: 67:65:0D:F1:7E:8E:7E:5B:82:40:A4:F4:56:4B:CF:E2:3D:69:C6:F0 SHA256: C0:A6:F4:DC:63:A2:4B:FD:CF:54:EF:2A:6A:08:2A:0A:72:DE:35:80:3E:2F:F5:FF:52:7A:E5:D8:72:06:DF:D5 Alias name: cia-crt-g3-01-ca SHA1: 2B:EE:2C:BA:A3:1D:B5:FE:60:40:41:95:08:ED:46:82:39:4D:ED:E2 SHA256: 20:48:AD:4C:EC:90:7F:FA:4A:15:D4:CE:45:E3:C8:E4:2C:EA:78:33:DC:C7:D3:40:48:FC:60:47:27:42:99:EC Alias name: cia-crt-g3-02-ca SHA1: 96:4A:BB:A7:BD:DA:FC:97:34:C0:0A:2D:F0:05:98:F7:E6:C6:6F:09 SHA256: 93:F1:72:FB:BA:43:31:5C:06:EE:0F:9F:04:89:B8:F6:88:BC:75:15:3C:BE:B4:80:AC:A7:14:3A:F6:FC:4A:C1 Alias name: comodo-ca SHA1: AF:E5:D2:44:A8:D1:19:42:30:FF:47:9F:E2:F8:97:BB:CD:7A:8C:B4 SHA256: 52:F0:E1:C4:E5:8E:C6:29:29:1B:60:31:7F:07:46:71:B8:5D:7E:A8:0D:5B:07:27:34:63:53:4B:32:B4:02:34 Alias name: comodoaaaca SHA1: D1:EB:23:A4:6D:17:D6:8F:D9:25:64:C2:F1:F1:60:17:64:D8:E3:49 SHA256: D7:A7:A0:FB:5D:7E:27:31:D7:71:E9:48:4E:BC:DE:F7:1D:5F:0C:3E:0A:29:48:78:2B:C8:3E:E0:EA:69:9E:F4 Alias name: comodoaaaservicesroot SHA1: D1:EB:23:A4:6D:17:D6:8F:D9:25:64:C2:F1:F1:60:17:64:D8:E3:49 SHA256: D7:A7:A0:FB:5D:7E:27:31:D7:71:E9:48:4E:BC:DE:F7:1D:5F:0C:3E:0A:29:48:78:2B:C8:3E:E0:EA:69:9E:F4 Alias name: comodocertificationauthority SHA1: 66:31:BF:9E:F7:4F:9E:B6:C9:D5:A6:0C:BA:6A:BE:D1:F7:BD:EF:7B SHA256: 0C:2C:D6:3D:F7:80:6F:A3:99:ED:E8:09:11:6B:57:5B:F8:79:89:F0:65:18:F9:80:8C:86:05:03:17:8B:AF:66 Alias name: comodoecccertificationauthority SHA1: 9F:74:4E:9F:2B:4D:BA:EC:0F:31:2C:50:B6:56:3B:8E:2D:93:C3:11 SHA256: 17:93:92:7A:06:14:54:97:89:AD:CE:2F:8F:34:F7:F0:B6:6D:0F:3A:E3:A3:B8:4D:21:EC:15:DB:BA:4F:AD:C7 Alias name: comodorsacertificationauthority SHA1: AF:E5:D2:44:A8:D1:19:42:30:FF:47:9F:E2:F8:97:BB:CD:7A:8C:B4 Client certificates 926 Amazon API Gateway SHA256: Developer Guide 52:F0:E1:C4:E5:8E:C6:29:29:1B:60:31:7F:07:46:71:B8:5D:7E:A8:0D:5B:07:27:34:63:53:4B:32:B4:02:34 Alias name: cybertrustglobalroot SHA1: 5F:43:E5:B1:BF:F8:78:8C:AC:1C:C7:CA:4A:9A:C6:22:2B:CC:34:C6 SHA256: 96:0A:DF:00:63:E9:63:56:75:0C:29:65:DD:0A:08:67:DA:0B:9C:BD:6E:77:71:4A:EA:FB:23:49:AB:39:3D:A3 Alias name: deprecateditsecca SHA1: 12:12:0B:03:0E:15:14:54:F4:DD:B3:F5:DE:13:6E:83:5A:29:72:9D SHA256: 9A:59:DA:86:24:1A:FD:BA:A3:39:FA:9C:FD:21:6A:0B:06:69:4D:E3:7E:37:52:6B:BE:63:C8:BC:83:74:2E:CB Alias name: deutschetelekomrootca2 SHA1: 85:A4:08:C0:9C:19:3E:5D:51:58:7D:CD:D6:13:30:FD:8C:DE:37:BF SHA256: B6:19:1A:50:D0:C3:97:7F:7D:A9:9B:CD:AA:C8:6A:22:7D:AE:B9:67:9E:C7:0B:A3:B0:C9:D9:22:71:C1:70:D3 Alias name: digicertassuredidrootca SHA1: 05:63:B8:63:0D:62:D7:5A:BB:C8:AB:1E:4B:DF:B5:A8:99:B2:4D:43 SHA256: 3E:90:99:B5:01:5E:8F:48:6C:00:BC:EA:9D:11:1E:E7:21:FA:BA:35:5A:89:BC:F1:DF:69:56:1E:3D:C6:32:5C Alias name: digicertassuredidrootg2 SHA1: A1:4B:48:D9:43:EE:0A:0E:40:90:4F:3C:E0:A4:C0:91:93:51:5D:3F SHA256: 7D:05:EB:B6:82:33:9F:8C:94:51:EE:09:4E:EB:FE:FA:79:53:A1:14:ED:B2:F4:49:49:45:2F:AB:7D:2F:C1:85 Alias name: digicertassuredidrootg3 SHA1: F5:17:A2:4F:9A:48:C6:C9:F8:A2:00:26:9F:DC:0F:48:2C:AB:30:89 SHA256: 7E:37:CB:8B:4C:47:09:0C:AB:36:55:1B:A6:F4:5D:B8:40:68:0F:BA:16:6A:95:2D:B1:00:71:7F:43:05:3F:C2 Alias name: digicertglobalrootca SHA1: A8:98:5D:3A:65:E5:E5:C4:B2:D7:D6:6D:40:C6:DD:2F:B1:9C:54:36 SHA256: 43:48:A0:E9:44:4C:78:CB:26:5E:05:8D:5E:89:44:B4:D8:4F:96:62:BD:26:DB:25:7F:89:34:A4:43:C7:01:61 Alias name: digicertglobalrootg2 SHA1: DF:3C:24:F9:BF:D6:66:76:1B:26:80:73:FE:06:D1:CC:8D:4F:82:A4 SHA256: CB:3C:CB:B7:60:31:E5:E0:13:8F:8D:D3:9A:23:F9:DE:47:FF:C3:5E:43:C1:14:4C:EA:27:D4:6A:5A:B1:CB:5F Alias name: digicertglobalrootg3 SHA1: 7E:04:DE:89:6A:3E:66:6D:00:E6:87:D3:3F:FA:D9:3B:E8:3D:34:9E SHA256: 31:AD:66:48:F8:10:41:38:C7:38:F3:9E:A4:32:01:33:39:3E:3A:18:CC:02:29:6E:F9:7C:2A:C9:EF:67:31:D0 Alias name: digicerthighassuranceevrootca SHA1: 5F:B7:EE:06:33:E2:59:DB:AD:0C:4C:9A:E6:D3:8F:1A:61:C7:DC:25 SHA256: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF Alias name: digicerttrustedrootg4 SHA1: DD:FB:16:CD:49:31:C9:73:A2:03:7D:3F:C8:3A:4D:7D:77:5D:05:E4 Client certificates 927 Amazon API Gateway SHA256: Developer Guide 55:2F:7B:DC:F1:A7:AF:9E:6C:E6:72:01:7F:4F:12:AB:F7:72:40:C7:8E:76:1A:C2:03:D1:D9:D2:0A:C8:99:88 Alias name: dstrootcax3 SHA1: DA:C9:02:4F:54:D8:F6:DF:94:93:5F:B1:73:26:38:CA:6A:D7:7C:13 SHA256: 06:87:26:03:31:A7:24:03:D9:09:F1:05:E6:9B:CF:0D:32:E1:BD:24:93:FF:C6:D9:20:6D:11:BC:D6:77:07:39 Alias name: dtrustrootclass3ca22009 SHA1: 58:E8:AB:B0:36:15:33:FB:80:F7:9B:1B:6D:29:D3:FF:8D:5F:00:F0 SHA256: 49:E7:A4:42:AC:F0:EA:62:87:05:00:54:B5:25:64:B6:50:E4:F4:9E:42:E3:48:D6:AA:38:E0:39:E9:57:B1:C1 Alias name: dtrustrootclass3ca2ev2009 SHA1: 96:C9:1B:0B:95:B4:10:98:42:FA:D0:D8:22:79:FE:60:FA:B9:16:83 SHA256: EE:C5:49:6B:98:8C:E9:86:25:B9:34:09:2E:EC:29:08:BE:D0:B0:F3:16:C2:D4:73:0C:84:EA:F1:F3:D3:48:81 Alias name: ecacc SHA1: 28:90:3A:63:5B:52:80:FA:E6:77:4C:0B:6D:A7:D6:BA:A6:4A:F2:E8 SHA256: 88:49:7F:01:60:2F:31:54:24:6A:E2:8C:4D:5A:EF:10:F1:D8:7E:BB:76:62:6F:4A:E0:B7:F9:5B:A7:96:87:99 Alias name: emsigneccrootcac3 SHA1: B6:AF:43:C2:9B:81:53:7D:F6:EF:6B:C3:1F:1F:60:15:0C:EE:48:66 SHA256: BC:4D:80:9B:15:18:9D:78:DB:3E:1D:8C:F4:F9:72:6A:79:5D:A1:64:3C:A5:F1:35:8E:1D:DB:0E:DC:0D:7E:B3 Alias name: emsigneccrootcag3 SHA1: 30:43:FA:4F:F2:57:DC:A0:C3:80:EE:2E:58:EA:78:B2:3F:E6:BB:C1 SHA256: 86:A1:EC:BA:08:9C:4A:8D:3B:BE:27:34:C6:12:BA:34:1D:81:3E:04:3C:F9:E8:A8:62:CD:5C:57:A3:6B:BE:6B Alias name: emsignrootcac1 SHA1: E7:2E:F1:DF:FC:B2:09:28:CF:5D:D4:D5:67:37:B1:51:CB:86:4F:01 SHA256: 12:56:09:AA:30:1D:A0:A2:49:B9:7A:82:39:CB:6A:34:21:6F:44:DC:AC:9F:39:54:B1:42:92:F2:E8:C8:60:8F Alias name: emsignrootcag1 SHA1: 8A:C7:AD:8F:73:AC:4E:C1:B5:75:4D:A5:40:F4:FC:CF:7C:B5:8E:8C SHA256: 40:F6:AF:03:46:A9:9A:A1:CD:1D:55:5A:4E:9C:CE:62:C7:F9:63:46:03:EE:40:66:15:83:3D:C8:C8:D0:03:67 Alias name: entrust2048ca SHA1: 50:30:06:09:1D:97:D4:F5:AE:39:F7:CB:E7:92:7D:7D:65:2D:34:31 SHA256: 6D:C4:71:72:E0:1C:BC:B0:BF:62:58:0D:89:5F:E2:B8:AC:9A:D4:F8:73:80:1E:0C:10:B9:C8:37:D2:1E:B1:77 Alias name: entrustevca SHA1: B3:1E:B1:B7:40:E3:6C:84:02:DA:DC:37:D4:4D:F5:D4:67:49:52:F9 SHA256: 73:C1:76:43:4F:1B:C6:D5:AD:F4:5B:0E:76:E7:27:28:7C:8D:E5:76:16:C1:E6:E6:14:1A:2B:2C:BC:7D:8E:4C Alias name: entrustnetpremium2048secureserverca SHA1: 50:30:06:09:1D:97:D4:F5:AE:39:F7:CB:E7:92:7D:7D:65:2D:34:31 Client certificates 928 Amazon API Gateway SHA256: Developer Guide 6D:C4:71:72:E0:1C:BC:B0:BF:62:58:0D:89:5F:E2:B8:AC:9A:D4:F8:73:80:1E:0C:10:B9:C8:37:D2:1E:B1:77 Alias name: entrustrootcag2 SHA1: 8C:F4:27:FD:79:0C:3A:D1:66:06:8D:E8:1E:57:EF:BB:93:22:72:D4 SHA256: 43:DF:57:74:B0:3E:7F:EF:5F:E4:0D:93:1A:7B:ED:F1:BB:2E:6B:42:73:8C:4E:6D:38:41:10:3D:3A:A7:F3:39 Alias name: entrustrootcertificationauthority SHA1: B3:1E:B1:B7:40:E3:6C:84:02:DA:DC:37:D4:4D:F5:D4:67:49:52:F9 SHA256: 73:C1:76:43:4F:1B:C6:D5:AD:F4:5B:0E:76:E7:27:28:7C:8D:E5:76:16:C1:E6:E6:14:1A:2B:2C:BC:7D:8E:4C Alias name: entrustrootcertificationauthorityec1 SHA1: 20:D8:06:40:DF:9B:25:F5:12:25:3A:11:EA:F7:59:8A:EB:14:B5:47 SHA256: 02:ED:0E:B2:8C:14:DA:45:16:5C:56:67:91:70:0D:64:51:D7:FB:56:F0:B2:AB:1D:3B:8E:B0:70:E5:6E:DF:F5 Alias name: entrustrootcertificationauthorityg2 SHA1: 8C:F4:27:FD:79:0C:3A:D1:66:06:8D:E8:1E:57:EF:BB:93:22:72:D4 SHA256: 43:DF:57:74:B0:3E:7F:EF:5F:E4:0D:93:1A:7B:ED:F1:BB:2E:6B:42:73:8C:4E:6D:38:41:10:3D:3A:A7:F3:39 Alias name: entrustrootcertificationauthorityg4 SHA1: 14:88:4E:86:26:37:B0:26:AF:59:62:5C:40:77:EC:35:29:BA:96:01 SHA256: DB:35:17:D1:F6:73:2A:2D:5A:B9:7C:53:3E:C7:07:79:EE:32:70:A6:2F:B4:AC:42:38:37:24:60:E6:F0:1E:88 Alias name: epkirootcertificationauthority SHA1: 67:65:0D:F1:7E:8E:7E:5B:82:40:A4:F4:56:4B:CF:E2:3D:69:C6:F0 SHA256: C0:A6:F4:DC:63:A2:4B:FD:CF:54:EF:2A:6A:08:2A:0A:72:DE:35:80:3E:2F:F5:FF:52:7A:E5:D8:72:06:DF:D5 Alias name: equifaxsecureebusinessca1 SHA1: AE:E6:3D:70:E3:76:FB:C7:3A:EB:B0:A1:C1:D4:C4:7A:A7:40:B3:F4 SHA256: 2E:3A:2B:B5:11:25:05:83:6C:A8:96:8B:E2:CB:37:27:CE:9B:56:84:5C:6E:E9:8E:91:85:10:4A:FB:9A:F5:96 Alias name: equifaxsecureglobalebusinessca1 SHA1: 3A:74:CB:7A:47:DB:70:DE:89:1F:24:35:98:64:B8:2D:82:BD:1A:36 SHA256: 86:AB:5A:65:71:D3:32:9A:BC:D2:E4:E6:37:66:8B:A8:9C:73:1E:C2:93:B6:CB:A6:0F:71:63:40:A0:91:CE:AE Alias name: eszignorootca2017 SHA1: 89:D4:83:03:4F:9E:9A:48:80:5F:72:37:D4:A9:A6:EF:CB:7C:1F:D1 SHA256: BE:B0:0B:30:83:9B:9B:C3:2C:32:E4:44:79:05:95:06:41:F2:64:21:B1:5E:D0:89:19:8B:51:8A:E2:EA:1B:99 Alias name: etugracertificationauthority SHA1: 51:C6:E7:08:49:06:6E:F3:92:D4:5C:A0:0D:6D:A3:62:8F:C3:52:39 SHA256: B0:BF:D5:2B:B0:D7:D9:BD:92:BF:5D:4D:C1:3D:A2:55:C0:2C:54:2F:37:83:65:EA:89:39:11:F5:5E:55:F2:3C Alias name: gd-class2-root.pem SHA1: 27:96:BA:E6:3F:18:01:E2:77:26:1B:A0:D7:77:70:02:8F:20:EE:E4 Client certificates 929 Amazon API Gateway SHA256: Developer Guide C3:84:6B:F2:4B:9E:93:CA:64:27:4C:0E:C6:7C:1E:CC:5E:02:4F:FC:AC:D2:D7:40:19:35:0E:81:FE:54:6A:E4 Alias name: gd_bundle-g2.pem SHA1: 27:AC:93:69:FA:F2:52:07:BB:26:27:CE:FA:CC:BE:4E:F9:C3:19:B8 SHA256: 97:3A:41:27:6F:FD:01:E0:27:A2:AA:D4:9E:34:C3:78:46:D3:E9:76:FF:6A:62:0B:67:12:E3:38:32:04:1A:A6 Alias name: gdcatrustauthr5root SHA1: 0F:36:38:5B:81:1A:25:C3:9B:31:4E:83:CA:E9:34:66:70:CC:74:B4 SHA256: BF:FF:8F:D0:44:33:48:7D:6A:8A:A6:0C:1A:29:76:7A:9F:C2:BB:B0:5E:42:0F:71:3A:13:B9:92:89:1D:38:93 Alias name: gdroot-g2.pem SHA1: 47:BE:AB:C9:22:EA:E8:0E:78:78:34:62:A7:9F:45:C2:54:FD:E6:8B SHA256: 45:14:0B:32:47:EB:9C:C8:C5:B4:F0:D7:B5:30:91:F7:32:92:08:9E:6E:5A:63:E2:74:9D:D3:AC:A9:19:8E:DA Alias name: geotrustglobalca SHA1: DE:28:F4:A4:FF:E5:B9:2F:A3:C5:03:D1:A3:49:A7:F9:96:2A:82:12 SHA256: FF:85:6A:2D:25:1D:CD:88:D3:66:56:F4:50:12:67:98:CF:AB:AA:DE:40:79:9C:72:2D:E4:D2:B5:DB:36:A7:3A Alias name: geotrustprimaryca SHA1: 32:3C:11:8E:1B:F7:B8:B6:52:54:E2:E2:10:0D:D6:02:90:37:F0:96 SHA256: 37:D5:10:06:C5:12:EA:AB:62:64:21:F1:EC:8C:92:01:3F:C5:F8:2A:E9:8E:E5:33:EB:46:19:B8:DE:B4:D0:6C Alias name: geotrustprimarycag2 SHA1: 8D:17:84:D5:37:F3:03:7D:EC:70:FE:57:8B:51:9A:99:E6:10:D7:B0 SHA256: 5E:DB:7A:C4:3B:82:A0:6A:87:61:E8:D7:BE:49:79:EB:F2:61:1F:7D:D7:9B:F9:1C:1C:6B:56:6A:21:9E:D7:66 Alias name: geotrustprimarycag3 SHA1: 03:9E:ED:B8:0B:E7:A0:3C:69:53:89:3B:20:D2:D9:32:3A:4C:2A:FD SHA256: B4:78:B8:12:25:0D:F8:78:63:5C:2A:A7:EC:7D:15:5E:AA:62:5E:E8:29:16:E2:CD:29:43:61:88:6C:D1:FB:D4 Alias name: geotrustprimarycertificationauthority SHA1: 32:3C:11:8E:1B:F7:B8:B6:52:54:E2:E2:10:0D:D6:02:90:37:F0:96 SHA256: 37:D5:10:06:C5:12:EA:AB:62:64:21:F1:EC:8C:92:01:3F:C5:F8:2A:E9:8E:E5:33:EB:46:19:B8:DE:B4:D0:6C Alias name: geotrustprimarycertificationauthorityg2 SHA1: 8D:17:84:D5:37:F3:03:7D:EC:70:FE:57:8B:51:9A:99:E6:10:D7:B0 SHA256: 5E:DB:7A:C4:3B:82:A0:6A:87:61:E8:D7:BE:49:79:EB:F2:61:1F:7D:D7:9B:F9:1C:1C:6B:56:6A:21:9E:D7:66 Alias name: geotrustprimarycertificationauthorityg3 SHA1: 03:9E:ED:B8:0B:E7:A0:3C:69:53:89:3B:20:D2:D9:32:3A:4C:2A:FD SHA256: B4:78:B8:12:25:0D:F8:78:63:5C:2A:A7:EC:7D:15:5E:AA:62:5E:E8:29:16:E2:CD:29:43:61:88:6C:D1:FB:D4 Alias name: geotrustuniversalca SHA1: E6:21:F3:35:43:79:05:9A:4B:68:30:9D:8A:2F:74:22:15:87:EC:79 Client certificates 930 Amazon API Gateway SHA256: Developer Guide A0:45:9B:9F:63:B2:25:59:F5:FA:5D:4C:6D:B3:F9:F7:2F:F1:93:42:03:35:78:F0:73:BF:1D:1B:46:CB:B9:12 Alias name: geotrustuniversalca2 SHA1: 37:9A:19:7B:41:85:45:35:0C:A6:03:69:F3:3C:2E:AF:47:4F:20:79 SHA256: A0:23:4F:3B:C8:52:7C:A5:62:8E:EC:81:AD:5D:69:89:5D:A5:68:0D:C9:1D:1C:B8:47:7F:33:F8:78:B9:5B:0B Alias name: globalchambersignroot2008 SHA1: 4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C SHA256: 13:63:35:43:93:34:A7:69:80:16:A0:D3:24:DE:72:28:4E:07:9D:7B:52:20:BB:8F:BD:74:78:16:EE:BE:BA:CA Alias name: globalsignca SHA1: B1:BC:96:8B:D4:F4:9D:62:2A:A8:9A:81:F2:15:01:52:A4:1D:82:9C SHA256: EB:D4:10:40:E4:BB:3E:C7:42:C9:E3:81:D3:1E:F2:A4:1A:48:B6:68:5C:96:E7:CE:F3:C1:DF:6C:D4:33:1C:99 Alias name: globalsigneccrootcar4 SHA1: 69:69:56:2E:40:80:F4:24:A1:E7:19:9F:14:BA:F3:EE:58:AB:6A:BB SHA256: BE:C9:49:11:C2:95:56:76:DB:6C:0A:55:09:86:D7:6E:3B:A0:05:66:7C:44:2C:97:62:B4:FB:B7:73:DE:22:8C Alias name: globalsigneccrootcar5 SHA1: 1F:24:C6:30:CD:A4:18:EF:20:69:FF:AD:4F:DD:5F:46:3A:1B:69:AA SHA256: 17:9F:BC:14:8A:3D:D0:0F:D2:4E:A1:34:58:CC:43:BF:A7:F5:9C:81:82:D7:83:A5:13:F6:EB:EC:10:0C:89:24 Alias name: globalsignr2ca SHA1: 75:E0:AB:B6:13:85:12:27:1C:04:F8:5F:DD:DE:38:E4:B7:24:2E:FE SHA256: CA:42:DD:41:74:5F:D0:B8:1E:B9:02:36:2C:F9:D8:BF:71:9D:A1:BD:1B:1E:FC:94:6F:5B:4C:99:F4:2C:1B:9E Alias name: globalsignr3ca SHA1: D6:9B:56:11:48:F0:1C:77:C5:45:78:C1:09:26:DF:5B:85:69:76:AD SHA256: CB:B5:22:D7:B7:F1:27:AD:6A:01:13:86:5B:DF:1C:D4:10:2E:7D:07:59:AF:63:5A:7C:F4:72:0D:C9:63:C5:3B Alias name: globalsignrootca SHA1: B1:BC:96:8B:D4:F4:9D:62:2A:A8:9A:81:F2:15:01:52:A4:1D:82:9C SHA256: EB:D4:10:40:E4:BB:3E:C7:42:C9:E3:81:D3:1E:F2:A4:1A:48:B6:68:5C:96:E7:CE:F3:C1:DF:6C:D4:33:1C:99 Alias name: globalsignrootcar2 SHA1: 75:E0:AB:B6:13:85:12:27:1C:04:F8:5F:DD:DE:38:E4:B7:24:2E:FE SHA256: CA:42:DD:41:74:5F:D0:B8:1E:B9:02:36:2C:F9:D8:BF:71:9D:A1:BD:1B:1E:FC:94:6F:5B:4C:99:F4:2C:1B:9E Alias name: globalsignrootcar3 SHA1: D6:9B:56:11:48:F0:1C:77:C5:45:78:C1:09:26:DF:5B:85:69:76:AD SHA256: CB:B5:22:D7:B7:F1:27:AD:6A:01:13:86:5B:DF:1C:D4:10:2E:7D:07:59:AF:63:5A:7C:F4:72:0D:C9:63:C5:3B Alias name: globalsignrootcar6 SHA1: 80:94:64:0E:B5:A7:A1:CA:11:9C:1F:DD:D5:9F:81:02:63:A7:FB:D1 Client certificates 931 Amazon API Gateway SHA256: Developer Guide 2C:AB:EA:FE:37:D0:6C:A2:2A:BA:73:91:C0:03:3D:25:98:29:52:C4:53:64:73:49:76:3A:3A:B5:AD:6C:CF:69 Alias name: godaddyclass2ca SHA1: 27:96:BA:E6:3F:18:01:E2:77:26:1B:A0:D7:77:70:02:8F:20:EE:E4 SHA256: C3:84:6B:F2:4B:9E:93:CA:64:27:4C:0E:C6:7C:1E:CC:5E:02:4F:FC:AC:D2:D7:40:19:35:0E:81:FE:54:6A:E4 Alias name: godaddyrootcertificateauthorityg2 SHA1: 47:BE:AB:C9:22:EA:E8:0E:78:78:34:62:A7:9F:45:C2:54:FD:E6:8B SHA256: 45:14:0B:32:47:EB:9C:C8:C5:B4:F0:D7:B5:30:91:F7:32:92:08:9E:6E:5A:63:E2:74:9D:D3:AC:A9:19:8E:DA Alias name: godaddyrootg2ca SHA1: 47:BE:AB:C9:22:EA:E8:0E:78:78:34:62:A7:9F:45:C2:54:FD:E6:8B SHA256: 45:14:0B:32:47:EB:9C:C8:C5:B4:F0:D7:B5:30:91:F7:32:92:08:9E:6E:5A:63:E2:74:9D:D3:AC:A9:19:8E:DA Alias name: gtsrootr1 SHA1: E1:C9:50:E6:EF:22:F8:4C:56:45:72:8B:92:20:60:D7:D5:A7:A3:E8 SHA256: 2A:57:54:71:E3:13:40:BC:21:58:1C:BD:2C:F1:3E:15:84:63:20:3E:CE:94:BC:F9:D3:CC:19:6B:F0:9A:54:72 Alias name: gtsrootr2 SHA1: D2:73:96:2A:2A:5E:39:9F:73:3F:E1:C7:1E:64:3F:03:38:34:FC:4D SHA256: C4:5D:7B:B0:8E:6D:67:E6:2E:42:35:11:0B:56:4E:5F:78:FD:92:EF:05:8C:84:0A:EA:4E:64:55:D7:58:5C:60 Alias name: gtsrootr3 SHA1: 30:D4:24:6F:07:FF:DB:91:89:8A:0B:E9:49:66:11:EB:8C:5E:46:E5 SHA256: 15:D5:B8:77:46:19:EA:7D:54:CE:1C:A6:D0:B0:C4:03:E0:37:A9:17:F1:31:E8:A0:4E:1E:6B:7A:71:BA:BC:E5 Alias name: gtsrootr4 SHA1: 2A:1D:60:27:D9:4A:B1:0A:1C:4D:91:5C:CD:33:A0:CB:3E:2D:54:CB SHA256: 71:CC:A5:39:1F:9E:79:4B:04:80:25:30:B3:63:E1:21:DA:8A:30:43:BB:26:66:2F:EA:4D:CA:7F:C9:51:A4:BD Alias name: hellenicacademicandresearchinstitutionseccrootca2015 SHA1: 9F:F1:71:8D:92:D5:9A:F3:7D:74:97:B4:BC:6F:84:68:0B:BA:B6:66 SHA256: 44:B5:45:AA:8A:25:E6:5A:73:CA:15:DC:27:FC:36:D2:4C:1C:B9:95:3A:06:65:39:B1:15:82:DC:48:7B:48:33 Alias name: hellenicacademicandresearchinstitutionsrootca2011 SHA1:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.