使用 Amazon SDK 设置边缘优化的 API - Amazon API Gateway
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

使用 Amazon SDK 设置边缘优化的 API

以下代码示例显示了如何创建支持 GET /petsGET /pets/{petId} 方法的 PetStore API。您可以使用以下函数来设置 API:

有关适用于 JavaScript 的 Amazon SDK v3 的更多信息,请参阅 What's the Amazon SDK for JavaScript? 有关适用于 Python 的 SDK(Boto3)的更多信息,请参阅 Amazon SDK for Python (Boto3)

使用 Amazon SDK 设置简单 PetStore API
  1. 下面的示例将创建 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'}

    您创建的 API 的 API ID 为 abcd1234,根资源 ID 为 efg567。您可以在 API 的设置中使用这些值。

  2. 以下示例为 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'}

    您创建的 /pets 资源的资源 ID 为 aaa111。您可以在 API 的设置中使用此值。

  3. 以下示例为 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}'}

    您创建的 /pets/{petId} 资源的资源 ID 为 bbb222。您可以在 API 的设置中使用此值。

  4. 以下示例在 /pets 资源上添加 GET HTTP 方法:

    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}
  5. 以下示例在 /pets/{petId} 资源上添加 GET HTTP 方法,并设置 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}}
  6. 以下示例添加 GET /pets 方法的方法响应:

    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'}
  7. 以下示例添加 GET /pets/{petId} 方法的方法响应:

    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'}
  8. 以下示例使用 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'}
  9. 以下示例使用 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'}}}
  10. 以下示例添加 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'}
  11. 以下示例添加 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'}
  12. 我们建议先测试您的 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)
  13. 以下示例以 petId 为 3 来测试 GET /pets/{petId} 方法:

    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)

    成功测试 API 后,您可以将其部署到阶段。

  14. 以下示例将 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 SDK 创建 API 的更多示例,请参阅 Actions for API Gateway using Amazon SDKs