APIExemples de passerelles utilisées SDK pour Python (Boto3) - Exemples de code de l'AWS SDK

D'autres AWS SDK exemples sont disponibles dans le GitHub dépôt AWS Doc SDK Examples.

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.

APIExemples de passerelles utilisées SDK pour Python (Boto3)

Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants à l'aide de la API passerelle AWS SDK for Python (Boto3) with.

Les actions sont des extraits de code de programmes plus larges et doivent être exécutées dans leur contexte. Les actions vous indiquent comment appeler des fonctions de service individuelles, mais vous pouvez les visualiser dans leur contexte dans les scénarios correspondants.

Les scénarios sont des exemples de code qui vous montrent comment accomplir des tâches spécifiques en appelant plusieurs fonctions au sein d'un service ou en les combinant à d'autres Services AWS.

Chaque exemple inclut un lien vers le code source complet, où vous trouverez des instructions sur la façon de configurer et d'exécuter le code en contexte.

Actions

L'exemple de code suivant montre comment utiliserCreateDeployment.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def deploy_api(self, stage_name): """ Deploys a REST API. After a REST API is deployed, it can be called from any REST client, such as the Python Requests package or Postman. :param stage_name: The stage of the API to deploy, such as 'test'. :return: The base URL of the deployed REST API. """ try: self.apig_client.create_deployment( restApiId=self.api_id, stageName=stage_name ) self.stage = stage_name logger.info("Deployed stage %s.", stage_name) except ClientError: logger.exception("Couldn't deploy stage %s.", stage_name) raise else: return self.api_url() def api_url(self, resource=None): """ Builds the REST API URL from its parts. :param resource: The resource path to append to the base URL. :return: The REST URL to the specified resource. """ url = ( f"https://{self.api_id}.execute-api.{self.apig_client.meta.region_name}" f".amazonaws.com/{self.stage}" ) if resource is not None: url = f"{url}/{resource}" return url
  • Pour API plus de détails, reportez-vous CreateDeploymentà la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserCreateResource.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def add_rest_resource(self, parent_id, resource_path): """ Adds a resource to a REST API. :param parent_id: The ID of the parent resource. :param resource_path: The path of the new resource, relative to the parent. :return: The ID of the new resource. """ try: result = self.apig_client.create_resource( restApiId=self.api_id, parentId=parent_id, pathPart=resource_path ) resource_id = result["id"] logger.info("Created resource %s.", resource_path) except ClientError: logger.exception("Couldn't create resource %s.", resource_path) raise else: return resource_id
  • Pour API plus de détails, reportez-vous CreateResourceà la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserCreateRestApi.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def create_rest_api(self, api_name): """ Creates a REST API on API Gateway. The default API has only a root resource and no HTTP methods. :param api_name: The name of the API. This descriptive name is not used in the API path. :return: The ID of the newly created API. """ try: result = self.apig_client.create_rest_api(name=api_name) self.api_id = result["id"] logger.info("Created REST API %s with ID %s.", api_name, self.api_id) except ClientError: logger.exception("Couldn't create REST API %s.", api_name) raise try: result = self.apig_client.get_resources(restApiId=self.api_id) self.root_id = next( item for item in result["items"] if item["path"] == "/" )["id"] except ClientError: logger.exception("Couldn't get resources for API %s.", self.api_id) raise except StopIteration as err: logger.exception("No root resource found in API %s.", self.api_id) raise ValueError from err return self.api_id
  • Pour API plus de détails, reportez-vous CreateRestApià la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserDeleteRestApi.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def delete_rest_api(self): """ Deletes a REST API, including all of its resources and configuration. """ try: self.apig_client.delete_rest_api(restApiId=self.api_id) logger.info("Deleted REST API %s.", self.api_id) self.api_id = None except ClientError: logger.exception("Couldn't delete REST API %s.", self.api_id) raise
  • Pour API plus de détails, reportez-vous DeleteRestApià la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserGetResources.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def create_rest_api(self, api_name): """ Creates a REST API on API Gateway. The default API has only a root resource and no HTTP methods. :param api_name: The name of the API. This descriptive name is not used in the API path. :return: The ID of the newly created API. """ try: result = self.apig_client.create_rest_api(name=api_name) self.api_id = result["id"] logger.info("Created REST API %s with ID %s.", api_name, self.api_id) except ClientError: logger.exception("Couldn't create REST API %s.", api_name) raise try: result = self.apig_client.get_resources(restApiId=self.api_id) self.root_id = next( item for item in result["items"] if item["path"] == "/" )["id"] except ClientError: logger.exception("Couldn't get resources for API %s.", self.api_id) raise except StopIteration as err: logger.exception("No root resource found in API %s.", self.api_id) raise ValueError from err return self.api_id
  • Pour API plus de détails, reportez-vous GetResourcesà la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserGetRestApis.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def get_rest_api_id(self, api_name): """ Gets the ID of a REST API from its name by searching the list of REST APIs for the current account. Because names need not be unique, this returns only the first API with the specified name. :param api_name: The name of the API to look up. :return: The ID of the specified API. """ try: rest_api = None paginator = self.apig_client.get_paginator("get_rest_apis") for page in paginator.paginate(): rest_api = next( (item for item in page["items"] if item["name"] == api_name), None ) if rest_api is not None: break self.api_id = rest_api["id"] logger.info("Found ID %s for API %s.", rest_api["id"], api_name) except ClientError: logger.exception("Couldn't find ID for API %s.", api_name) raise else: return rest_api["id"]
  • Pour API plus de détails, reportez-vous GetRestApisà la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserPutIntegration.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def add_integration_method( self, resource_id, rest_method, service_endpoint_prefix, service_action, service_method, role_arn, mapping_template, ): """ Adds an integration method to a REST API. An integration method is a REST resource, such as '/users', and an HTTP verb, such as GET. The integration method is backed by an AWS service, such as Amazon DynamoDB. :param resource_id: The ID of the REST resource. :param rest_method: The HTTP verb used with the REST resource. :param service_endpoint_prefix: The service endpoint that is integrated with this method, such as 'dynamodb'. :param service_action: The action that is called on the service, such as 'GetItem'. :param service_method: The HTTP method of the service request, such as POST. :param role_arn: The Amazon Resource Name (ARN) of a role that grants API Gateway permission to use the specified action with the service. :param mapping_template: A mapping template that is used to translate REST elements, such as query parameters, to the request body format required by the service. """ service_uri = ( f"arn:aws:apigateway:{self.apig_client.meta.region_name}" f":{service_endpoint_prefix}:action/{service_action}" ) try: self.apig_client.put_method( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, authorizationType="NONE", ) self.apig_client.put_method_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseModels={"application/json": "Empty"}, ) logger.info("Created %s method for resource %s.", rest_method, resource_id) except ClientError: logger.exception( "Couldn't create %s method for resource %s.", rest_method, resource_id ) raise try: self.apig_client.put_integration( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, type="AWS", integrationHttpMethod=service_method, credentials=role_arn, requestTemplates={"application/json": json.dumps(mapping_template)}, uri=service_uri, passthroughBehavior="WHEN_NO_TEMPLATES", ) self.apig_client.put_integration_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseTemplates={"application/json": ""}, ) logger.info( "Created integration for resource %s to service URI %s.", resource_id, service_uri, ) except ClientError: logger.exception( "Couldn't create integration for resource %s to service URI %s.", resource_id, service_uri, ) raise
  • Pour API plus de détails, reportez-vous PutIntegrationà la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserPutIntegrationResponse.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def add_integration_method( self, resource_id, rest_method, service_endpoint_prefix, service_action, service_method, role_arn, mapping_template, ): """ Adds an integration method to a REST API. An integration method is a REST resource, such as '/users', and an HTTP verb, such as GET. The integration method is backed by an AWS service, such as Amazon DynamoDB. :param resource_id: The ID of the REST resource. :param rest_method: The HTTP verb used with the REST resource. :param service_endpoint_prefix: The service endpoint that is integrated with this method, such as 'dynamodb'. :param service_action: The action that is called on the service, such as 'GetItem'. :param service_method: The HTTP method of the service request, such as POST. :param role_arn: The Amazon Resource Name (ARN) of a role that grants API Gateway permission to use the specified action with the service. :param mapping_template: A mapping template that is used to translate REST elements, such as query parameters, to the request body format required by the service. """ service_uri = ( f"arn:aws:apigateway:{self.apig_client.meta.region_name}" f":{service_endpoint_prefix}:action/{service_action}" ) try: self.apig_client.put_method( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, authorizationType="NONE", ) self.apig_client.put_method_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseModels={"application/json": "Empty"}, ) logger.info("Created %s method for resource %s.", rest_method, resource_id) except ClientError: logger.exception( "Couldn't create %s method for resource %s.", rest_method, resource_id ) raise try: self.apig_client.put_integration( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, type="AWS", integrationHttpMethod=service_method, credentials=role_arn, requestTemplates={"application/json": json.dumps(mapping_template)}, uri=service_uri, passthroughBehavior="WHEN_NO_TEMPLATES", ) self.apig_client.put_integration_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseTemplates={"application/json": ""}, ) logger.info( "Created integration for resource %s to service URI %s.", resource_id, service_uri, ) except ClientError: logger.exception( "Couldn't create integration for resource %s to service URI %s.", resource_id, service_uri, ) raise
  • Pour API plus de détails, reportez-vous PutIntegrationResponseà la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserPutMethod.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def add_integration_method( self, resource_id, rest_method, service_endpoint_prefix, service_action, service_method, role_arn, mapping_template, ): """ Adds an integration method to a REST API. An integration method is a REST resource, such as '/users', and an HTTP verb, such as GET. The integration method is backed by an AWS service, such as Amazon DynamoDB. :param resource_id: The ID of the REST resource. :param rest_method: The HTTP verb used with the REST resource. :param service_endpoint_prefix: The service endpoint that is integrated with this method, such as 'dynamodb'. :param service_action: The action that is called on the service, such as 'GetItem'. :param service_method: The HTTP method of the service request, such as POST. :param role_arn: The Amazon Resource Name (ARN) of a role that grants API Gateway permission to use the specified action with the service. :param mapping_template: A mapping template that is used to translate REST elements, such as query parameters, to the request body format required by the service. """ service_uri = ( f"arn:aws:apigateway:{self.apig_client.meta.region_name}" f":{service_endpoint_prefix}:action/{service_action}" ) try: self.apig_client.put_method( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, authorizationType="NONE", ) self.apig_client.put_method_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseModels={"application/json": "Empty"}, ) logger.info("Created %s method for resource %s.", rest_method, resource_id) except ClientError: logger.exception( "Couldn't create %s method for resource %s.", rest_method, resource_id ) raise try: self.apig_client.put_integration( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, type="AWS", integrationHttpMethod=service_method, credentials=role_arn, requestTemplates={"application/json": json.dumps(mapping_template)}, uri=service_uri, passthroughBehavior="WHEN_NO_TEMPLATES", ) self.apig_client.put_integration_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseTemplates={"application/json": ""}, ) logger.info( "Created integration for resource %s to service URI %s.", resource_id, service_uri, ) except ClientError: logger.exception( "Couldn't create integration for resource %s to service URI %s.", resource_id, service_uri, ) raise
  • Pour API plus de détails, reportez-vous PutMethodà la section AWS SDKrelative à la référence Python (Boto3). API

L'exemple de code suivant montre comment utiliserPutMethodResponse.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def add_integration_method( self, resource_id, rest_method, service_endpoint_prefix, service_action, service_method, role_arn, mapping_template, ): """ Adds an integration method to a REST API. An integration method is a REST resource, such as '/users', and an HTTP verb, such as GET. The integration method is backed by an AWS service, such as Amazon DynamoDB. :param resource_id: The ID of the REST resource. :param rest_method: The HTTP verb used with the REST resource. :param service_endpoint_prefix: The service endpoint that is integrated with this method, such as 'dynamodb'. :param service_action: The action that is called on the service, such as 'GetItem'. :param service_method: The HTTP method of the service request, such as POST. :param role_arn: The Amazon Resource Name (ARN) of a role that grants API Gateway permission to use the specified action with the service. :param mapping_template: A mapping template that is used to translate REST elements, such as query parameters, to the request body format required by the service. """ service_uri = ( f"arn:aws:apigateway:{self.apig_client.meta.region_name}" f":{service_endpoint_prefix}:action/{service_action}" ) try: self.apig_client.put_method( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, authorizationType="NONE", ) self.apig_client.put_method_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseModels={"application/json": "Empty"}, ) logger.info("Created %s method for resource %s.", rest_method, resource_id) except ClientError: logger.exception( "Couldn't create %s method for resource %s.", rest_method, resource_id ) raise try: self.apig_client.put_integration( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, type="AWS", integrationHttpMethod=service_method, credentials=role_arn, requestTemplates={"application/json": json.dumps(mapping_template)}, uri=service_uri, passthroughBehavior="WHEN_NO_TEMPLATES", ) self.apig_client.put_integration_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseTemplates={"application/json": ""}, ) logger.info( "Created integration for resource %s to service URI %s.", resource_id, service_uri, ) except ClientError: logger.exception( "Couldn't create integration for resource %s to service URI %s.", resource_id, service_uri, ) raise
  • Pour API plus de détails, reportez-vous PutMethodResponseà la section AWS SDKrelative à la référence Python (Boto3). API

Scénarios

L'exemple de code suivant montre comment créer un système REST API qui simule un système permettant de suivre les cas quotidiens de COVID -19 aux États-Unis, à l'aide de données fictives.

SDKpour Python (Boto3)

Montre comment utiliser AWS Chalice avec le AWS SDK for Python (Boto3) pour créer un serveur sans serveur REST API utilisant Amazon API Gateway et Amazon DynamoDB. AWS Lambda Il REST API simule un système qui suit les cas quotidiens de COVID -19 aux États-Unis, à l'aide de données fictives. Découvrez comment :

  • Utilisez AWS Chalice pour définir des routes dans les fonctions Lambda appelées pour gérer les REST demandes qui passent par Gateway. API

  • Utilisez les fonctions Lambda pour récupérer et stocker des données dans une table DynamoDB afin de répondre aux demandes. REST

  • Définissez la structure des tables et les ressources des rôles de sécurité dans un AWS CloudFormation modèle.

  • Utilisez AWS Chalice CloudFormation pour empaqueter et déployer toutes les ressources nécessaires.

  • CloudFormation À utiliser pour nettoyer toutes les ressources créées.

Pour obtenir le code source complet et les instructions de configuration et d'exécution, consultez l'exemple complet sur GitHub.

Les services utilisés dans cet exemple
  • APIPasserelle

  • AWS CloudFormation

  • DynamoDB

  • Lambda

L'exemple de code suivant montre comment créer une bibliothèque de prêt dans laquelle les clients peuvent emprunter et retourner des livres à l'aide d'une base de données REST API soutenue par Amazon Aurora.

SDKpour Python (Boto3)

Montre comment utiliser le AWS SDK for Python (Boto3) avec Amazon Relational Database Service API (RDSAmazon) et AWS Chalice pour créer REST API une base de données basée sur une base de données Amazon Aurora. Le service Web est entièrement sans serveur et représente une bibliothèque de prêt simple où les clients peuvent emprunter et retourner des livres. Découvrez comment :

  • Créer et gérer un cluster de bases de données Aurora sans serveur.

  • AWS Secrets Manager À utiliser pour gérer les informations d'identification de base de données.

  • Implémentez une couche de stockage de données qui utilise Amazon RDS pour déplacer les données dans et hors de la base de données.

  • Utilisez AWS Chalice pour déployer un serveur sans serveur REST API sur Amazon API Gateway et. AWS Lambda

  • Utiliser le package Requests (Requêtes) pour envoyer des requêtes au service web.

Pour obtenir le code source complet et les instructions de configuration et d'exécution, consultez l'exemple complet sur GitHub.

Les services utilisés dans cet exemple
  • APIPasserelle

  • Aurora

  • Lambda

  • Secrets Manager

L'exemple de code suivant montre comment créer une application de chat desservie par un websocket API basé sur Amazon API Gateway.

SDKpour Python (Boto3)

Montre comment utiliser Amazon API Gateway V2 pour créer un websocket API qui s'intègre à Amazon AWS Lambda DynamoDB. AWS SDK for Python (Boto3)

  • Créez un websocket API servi par API Gateway.

  • Définissez un gestionnaire Lambda qui stocke les connexions dans DynamoDB et publie des messages pour d’autres participants au chat.

  • Connectez-vous à l’application de chat Websocket et envoyez des messages avec le package Websockets.

Pour obtenir le code source complet et les instructions de configuration et d'exécution, consultez l'exemple complet sur GitHub.

Les services utilisés dans cet exemple
  • APIPasserelle

  • DynamoDB

  • Lambda

L’exemple de code suivant illustre comment :

  • Créez un REST API serveur géré par API Gateway.

  • Ajoutez des ressources au REST API pour représenter un profil utilisateur.

  • Ajoutez des méthodes d'intégration afin d'RESTAPIutiliser une table DynamoDB pour stocker les données de profil utilisateur.

  • Envoyez HTTP des demandes au REST API pour ajouter et récupérer des profils utilisateur.

SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Créez une classe qui englobe les opérations de API passerelle.

import argparse import json import logging from pprint import pprint import boto3 from botocore.exceptions import ClientError import requests logger = logging.getLogger(__name__) class ApiGatewayToService: """ Encapsulates Amazon API Gateway functions that are used to create a REST API that integrates with another AWS service. """ def __init__(self, apig_client): """ :param apig_client: A Boto3 API Gateway client. """ self.apig_client = apig_client self.api_id = None self.root_id = None self.stage = None def create_rest_api(self, api_name): """ Creates a REST API on API Gateway. The default API has only a root resource and no HTTP methods. :param api_name: The name of the API. This descriptive name is not used in the API path. :return: The ID of the newly created API. """ try: result = self.apig_client.create_rest_api(name=api_name) self.api_id = result["id"] logger.info("Created REST API %s with ID %s.", api_name, self.api_id) except ClientError: logger.exception("Couldn't create REST API %s.", api_name) raise try: result = self.apig_client.get_resources(restApiId=self.api_id) self.root_id = next( item for item in result["items"] if item["path"] == "/" )["id"] except ClientError: logger.exception("Couldn't get resources for API %s.", self.api_id) raise except StopIteration as err: logger.exception("No root resource found in API %s.", self.api_id) raise ValueError from err return self.api_id def add_rest_resource(self, parent_id, resource_path): """ Adds a resource to a REST API. :param parent_id: The ID of the parent resource. :param resource_path: The path of the new resource, relative to the parent. :return: The ID of the new resource. """ try: result = self.apig_client.create_resource( restApiId=self.api_id, parentId=parent_id, pathPart=resource_path ) resource_id = result["id"] logger.info("Created resource %s.", resource_path) except ClientError: logger.exception("Couldn't create resource %s.", resource_path) raise else: return resource_id def add_integration_method( self, resource_id, rest_method, service_endpoint_prefix, service_action, service_method, role_arn, mapping_template, ): """ Adds an integration method to a REST API. An integration method is a REST resource, such as '/users', and an HTTP verb, such as GET. The integration method is backed by an AWS service, such as Amazon DynamoDB. :param resource_id: The ID of the REST resource. :param rest_method: The HTTP verb used with the REST resource. :param service_endpoint_prefix: The service endpoint that is integrated with this method, such as 'dynamodb'. :param service_action: The action that is called on the service, such as 'GetItem'. :param service_method: The HTTP method of the service request, such as POST. :param role_arn: The Amazon Resource Name (ARN) of a role that grants API Gateway permission to use the specified action with the service. :param mapping_template: A mapping template that is used to translate REST elements, such as query parameters, to the request body format required by the service. """ service_uri = ( f"arn:aws:apigateway:{self.apig_client.meta.region_name}" f":{service_endpoint_prefix}:action/{service_action}" ) try: self.apig_client.put_method( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, authorizationType="NONE", ) self.apig_client.put_method_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseModels={"application/json": "Empty"}, ) logger.info("Created %s method for resource %s.", rest_method, resource_id) except ClientError: logger.exception( "Couldn't create %s method for resource %s.", rest_method, resource_id ) raise try: self.apig_client.put_integration( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, type="AWS", integrationHttpMethod=service_method, credentials=role_arn, requestTemplates={"application/json": json.dumps(mapping_template)}, uri=service_uri, passthroughBehavior="WHEN_NO_TEMPLATES", ) self.apig_client.put_integration_response( restApiId=self.api_id, resourceId=resource_id, httpMethod=rest_method, statusCode="200", responseTemplates={"application/json": ""}, ) logger.info( "Created integration for resource %s to service URI %s.", resource_id, service_uri, ) except ClientError: logger.exception( "Couldn't create integration for resource %s to service URI %s.", resource_id, service_uri, ) raise def deploy_api(self, stage_name): """ Deploys a REST API. After a REST API is deployed, it can be called from any REST client, such as the Python Requests package or Postman. :param stage_name: The stage of the API to deploy, such as 'test'. :return: The base URL of the deployed REST API. """ try: self.apig_client.create_deployment( restApiId=self.api_id, stageName=stage_name ) self.stage = stage_name logger.info("Deployed stage %s.", stage_name) except ClientError: logger.exception("Couldn't deploy stage %s.", stage_name) raise else: return self.api_url() def api_url(self, resource=None): """ Builds the REST API URL from its parts. :param resource: The resource path to append to the base URL. :return: The REST URL to the specified resource. """ url = ( f"https://{self.api_id}.execute-api.{self.apig_client.meta.region_name}" f".amazonaws.com/{self.stage}" ) if resource is not None: url = f"{url}/{resource}" return url

Déployez un REST API et appelez-le avec le package Requests.

def usage_demo(table_name, role_name, rest_api_name): """ Demonstrates how to used API Gateway to create and deploy a REST API, and how to use the Requests package to call it. :param table_name: The name of the demo DynamoDB table. :param role_name: The name of the demo role that grants API Gateway permission to call DynamoDB. :param rest_api_name: The name of the demo REST API created by the demo. """ gateway = ApiGatewayToService(boto3.client("apigateway")) role = boto3.resource("iam").Role(role_name) print("Creating REST API in API Gateway.") gateway.create_rest_api(rest_api_name) print("Adding resources to the REST API.") profiles_id = gateway.add_rest_resource(gateway.root_id, "profiles") username_id = gateway.add_rest_resource(profiles_id, "{username}") # The DynamoDB service requires that all integration requests use POST. print("Adding integration methods to read and write profiles in Amazon DynamoDB.") gateway.add_integration_method( profiles_id, "GET", "dynamodb", "Scan", "POST", role.arn, {"TableName": table_name}, ) gateway.add_integration_method( profiles_id, "POST", "dynamodb", "PutItem", "POST", role.arn, { "TableName": table_name, "Item": { "username": {"S": "$input.path('$.username')"}, "name": {"S": "$input.path('$.name')"}, "title": {"S": "$input.path('$.title')"}, }, }, ) gateway.add_integration_method( username_id, "GET", "dynamodb", "GetItem", "POST", role.arn, { "TableName": table_name, "Key": {"username": {"S": "$method.request.path.username"}}, }, ) stage = "test" print(f"Deploying the {stage} stage.") gateway.deploy_api(stage) profiles_url = gateway.api_url("profiles") print( f"Using the Requests package to post some people to the profiles REST API at " f"{profiles_url}." ) requests.post( profiles_url, json={"username": "will", "name": "William Shakespeare", "title": "playwright"}, ) requests.post( profiles_url, json={ "username": "ludwig", "name": "Ludwig van Beethoven", "title": "composer", }, ) requests.post( profiles_url, json={"username": "jane", "name": "Jane Austen", "title": "author"}, ) print("Getting the list of profiles from the REST API.") profiles = requests.get(profiles_url).json() pprint(profiles) print(f"Getting just the profile for username 'jane' (URL: {profiles_url}/jane).") jane = requests.get(f"{profiles_url}/jane").json() pprint(jane)

L'exemple de code suivant montre comment créer une AWS Lambda fonction invoquée par Amazon API Gateway.

SDKpour Python (Boto3)

Cet exemple montre comment créer et utiliser un Amazon API Gateway REST API qui cible une AWS Lambda fonction. Le gestionnaire Lambda montre comment effectuer un routage en fonction de HTTP méthodes, comment obtenir des données à partir de la chaîne de requête, de l'en-tête et du corps de la requête, et comment renvoyer une réponse. JSON

  • Déploier une fonction Lambda.

  • Créez une API passerelle RESTAPI.

  • Créez une REST ressource qui cible la fonction Lambda.

  • Accordez l'autorisation de laisser API Gateway invoquer la fonction Lambda.

  • Utilisez le package Requests pour envoyer des demandes au RESTAPI.

  • Nettoyer toutes les ressources créées lors de la démonstration.

Il est préférable de visionner cet exemple sur GitHub. Pour obtenir le code source complet et les instructions de configuration et d'exécution, consultez l'exemple complet sur GitHub.

Les services utilisés dans cet exemple
  • APIPasserelle

  • Lambda