Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 
      中国的 Amazon Web Services 服务入门
         (PDF)。
    教程:使用 Amazon SDK 或 Amazon CLI 创建 REST API
使用以下教程创建支持 GET /pets 和 GET
      /pets/{petId} 方法的 PetStore API。这些方法与 HTTP 端点集成。您可以按照本教程的说明,使用适用于 JavaScript 的 Amazon SDK、适用于 Python 的 SDK(Boto3)或 Amazon CLI。您可以使用以下函数或命令来设置 API:
  - JavaScript v3
- Python
- 
      
- Amazon CLI
- 
      
有关适用于 JavaScript 的 Amazon SDK v3 的更多信息,请参阅 What's the Amazon SDK for JavaScript? 有关适用于 Python 的 SDK(Boto3)的更多信息,请参阅 适用于 Python (Boto3) 的 Amazon SDK。有关 Amazon CLI 的更多信息,请参阅 What is the Amazon CLI?
    设置边缘优化的 PetStore API
    在本教程中,示例命令使用占位符值作为值 ID,例如 API ID 和资源 ID。在完成本教程时,请将这些值替换为您自己的值。
            使用 Amazon SDK 设置边缘优化的 PetStore API
- 
                    使用以下示例来创建 RestApi实体:
 
                    - JavaScript v3
- import {APIGatewayClient, CreateRestApiCommand} from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new CreateRestApiCommand({
    name: "Simple PetStore (JavaScript v3 SDK)",
    description: "Demo API created using the AWS SDK for JavaScript v3",
    version: "0.00.001",
    binaryMediaTypes: [
    '*']
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.error(Couldn't create API:\n", err)
}
})();
 - 成功的调用会在输出中返回 API ID 和 API 的根资源 ID,如下所示: - {
  id: 'abc1234',
  name: 'PetStore (JavaScript v3 SDK)',
  description: 'Demo API created using the Amazon SDK for node.js',
  createdDate: 2017-09-05T19:32:35.000Z,
  version: '0.00.001',
  rootResourceId: 'efg567'
  binaryMediaTypes: [ '*' ] 
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.create_rest_api(
        name='Simple PetStore (Python SDK)',
        description='Demo API created using the AWS SDK for Python',
        version='0.00.001',
        binaryMediaTypes=[
            '*'
        ]
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Couldn't create REST API %s.", error)
    raise
attribute=["id","name","description","createdDate","version","binaryMediaTypes","apiKeySource","endpointConfiguration","disableExecuteApiEndpoint","rootResourceId"]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用会在输出中返回 API ID 和 API 的根资源 ID,如下所示: - {'id': 'abc1234', 'name': 'Simple PetStore (Python SDK)', 'description': 'Demo API created using the AWS SDK for Python', 'createdDate': datetime.datetime(2024, 4, 3, 14, 31, 39, tzinfo=tzlocal()), 'version': '0.00.001', 'binaryMediaTypes': ['*'], 'apiKeySource': 'HEADER', 'endpointConfiguration': {'types': ['EDGE']}, 'disableExecuteApiEndpoint': False, 'rootResourceId': 'efg567'}
 
- Amazon CLI
- aws apigateway create-rest-api --name 'Simple PetStore (Amazon CLI)' --region us-west-2
 - 此命令的输出如下: - {
    "id": "abcd1234", 
    "name": "Simple PetStore (Amazon CLI)", 
    "createdDate": "2022-12-15T08:07:04-08:00",
    "apiKeySource": "HEADER",
    "endpointConfiguration": {
        "types": [
            "EDGE"
        ]
    },
    "disableExecuteApiEndpoint": false,
    "rootResourceId": "efg567"
}
 
 您创建的 API 的 API ID 为 abcd1234,根资源 ID 为efg567。您可以在 API 的设置中使用这些值。
 
- 
                  接下来,在根目录下附加子资源,您可以将 RootResourceId指定为parentId属性值。使用以下示例为 API 创建/pets资源:
 
                    - JavaScript v3
- import {APIGatewayClient,  CreateResourceCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new CreateResourceCommand({
    restApiId: 'abcd1234',
    parentId: 'efg567',
    pathPart: 'pets'
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("The '/pets' resource setup failed:\n", err)
}
})();
 - 成功的调用会在输出中返回有关您的资源的信息,如下所示: - {
    "path": "/pets", 
    "pathPart": "pets", 
    "id": "aaa111", 
    "parentId": "efg567'"
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.create_resource(
        restApiId='abcd1234',
        parentId='efg567',
        pathPart='pets'
    )
except botocore.exceptions.ClientError as error:
    logger.exception("The '/pets' resource setup failed: %s.", error)
    raise
attribute=["id","parentId", "pathPart", "path",]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用会在输出中返回有关您的资源的信息,如下所示: - {'id': '- aaa111', 'parentId': 'efg567', 'pathPart': 'pets', 'path': '/pets'}
 
- Amazon CLI
-  aws apigateway create-resource --rest-api-id abcd1234 \
  --region us-west-2 \
  --parent-id efg567 \
  --path-part pets
 此命令的输出如下: {
    "id": "aaa111", 
    "parentId": "efg567",
    "pathPart": "pets",
    "path": "/pets"
}
 
 您创建的 /pets资源的资源 ID 为aaa111。您可以在 API 的设置中使用此值。
 
- 
      接下来,在 /pets资源下附加子资源。此资源/{petId}具有{petId}的路径参数。为了让路径部分成为路径参数,请将其括在一对大括号{ }内。使用以下示例为 API 创建/pets/{petId}资源:
 
                  - JavaScript v3
- import {APIGatewayClient,  CreateResourceCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new CreateResourceCommand({
    restApiId: 'abcd1234',
    parentId: 'aaa111',
    pathPart: '{petId}'
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("The '/pets/{petId}' resource setup failed:\n", err)
}
})();
 - 成功的调用会在输出中返回有关您的资源的信息,如下所示: - {
    "path": "/pets/{petId}", 
    "pathPart": "{petId}", 
    "id": "bbb222", 
    "parentId": "aaa111'"
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.create_resource(
        restApiId='abcd1234',
        parentId='aaa111',
        pathPart='{petId}'
    )
except botocore.exceptions.ClientError as error:
    logger.exception("The '/pets/{petId}' resource setup failed: %s.", error)
    raise
attribute=["id","parentId", "pathPart", "path",]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用会在输出中返回有关您的资源的信息,如下所示: - {'id': 'bbb222', 'parentId': 'aaa111', 'pathPart': '{petId}', 'path': '/pets/{petId}'}
 
- Amazon CLI
- aws apigateway create-resource --rest-api-id abcd1234 \
  --region us-west-2 \
  --parent-id aaa111 \
  --path-part '{petId}'
 - 此命令的输出如下: - {
    "id": "bbb222",
    "parentId": "aaa111",
    "path": "/pets/{petId}", 
    "pathPart": "{petId}"
}
 
 您创建的 /pets/{petId}资源的资源 ID 为bbb222。您可以在 API 的设置中使用此值。
 
- 
                在以下两个步骤中,您向资源添加 HTTP 方法。在本教程中,您可以通过将 authorization-type设置为NONE,来将方法设置为具有开放访问权限。要仅允许已验证身份的用户调用此方法,您可以使用 IAM 角色和策略、Lambda 授权方(以前称为自定义授权方)或者 Amazon Cognito 用户池。有关更多信息,请参阅 在 API Gateway 中控制和管理对 REST API 的访问。
 使用以下示例在 /pets资源上添加GETHTTP 方法:
 
                - JavaScript v3
- 
                import {APIGatewayClient,  PutMethodCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new PutMethodCommand({
    restApiId: 'abcd1234',
    resourceId: 'aaa111',
    httpMethod: 'GET',
    authorizationType: 'NONE'
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("The 'GET /pets' method setup failed:\n", err)
}
})();
 成功的调用返回以下输出: {
    "apiKeyRequired": false, 
    "httpMethod": "GET", 
    "authorizationType": "NONE"
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.put_method(
        restApiId='abcd1234',
        resourceId='aaa111',
        httpMethod='GET',
        authorizationType='NONE'
    )
except botocore.exceptions.ClientError as error:
    logger.exception("The 'GET /pets' method setup failed: %s", error)
    raise
attribute=["httpMethod","authorizationType","apiKeyRequired"]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用返回以下输出: - {'httpMethod': 'GET', 'authorizationType': 'NONE', 'apiKeyRequired': False}
 
- Amazon CLI
- 
                  aws apigateway put-method --rest-api-id abcd1234 \
  --resource-id aaa111 \
  --http-method GET \
  --authorization-type "NONE" \
  --region us-west-2
 此命令的输出如下: {
    "httpMethod": "GET", 
    "authorizationType": "NONE",
    "apiKeyRequired": false
}
 
 
- 
          使用以下示例在 /pets/{petId}资源上添加GETHTTP 方法,并设置requestParameters属性将客户端提供的petId值传递给后端:
 
                  - JavaScript v3
- 
                      import {APIGatewayClient,  PutMethodCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new PutMethodCommand({
    restApiId: 'abcd1234',
    resourceId: 'bbb222',
    httpMethod: 'GET',
    authorizationType: 'NONE'
    requestParameters: {
        "method.request.path.petId" : true
    }
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("The 'GET /pets/{petId}' method setup failed:\n", err)
}
})();
 成功的调用返回以下输出: {
    "apiKeyRequired": false, 
    "httpMethod": "GET", 
    "authorizationType": "NONE",
    "requestParameters": {
       "method.request.path.petId": true
    }
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.put_method(
        restApiId='abcd1234',
        resourceId='bbb222',
        httpMethod='GET',
        authorizationType='NONE',
        requestParameters={
            "method.request.path.petId": True
        }
    )
except botocore.exceptions.ClientError as error:
    logger.exception("The 'GET /pets/{petId}' method setup failed: %s", error)
    raise
attribute=["httpMethod","authorizationType","apiKeyRequired", "requestParameters" ]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用返回以下输出: - {'httpMethod': 'GET', 'authorizationType': 'NONE', 'apiKeyRequired': False, 'requestParameters': {'method.request.path.petId': True}}
 
- Amazon CLI
- aws apigateway put-method --rest-api-id abcd1234 \
  --resource-id bbb222 --http-method GET \
  --authorization-type "NONE" \
  --region us-west-2 \
  --request-parameters method.request.path.petId=true
 - 此命令的输出如下: - {
    "httpMethod": "GET", 
    "authorizationType": "NONE", 
    "apiKeyRequired": false, 
    "requestParameters": {
        "method.request.path.petId": true
    }
}
 
 
- 
                使用以下示例为 GET /pets方法添加 200 OK 方法响应:
 
                  - JavaScript v3
- 
                      import {APIGatewayClient,  PutMethodResponseCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new PutMethodResponseCommand({
    restApiId: 'abcd1234',
    resourceId: 'aaa111',
    httpMethod: 'GET',
    statusCode: '200'
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("Set up the 200 OK response for the 'GET /pets' method failed:\n", err)
}
})();
 成功的调用返回以下输出: {
    "statusCode": "200"
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.put_method_response(
        restApiId='abcd1234',
        resourceId='aaa111',
        httpMethod='GET',
        statusCode='200'
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Set up the 200 OK response for the 'GET /pets' method failed %s.", error)
    raise
attribute=["statusCode"]
filtered_result ={key:result[key] for key in attribute}
logger.info(filtered_result)
 - 成功的调用返回以下输出: - {'statusCode': '200'}
 
- Amazon CLI
-  aws apigateway put-method-response --rest-api-id abcd1234 \ 
  --resource-id aaa111 --http-method GET \
  --status-code 200  --region us-west-2
 此命令的输出如下: {
    "statusCode": "200"
}
 
 
- 
                使用以下示例为 GET /pets/{petId}方法添加 200 OK 方法响应:
 
                  - JavaScript v3
- 
                      import {APIGatewayClient,  PutMethodResponseCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new PutMethodResponseCommand({
    restApiId: 'abcd1234',
    resourceId: 'bbb222',
    httpMethod: 'GET',
    statusCode: '200'
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("Set up the 200 OK response for the 'GET /pets/{petId}' method failed:\n", err)
}
})();
 成功的调用返回以下输出: {
    "statusCode": "200"
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.put_method_response(
        restApiId='abcd1234',
        resourceId='bbb222',
        httpMethod='GET',
        statusCode='200'
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Set up the 200 OK response for the 'GET /pets/{petId}' method failed %s.", error)
    raise
attribute=["statusCode"]
filtered_result ={key:result[key] for key in attribute}
logger.info(filtered_result)
 - 成功的调用返回以下输出: - {'statusCode': '200'}
 
- Amazon CLI
- aws apigateway put-method-response --rest-api-id abcd1234 \ 
  --resource-id bbb222 --http-method GET \
  --status-code 200  --region us-west-2
 - 此命令的输出如下: - {
    "statusCode": "200"
}
 
 
- 
          使用以下示例对 HTTP 端点配置 GET /pets方法的集成。HTTP 端点为http://petstore-demo-endpoint.execute-api.com/petstore/pets。
 
                    - JavaScript v3
- 
                        import {APIGatewayClient,  PutIntegrationCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new PutIntegrationCommand({
    restApiId: 'abcd1234',
    resourceId: 'aaa111',
    httpMethod: 'GET',
    type: 'HTTP',
    integrationHttpMethod: 'GET',
    uri: 'http://petstore-demo-endpoint.execute-api.com/petstore/pets'
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("Set up the integration of the 'GET /pets' method of the API failed:\n", err)
}
})();
 成功的调用返回以下输出: {
    "httpMethod": "GET", 
    "passthroughBehavior": "WHEN_NO_MATCH", 
    "cacheKeyParameters": [], 
    "type": "HTTP", 
    "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets", 
    "cacheNamespace": "ccc333"
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.put_integration(
        restApiId='abcd1234',
        resourceId='aaa111',
        httpMethod='GET',
        type='HTTP',
        integrationHttpMethod='GET',
        uri='http://petstore-demo-endpoint.execute-api.com/petstore/pets'
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Set up the integration of the 'GET /' method of the API failed %s.", error)
    raise
attribute=["httpMethod","passthroughBehavior","cacheKeyParameters", "type", "uri", "cacheNamespace"]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用返回以下输出: - {'httpMethod': 'GET', 'passthroughBehavior': 'WHEN_NO_MATCH', 'cacheKeyParameters': [], 'type': 'HTTP', 'uri': 'http://petstore-demo-endpoint.execute-api.com/petstore/pets', 'cacheNamespace': 'ccc333'}
 
- Amazon CLI
-  aws apigateway put-integration --rest-api-id abcd1234 \
  --resource-id aaa111 --http-method GET --type HTTP \
  --integration-http-method GET \
  --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets' \
  --region us-west-2
 此命令的输出如下: {
    "type": "HTTP",
    "httpMethod": "GET",
    "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
    "connectionType": "INTERNET",
    "passthroughBehavior": "WHEN_NO_MATCH",
    "timeoutInMillis": 29000,
    "cacheNamespace": "6sxz2j",
    "cacheKeyParameters": []
}
 
 
- 
          使用以下示例对 HTTP 端点配置 GET /pets/{petId}方法的集成。HTTP 端点为http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}。在此步骤中,您将路径参数petId映射到集成端点路径参数id。
 
                  - JavaScript v3
- 
                      import {APIGatewayClient,  PutIntegrationCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new PutIntegrationCommand({
    restApiId: 'abcd1234',
    resourceId: 'bbb222',
    httpMethod: 'GET',
    type: 'HTTP',
    integrationHttpMethod: 'GET',
    uri: 'http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}'
    requestParameters: {
        "integration.request.path.id": "method.request.path.petId"
     }
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("Set up the integration of the 'GET /pets/{petId}' method of the API failed:\n", err)
}
})();
 成功的调用返回以下输出: {
    "httpMethod": "GET", 
    "passthroughBehavior": "WHEN_NO_MATCH", 
    "cacheKeyParameters": [], 
    "type": "HTTP", 
    "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}", 
    "cacheNamespace": "ddd444",
    "requestParameters": {
       "integration.request.path.id": "method.request.path.petId"
    }
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.put_integration(
        restApiId='ieps9b05sf',
        resourceId='t8zeb4',
        httpMethod='GET',
        type='HTTP',
        integrationHttpMethod='GET',
        uri='http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}',
        requestParameters={
            "integration.request.path.id": "method.request.path.petId"
        }
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Set up the integration of the 'GET /pets/{petId}' method of the API failed %s.", error)
    raise
attribute=["httpMethod","passthroughBehavior","cacheKeyParameters", "type", "uri", "cacheNamespace", "requestParameters"]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用返回以下输出: - {'httpMethod': 'GET', 'passthroughBehavior': 'WHEN_NO_MATCH', 'cacheKeyParameters': [], 'type': 'HTTP', 'uri': 'http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}', 'cacheNamespace': 'ddd444', 'requestParameters': {'integration.request.path.id': 'method.request.path.petId'}}}
 
- Amazon CLI
-  aws apigateway put-integration --rest-api-id abcd1234 \
  --resource-id bbb222 --http-method GET --type HTTP \
  --integration-http-method GET \
  --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}' \ 
  --request-parameters '{"integration.request.path.id":"method.request.path.petId"}' \
  --region us-west-2
 此命令的输出如下: {
    "type": "HTTP",
    "httpMethod": "GET",
    "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}",
    "connectionType": "INTERNET",
    "requestParameters": {
        "integration.request.path.id": "method.request.path.petId"
    },
    "passthroughBehavior": "WHEN_NO_MATCH",
    "timeoutInMillis": 29000,
    "cacheNamespace": "rjkmth",
    "cacheKeyParameters": []
}
 
 
- 
                  使用以下示例为 GET /pets集成添加集成响应:
 
                    - JavaScript v3
- 
                        import {APIGatewayClient,  PutIntegrationResponseCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new PutIntegrationResponseCommand({
    restApiId: 'abcd1234',
    resourceId: 'aaa111',
    httpMethod: 'GET',
    statusCode: '200',
    selectionPattern: ''
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("The 'GET /pets' method integration response setup failed:\n", err)
}
})();
 成功的调用返回以下输出: {
    "selectionPattern": "", 
    "statusCode": "200"
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.put_integration_response(
        restApiId='abcd1234',
        resourceId='aaa111',
        httpMethod='GET',
        statusCode='200',
        selectionPattern='',
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Set up the integration response of the 'GET /pets' method of the API failed: %s", error)
    raise
attribute=["selectionPattern","statusCode"]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用返回以下输出: - {'selectionPattern': "", 'statusCode': '200'}
 
- Amazon CLI
-  
                        aws apigateway put-integration-response --rest-api-id abcd1234 \
  --resource-id aaa111 --http-method GET \
  --status-code 200 --selection-pattern ""  \
  --region us-west-2
 此命令的输出如下: {
    "statusCode": "200",
    "selectionPattern": "" 
}
 
 
- 
                使用以下示例为 GET /pets/{petId}集成添加集成响应:
 
                  - JavaScript v3
- 
                      import {APIGatewayClient,  PutIntegrationResponseCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new PutIntegrationResponseCommand({
    restApiId: 'abcd1234',
    resourceId: 'bbb222',
    httpMethod: 'GET',
    statusCode: '200',
    selectionPattern: ''
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("The 'GET /pets/{petId}' method integration response setup failed:\n", err)
}
})();
 成功的调用返回以下输出: {
    "selectionPattern": "", 
    "statusCode": "200"
}
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.put_integration_response(
        restApiId='abcd1234',
        resourceId='bbb222',
        httpMethod='GET',
        statusCode='200',
        selectionPattern='',
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Set up the integration response of the 'GET /pets/{petId}' method of the API failed: %s", error)
    raise
attribute=["selectionPattern","statusCode"]
filtered_result ={key:result[key] for key in attribute}
print(filtered_result)
 - 成功的调用返回以下输出: - {'selectionPattern': "", 'statusCode': '200'}
 
- Amazon CLI
- 
                      aws apigateway put-integration-response --rest-api-id abcd1234 \
  --resource-id bbb222 --http-method GET 
  --status-code 200 --selection-pattern ""  
  --region us-west-2
 此命令的输出如下: {
    "statusCode": "200",
    "selectionPattern": "" 
}
 
 创建集成响应后,API 可以在 PetStore 网站上查询所提供的宠物,并查看指定标识符的单个宠物。在客户能够调用 API 之前,您必须先部署该 API。我们建议您在部署 API 之前先对其进行测试。 
- 使用以下示例测试 - GET /pets方法:
 - 
                  - JavaScript v3
- 
                      import {APIGatewayClient,  TestInvokeMethodCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new TestInvokeMethodCommand({
    restApiId: 'abcd1234',
    resourceId: 'aaa111',
    httpMethod: 'GET',
    pathWithQueryString: '/',
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("The test on 'GET /pets' method failed:\n", err)
}
})();
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.test_invoke_method(
        restApiId='abcd1234',
        resourceId='aaa111',
        httpMethod='GET',
        pathWithQueryString='/',
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Test invoke method on 'GET /pets' failed: %s", error)
    raise
print(result)
 
- Amazon CLI
- 
                      aws apigateway test-invoke-method --rest-api-id abcd1234 /
  --resource-id aaa111 /
  --http-method GET /
  --path-with-query-string '/'
 
 
- 使用以下示例测试 - GET /pets/{petId}方法,其中- petId为 3:
 - 
                  - JavaScript v3
- 
                      import {APIGatewayClient,  TestInvokeMethodCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new TestInvokeMethodCommand({
    restApiId: 'abcd1234',
    resourceId: 'bbb222',
    httpMethod: 'GET',
    pathWithQueryString: '/pets/3',
});
try {
    const results = await apig.send(command)
    console.log(results)
} catch (err) {
    console.log("The test on 'GET /pets/{petId}' method failed:\n", err)
}
})();
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.test_invoke_method(
        restApiId='abcd1234',
        resourceId='bbb222',
        httpMethod='GET',
        pathWithQueryString='/pets/3',
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Test invoke method on 'GET /pets/{petId}' failed: %s", error)
    raise
print(result)
 
- Amazon CLI
- 
                      aws apigateway test-invoke-method --rest-api-id abcd1234 /
  --resource-id bbb222 /
  --http-method GET /
  --path-with-query-string '/pets/3'
 
 - 成功测试 API 后,您可以将其部署到阶段。 
- 
                使用以下示例将 API 部署到名为 test的阶段。将 API 部署到阶段时,API 调用方可以调用 API。
 
                  - JavaScript v3
- 
                      import {APIGatewayClient,  CreateDeploymentCommand } from "@aws-sdk/client-api-gateway";
(async function (){
const apig = new APIGatewayClient({region:"us-east-1"});
const command = new CreateDeploymentCommand({
    restApiId: 'abcd1234',
    stageName: 'test',
    stageDescription: 'test deployment'
});
try {
    const results = await apig.send(command)
    console.log("Deploying API succeeded\n", results)
} catch (err) {
    console.log("Deploying API failed:\n", err)
}
})();
 
- Python
- import botocore
import boto3
import logging
logger = logging.getLogger()
apig = boto3.client('apigateway')
try:
    result = apig.create_deployment(
        restApiId='ieps9b05sf',
        stageName='test',
        stageDescription='my test stage',
    )
except botocore.exceptions.ClientError as error:
    logger.exception("Error deploying stage  %s.", error)
    raise
print('Deploying API succeeded')
print(result)
 
- Amazon CLI
- aws apigateway create-deployment --rest-api-id abcd1234 \ 
  --region us-west-2 \
  --stage-name test \
  --stage-description 'Test stage' \
  --description 'First deployment'
 - 此命令的输出如下: - {
    "id": "ab1c1d",
    "description": "First deployment",
    "createdDate": "2022-12-15T08:44:13-08:00"
}
 
 现在,客户可以调用您的 API 了。您可以通过在浏览器中输入 https://abcd1234.execute-api.us-west-2.amazonaws.com/test/petsURL 并将abcd1234替换为 API 的标识符,测试此 API。
 
有关如何使用 Amazon SDK 或 Amazon CLI 创建或更新 API 的更多示例,请参阅 Actions for API Gateway using Amazon SDKs。
   
    自动设置 API
    在创建 API 时,您不必按部就班地创建,而是可以通过使用 OpenAPI、Amazon CloudFormation 或 Terraform 来自动创建和清理 Amazon 资源。
    您可以将 OpenAPI 定义导入到 API Gateway 中。有关更多信息,请参阅 在 API Gateway 中使用 OpenAPI 开发 REST API。
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "Simple PetStore (OpenAPI)",
    "description" : "Demo API created using OpenAPI",
    "version" : "2024-05-24T20:39:34Z"
  },
  "servers" : [ {
    "url" : "{basePath}",
    "variables" : {
      "basePath" : {
        "default" : "Prod"
      }
    }
  } ],
  "paths" : {
    "/pets" : {
      "get" : {
        "responses" : {
          "200" : {
            "description" : "200 response",
            "content" : { }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "http",
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "passthroughBehavior" : "when_no_match",
          "timeoutInMillis" : 29000
        }
      }
    },
    "/pets/{petId}" : {
      "get" : {
        "parameters" : [ {
          "name" : "petId",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response",
            "content" : { }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "http",
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}",
          "responses" : {
            "default" : {
              "statusCode" : "200"
            }
          },
          "requestParameters" : {
            "integration.request.path.id" : "method.request.path.petId"
          },
          "passthroughBehavior" : "when_no_match",
          "timeoutInMillis" : 29000
        }
      }
    }
  },
  "components" : { }
}
要部署您的 Amazon CloudFormation 模板,请参阅在 Amazon CloudFormation 控制台上创建堆栈。
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: Simple PetStore (AWS CloudFormation)
  PetsResource:
    Type: 'AWS::ApiGateway::Resource'
    Properties:
      RestApiId: !Ref Api
      ParentId: !GetAtt Api.RootResourceId
      PathPart: 'pets'
  PetIdResource:
    Type: 'AWS::ApiGateway::Resource'
    Properties:
      RestApiId: !Ref Api
      ParentId: !Ref PetsResource
      PathPart: '{petId}'
  PetsMethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetsResource
      HttpMethod: GET
      AuthorizationType: NONE
      Integration:
        Type: HTTP
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
        IntegrationResponses:
          - StatusCode: '200'
      MethodResponses:
        - StatusCode: '200'
  PetIdMethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetIdResource
      HttpMethod: GET
      AuthorizationType: NONE
      RequestParameters: 
        method.request.path.petId: true
      Integration:
        Type: HTTP
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}
        RequestParameters:
          integration.request.path.id: method.request.path.petId
        IntegrationResponses:
          - StatusCode: '200'
      MethodResponses:
        - StatusCode: '200'
  ApiDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn:
      - PetsMethodGet
    Properties:
      RestApiId: !Ref Api
      StageName: Prod
Outputs:
  ApiRootUrl:
    Description: Root Url of the API
    Value: !Sub 'https://${Api}.execute-api.${AWS::Region}.amazonaws.com/Prod'
有关 Terraform 的信息,请参阅 Terraform。
provider "aws" {
  region = "us-east-1" # Update with your desired region
}
resource "aws_api_gateway_rest_api" "Api" {
  name        = "Simple PetStore (Terraform)"
  description = "Demo API created using Terraform"
}
resource "aws_api_gateway_resource" "petsResource"{
    rest_api_id = aws_api_gateway_rest_api.Api.id
    parent_id = aws_api_gateway_rest_api.Api.root_resource_id
    path_part = "pets"
}
resource "aws_api_gateway_resource" "petIdResource"{
    rest_api_id = aws_api_gateway_rest_api.Api.id
    parent_id = aws_api_gateway_resource.petsResource.id
    path_part = "{petId}"
}
resource "aws_api_gateway_method" "petsMethodGet" {
  rest_api_id   = aws_api_gateway_rest_api.Api.id
  resource_id   = aws_api_gateway_resource.petsResource.id
  http_method   = "GET"
  authorization = "NONE"
}
resource "aws_api_gateway_method_response" "petsMethodResponseGet" {
    rest_api_id = aws_api_gateway_rest_api.Api.id 
    resource_id = aws_api_gateway_resource.petsResource.id
    http_method = aws_api_gateway_method.petsMethodGet.http_method 
    status_code ="200"
}
resource "aws_api_gateway_integration" "petsIntegration" {
  rest_api_id = aws_api_gateway_rest_api.Api.id
  resource_id = aws_api_gateway_resource.petsResource.id
  http_method = aws_api_gateway_method.petsMethodGet.http_method
  type        = "HTTP"
  
  uri                     = "http://petstore-demo-endpoint.execute-api.com/petstore/pets"
  integration_http_method = "GET"
  depends_on              = [aws_api_gateway_method.petsMethodGet]
}
resource "aws_api_gateway_integration_response" "petsIntegrationResponse" {
    rest_api_id = aws_api_gateway_rest_api.Api.id
    resource_id = aws_api_gateway_resource.petsResource.id
    http_method = aws_api_gateway_method.petsMethodGet.http_method
    status_code = aws_api_gateway_method_response.petsMethodResponseGet.status_code
}
resource "aws_api_gateway_method" "petIdMethodGet" {
    rest_api_id   = aws_api_gateway_rest_api.Api.id
    resource_id   = aws_api_gateway_resource.petIdResource.id
    http_method   = "GET"
    authorization = "NONE"
    request_parameters = {"method.request.path.petId" = true}
}
resource "aws_api_gateway_method_response" "petIdMethodResponseGet" {
    rest_api_id = aws_api_gateway_rest_api.Api.id 
    resource_id = aws_api_gateway_resource.petIdResource.id
    http_method = aws_api_gateway_method.petIdMethodGet.http_method 
    status_code ="200"
}
resource "aws_api_gateway_integration" "petIdIntegration" {
    rest_api_id = aws_api_gateway_rest_api.Api.id
    resource_id = aws_api_gateway_resource.petIdResource.id
    http_method = aws_api_gateway_method.petIdMethodGet.http_method
    type        = "HTTP"
    uri                     = "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}"
    integration_http_method = "GET"
    request_parameters = {"integration.request.path.id" = "method.request.path.petId"}
    depends_on              = [aws_api_gateway_method.petIdMethodGet]
}
resource "aws_api_gateway_integration_response" "petIdIntegrationResponse" {
    rest_api_id = aws_api_gateway_rest_api.Api.id
    resource_id = aws_api_gateway_resource.petIdResource.id
    http_method = aws_api_gateway_method.petIdMethodGet.http_method
    status_code = aws_api_gateway_method_response.petIdMethodResponseGet.status_code
}
resource "aws_api_gateway_deployment" "Deployment" {
  rest_api_id = aws_api_gateway_rest_api.Api.id
  depends_on  = [aws_api_gateway_integration.petsIntegration,aws_api_gateway_integration.petIdIntegration ]
}
resource "aws_api_gateway_stage" "Stage" {
  stage_name    = "Prod"
  rest_api_id   = aws_api_gateway_rest_api.Api.id
  deployment_id = aws_api_gateway_deployment.Deployment.id
}