Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.
Verwenden Sie das folgende Tutorial, um eine PetStore API zu erstellen, die die GET
/pets/{petId}
Methoden GET /pets
und unterstützt. Die Methoden sind mit einem HTTP-Endpunkt integriert. Sie können diesem Tutorial mit dem AWS SDK für JavaScript, dem SDK for Python (Boto3) oder dem folgen. AWS CLI Das API richten Sie mithilfe der folgenden Funktionen und Befehle ein:
Weitere Informationen zum AWS SDK für JavaScript v3 finden Sie unter Wofür ist das AWS SDK? JavaScript . Weitere Informationen zum SDK für Python (Boto3) finden Sie unter AWS SDK for Python (Boto3). Weitere Informationen zu dem AWS CLI finden Sie unter Was ist der AWS CLI? .
Richten Sie eine Edge-optimierte API PetStore ein
In diesem Tutorial verwenden Beispielbefehle Platzhalterwerte für Werte IDs wie API-ID und Ressourcen-ID. Nach Abschluss des Tutorials ersetzen Sie die Beispielwerte mit Ihren eigenen Werten.
Um eine PetStore Edge-optimierte API einzurichten, verwenden Sie AWS SDKs
-
Erstellen Sie mithilfe des folgenden Beispiels eine
RestApi
-Entity: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) } })();
Ein erfolgreicher Aufruf gibt Ihre API-ID und die Root-Ressourcen-ID Ihrer API in einer Ausgabe wie folgt zurück:
{ id: 'abc1234', name: 'PetStore (JavaScript v3 SDK)', description: 'Demo API created using the AWS SDK for node.js', createdDate: 2017-09-05T19:32:35.000Z, version: '0.00.001', rootResourceId: 'efg567' binaryMediaTypes: [ '*' ] }
Die von Ihnen erstellte API hat die API-ID
abcd1234
und die Root-Ressourcen-IDefg567
. Diese Werte verwenden Sie nun bei der Einrichtung Ihrer API. -
Als Nächstes erstellen Sie eine untergeordnete Ressource für die Root-Ressource. Hierzu geben Sie
RootResourceId
als denparentId
-Eigenschaftswert an. Verwenden Sie das folgende Beispiel, um eine/pets
Ressource für Ihre API zu erstellen: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) } })();
Ein erfolgreicher Aufruf gibt Informationen zur Ressource in einer Ausgabe wie folgt zurück:
{ "path": "/pets", "pathPart": "pets", "id": "aaa111", "parentId": "efg567'" }
Die von Ihnen erstellte
/pets
-Ressource hat die Ressourcen-IDaaa111
. Diesen Wert verwenden Sie bei der Einrichtung Ihrer API. -
Als Nächstes fügen Sie der
/pets
-Ressource eine untergeordnete Ressource hinzu. Diese Ressource,/{petId}
, besitzt einen Pfadparameter für die{petId}
. Wenn Sie einen Teil eines Pfads zu einem Pfadparameter machen wollen, setzen Sie ihn in geschweifte Klammern{ }
. Verwenden Sie das folgende Beispiel, um eine/pets/{petId}
Ressource für Ihre API zu erstellen: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) } })();
Ein erfolgreicher Aufruf gibt Informationen zur Ressource in einer Ausgabe wie folgt zurück:
{ "path": "/pets/{petId}", "pathPart": "{petId}", "id": "bbb222", "parentId": "aaa111'" }
Die von Ihnen erstellte
/pets/{petId}
-Ressource hat die Ressourcen-IDbbb222
. Diesen Wert verwenden Sie bei der Einrichtung Ihrer API. -
In den nächsten zwei Schritten fügen Sie HTTP-Methoden zu Ihren Ressourcen hinzu. In diesem Tutorial legen Sie fest, dass die Methoden offenen Zugriff haben sollen. Hierfür setzen Sie
authorization-type
aufNONE
. Damit nur authentifizierte Benutzer die Methode aufrufen können, können Sie IAM-Rollen und -Richtlinien, einen Lambda-Genehmiger (früher als benutzerdefinierter Genehmiger bekannt) oder einen Amazon Cognito-Benutzerpool verwenden. Weitere Informationen finden Sie unter Zugriff auf REST-APIs in API Gateway steuern und verwalten.Verwenden Sie das folgende Beispiel, um die
GET
HTTP-Methode zur/pets
Ressource hinzuzufügen: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) } })();
Ein erfolgreicher Aufruf gibt Folgendes zurück:
{ "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE" }
-
Verwenden Sie das folgende Beispiel, um der
/pets/{petId}
Ressource dieGET
HTTP-Methode hinzuzufügen und dierequestParameters
Eigenschaft so festzulegen, dass der vom Client bereitgestelltepetId
Wert an das Backend übergeben wird: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) } })();
Ein erfolgreicher Aufruf gibt Folgendes zurück:
{ "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE", "requestParameters": { "method.request.path.petId": true } }
-
Fügen Sie mithilfe des folgenden Beispiels die 200 OK-Methodenantwort für die
GET /pets
-Methode hinzu: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) } })();
Ein erfolgreicher Aufruf gibt Folgendes zurück:
{ "statusCode": "200" }
-
Fügen Sie mithilfe des folgenden Beispiels die 200 OK-Methodenantwort für die
GET /pets/{petId}
-Methode hinzu: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) } })();
Ein erfolgreicher Aufruf gibt Folgendes zurück:
{ "statusCode": "200" }
-
Verwenden Sie das folgende Beispiel, um eine Integration für die
GET /pets
Methode mit einem HTTP-Endpunkt zu konfigurieren. Der HTTPS-Endpunkt lautethttp://petstore-demo-endpoint.execute-api.com/petstore/pets
.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) } })();
Ein erfolgreicher Aufruf gibt Folgendes zurück:
{ "httpMethod": "GET", "passthroughBehavior": "WHEN_NO_MATCH", "cacheKeyParameters": [], "type": "HTTP", "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "cacheNamespace": "ccc333" }
-
Verwenden Sie das folgende Beispiel, um eine Integration für die
GET /pets/{petId}
Methode mit einem HTTP-Endpunkt zu konfigurieren. Der HTTPS-Endpunkt lautethttp://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}
. Im folgenden Schritt ordnen Sie den PfadparameterpetId
dem Integrationsendpunkt-Pfadparameterid
zu.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) } })();
Ein erfolgreicher Aufruf gibt Folgendes zurück:
{ "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" } }
-
Verwenden Sie das folgende Beispiel, um die Integrationsantwort für die
GET /pets
Integration hinzuzufügen: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) } })();
Ein erfolgreicher Aufruf gibt Folgendes zurück:
{ "selectionPattern": "", "statusCode": "200" }
-
Verwenden Sie das folgende Beispiel, um die Integrationsantwort für die
GET /pets/{petId}
Integration hinzuzufügen: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) } })();
Ein erfolgreicher Aufruf gibt Folgendes zurück:
{ "selectionPattern": "", "statusCode": "200" }
Nachdem Sie die Integrationsantwort erstellt haben, kann Ihre API verfügbare Haustiere auf der PetStore Website abfragen und einzelne Haustiere mit einer bestimmten Kennung anzeigen. Sie müssen Ihre fertiggestellte API bereitstellen, damit sie von Ihren Kunden abgerufen werden kann. Wir empfehlen, Ihre API gründlich zu testen, bevor Sie sie bereitstellen.
Verwenden Sie das folgende Beispiel, um die
GET /pets
Methode zu testen: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) } })();
Verwenden Sie das folgende Beispiel, um die
GET /pets/{petId}
Methode mit einem WertpetId
von 3 zu testen: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) } })();
Nach einem erfolgreichen Test Ihrer API können Sie diese nun auf einer Stufe bereitstellen.
-
Verwenden Sie das folgende Beispiel, um Ihre API in einer Phase mit dem Namen bereitzustellen
test
. Nach der Bereitstellung Ihrer API in einer Stufe können API-Aufrufer nun Ihre API aufrufen.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) } })();
D. h. dass Ihre API jetzt von Kunden aufgerufen werden kann. Sie können diese API testen, indem Sie die
https://abcd1234.execute-api.us-west-2.amazonaws.com/test/pets
-URL in einen Browser eingeben undabcd1234
durch den Bezeichner Ihrer API ersetzen.
Weitere Beispiele zum Erstellen oder Aktualisieren einer API mithilfe von AWS SDKs oder finden Sie unter Aktionen für die AWS CLI Verwendung von API Gateway AWS SDKs.
Automatische Einrichtung Ihrer API
Anstatt Ihre API zu erstellen step-by-step, können Sie die Erstellung und Bereinigung von AWS Ressourcen automatisieren, indem Sie OpenAPI oder Terraform verwenden AWS CloudFormation, um Ihre API zu erstellen.
Sie können eine OpenAPI-Definition in API Gateway importieren. Weitere Informationen finden Sie unter REST-APIs mit OpenAPI in API Gateway erstellen.
{ "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" : { } }
Informationen zum Bereitstellen Ihrer AWS CloudFormation Vorlage finden Sie unter Einen Stack auf der AWS CloudFormation Konsole erstellen.
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'
Weitere Informationen zu Terraform finden Sie unter 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 }