Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.
Utilisez le didacticiel suivant pour créer une PetStore API prenant en charge les GET
/pets/{petId}
méthodes GET /pets
et. Ces méthodes sont intégrées avec un point de terminaison HTTP. Vous pouvez suivre ce didacticiel en utilisant le AWS SDK pour JavaScript, le SDK pour Python (Boto3) ou le. AWS CLI Vous pouvez utiliser les fonctions ou commandes suivantes pour configurer votre API :
Pour plus d'informations sur le AWS SDK pour la JavaScript version 3, voir À quoi sert le AWS SDK ? JavaScript . Pour plus d’informations sur le kit SDK pour Python (Boto3), consultez AWS SDK for Python (Boto3). Pour plus d'informations sur le AWS CLI, voir Qu'est-ce que le AWS CLI ? .
Configuration d'une API optimisée pour les périphériques PetStore
Dans ce didacticiel, les exemples de commandes utilisent des valeurs d'espace réservé pour des valeurs IDs telles que l'ID d'API et l'ID de ressource. Lorsque vous réalisez ce didacticiel, remplacez ces valeurs par les vôtres.
Pour configurer une API optimisée pour les périphériques à l'aide PetStore de AWS SDKs
-
Utilisez l’exemple suivant pour créer une entité
RestApi
: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) } })();
Un appel réussi renvoie l’ID d’API et l’ID de ressource racine de votre API dans une sortie similaire à la suivante :
{ 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: [ '*' ] }
L’API que vous avez créée possède l’ID d’API
abcd1234
et l’ID de ressource racineefg567
. Vous allez utiliser ces valeurs pour configurer votre API. -
Ensuite, vous allez ajouter une ressource enfant sous la racine et spécifier
RootResourceId
comme valeur de la propriétéparentId
. Utilisez l'exemple suivant pour créer une/pets
ressource pour votre API :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) } })();
Un appel réussi renvoie des informations sur votre ressource dans une sortie similaire à la suivante :
{ "path": "/pets", "pathPart": "pets", "id": "aaa111", "parentId": "efg567'" }
La ressource
/pets
que vous avez créée possède l’ID de ressourceaaa111
. Vous allez utiliser cette valeur pour configurer votre API. -
Ensuite, vous allez ajouter une ressource enfant sous la ressource
/pets
. La ressource enfant/{petId}
possède un paramètre de chemin pour{petId}
. Pour qu’un chemin fasse partie d’un paramètre de chemin, vous devez l’entourer d’une paire d’accolades,{ }
. Utilisez l'exemple suivant pour créer une/pets/{petId}
ressource pour votre API :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) } })();
Un appel réussi renvoie des informations sur votre ressource dans une sortie similaire à la suivante :
{ "path": "/pets/{petId}", "pathPart": "{petId}", "id": "bbb222", "parentId": "aaa111'" }
La ressource
/pets/{petId}
que vous avez créée possède l’ID de ressourcebbb222
. Vous allez utiliser cette valeur pour configurer votre API. -
Au cours des deux étapes suivantes, vous allez ajouter des méthodes HTTP à vos ressources. Dans ce didacticiel, vous allez définir les méthodes pour qu’elles soient en accès libre en définissant
authorization-type
surNONE
. Pour autoriser uniquement les utilisateurs authentifiés à appeler la méthode, vous pouvez utiliser des rôles et des politiques IAM, un mécanisme d’autorisation Lambda (anciennement appelé mécanisme d’autorisation personnalisée) ou un groupe d’utilisateurs Amazon Cognito. Pour de plus amples informations, veuillez consulter Contrôle et gestion de l’accès aux API REST dans API Gateway.Utilisez l'exemple suivant pour ajouter la méthode
GET
HTTP à la/pets
ressource :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) } })();
Un appel réussi renvoie une sortie similaire à la suivante :
{ "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE" }
-
Utilisez l'exemple suivant pour ajouter la méthode
GET
HTTP à la/pets/{petId}
ressource et pour définir larequestParameters
propriété afin de transmettre lapetId
valeur fournie par le client au backend :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) } })();
Un appel réussi renvoie une sortie similaire à la suivante :
{ "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE", "requestParameters": { "method.request.path.petId": true } }
-
Utilisez l’exemple suivant pour ajouter la réponse de la méthode 200 OK à la méthode
GET /pets
: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) } })();
Un appel réussi renvoie une sortie similaire à la suivante :
{ "statusCode": "200" }
-
Utilisez l’exemple suivant pour ajouter la réponse de la méthode 200 OK à la méthode
GET /pets/{petId}
: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) } })();
Un appel réussi renvoie une sortie similaire à la suivante :
{ "statusCode": "200" }
-
Utilisez l'exemple suivant pour configurer une intégration de la
GET /pets
méthode avec un point de terminaison HTTP. Le point de terminaison HTTP esthttp://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) } })();
Un appel réussi renvoie une sortie similaire à la suivante :
{ "httpMethod": "GET", "passthroughBehavior": "WHEN_NO_MATCH", "cacheKeyParameters": [], "type": "HTTP", "uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "cacheNamespace": "ccc333" }
-
Utilisez l'exemple suivant pour configurer une intégration de la
GET /pets/{petId}
méthode avec un point de terminaison HTTP. Le point de terminaison HTTP esthttp://petstore-demo-endpoint.execute-api.com/petstore/pets/{id}
. À cette étape, vous allez mapper le paramètre de cheminpetId
à celui du point de terminaison d’intégration deid
.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) } })();
Un appel réussi renvoie une sortie similaire à la suivante :
{ "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" } }
-
Utilisez l'exemple suivant pour ajouter la réponse d'intégration pour l'
GET /pets
intégration :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) } })();
Un appel réussi renvoie une sortie similaire à la suivante :
{ "selectionPattern": "", "statusCode": "200" }
-
Utilisez l'exemple suivant pour ajouter la réponse d'intégration pour l'
GET /pets/{petId}
intégration :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) } })();
Un appel réussi renvoie une sortie similaire à la suivante :
{ "selectionPattern": "", "statusCode": "200" }
Une fois que vous avez créé la réponse d'intégration, votre API peut interroger les animaux de compagnie disponibles sur le PetStore site Web et consulter un animal individuel avec un identifiant spécifique. Avant que votre API puisse être appelée par vos clients, vous devez la déployer. Nous vous recommandons de la tester avant de la déployer.
Utilisez l'exemple suivant pour tester la
GET /pets
méthode :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) } })();
Utilisez l'exemple suivant pour tester la
GET /pets/{petId}
méthode avec une valeurpetId
de 3 :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) } })();
Après avoir testé votre API, vous pouvez la déployer dans une étape.
-
Utilisez l'exemple suivant pour déployer votre API sur une étape nommée
test
. Lorsque vous déployez votre API dans une étape, les appelants d’API peuvent invoquer votre API.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) } })();
Vos clients peuvent désormais appeler votre API. Vous pouvez tester cette API en saisissant l’URL
https://abcd1234.execute-api.us-west-2.amazonaws.com/test/pets
dans un navigateur et en remplaçantabcd1234
par l’identifiant de votre API.
Pour plus d'exemples de création ou de mise à jour d'une API à l'aide de AWS SDKs ou de AWS CLI, consultez la section Actions pour API Gateway en utilisant AWS SDKs.
Automatisation de la configuration de votre API
Au lieu de créer votre API step-by-step, vous pouvez automatiser la création et le nettoyage des AWS ressources en utilisant OpenAPI AWS CloudFormation ou Terraform pour créer votre API.
Vous pouvez importer une définition OpenAPI dans API Gateway. Pour de plus amples informations, veuillez consulter Développement d’API REST à l’aide d’OpenAPI dans API Gateway.
{ "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" : { } }
Pour déployer votre AWS CloudFormation modèle, consultez la section Création d'une pile sur la AWS CloudFormation console.
AWSTemplateFormatVersion: 2010-09-09 Resources: Api: Type: 'AWS::ApiGateway::RestApi' Properties: Name: Simple PetStore (AWS CloudFormation) PetsResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !GetAtt Api.RootResourceId PathPart: 'pets' PetIdResource: Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref Api ParentId: !Ref PetsResource PathPart: '{petId}' PetsMethodGet: Type: 'AWS::ApiGateway::Method' Properties: RestApiId: !Ref Api 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'
Pour plus d’informations sur Terraform, consultez 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 }