APIGateway-Beispiele SDK für die Verwendung von Python (Boto3) - AWS SDKCode-Beispiele

Weitere AWS SDK Beispiele sind im Repo AWS Doc SDK Examples GitHub verfügbar.

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.

APIGateway-Beispiele SDK für die Verwendung von Python (Boto3)

Die folgenden Codebeispiele zeigen Ihnen, wie Sie mithilfe von AWS SDK for Python (Boto3) with API Gateway Aktionen ausführen und allgemeine Szenarien implementieren.

Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Aktionen zeigen Ihnen zwar, wie Sie einzelne Servicefunktionen aufrufen, aber Sie können Aktionen im Kontext der zugehörigen Szenarien sehen.

Szenarien sind Codebeispiele, die Ihnen zeigen, wie Sie bestimmte Aufgaben ausführen, indem Sie mehrere Funktionen innerhalb eines Dienstes oder in Kombination mit anderen aufrufen AWS-Services.

Jedes Beispiel enthält einen Link zum vollständigen Quellcode, in dem Sie Anweisungen zum Einrichten und Ausführen des Codes im Kontext finden.

Aktionen

Das folgende Codebeispiel zeigt die VerwendungCreateDeployment.

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter CreateDeploymentPython (Boto3) API -Referenz.AWS SDK

Das folgende Codebeispiel zeigt die Verwendung. CreateResource

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter CreateResourcePython (Boto3) API -Referenz.AWS SDK

Das folgende Codebeispiel zeigt die Verwendung. CreateRestApi

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter CreateRestApiPython (Boto3) API -Referenz.AWS SDK

Das folgende Codebeispiel zeigt die Verwendung. DeleteRestApi

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter DeleteRestApiPython (Boto3) API -Referenz.AWS SDK

Das folgende Codebeispiel zeigt die Verwendung. GetResources

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter GetResourcesPython (Boto3) API -Referenz.AWS SDK

Das folgende Codebeispiel zeigt die Verwendung. GetRestApis

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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"]
  • APIEinzelheiten finden Sie unter GetRestApisPython (Boto3) API -Referenz.AWS SDK

Das folgende Codebeispiel zeigt die Verwendung. PutIntegration

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter PutIntegrationPython (Boto3) API -Referenz.AWS SDK

Das folgende Codebeispiel zeigt die Verwendung. PutIntegrationResponse

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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

Das folgende Codebeispiel zeigt die Verwendung. PutMethod

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter PutMethodPython (Boto3) API -Referenz.AWS SDK

Das folgende Codebeispiel zeigt die Verwendung. PutMethodResponse

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter PutMethodResponsePython (Boto3) API -Referenz.AWS SDK

Szenarien

Das folgende Codebeispiel zeigt, wie Sie einen Code erstellen RESTAPI, der anhand fiktiver Daten ein System zur Erfassung täglicher Fälle von COVID -19 in den USA simuliert.

SDKfür Python (Boto3)

Zeigt, wie AWS Chalice mit dem verwendet wird AWS SDK for Python (Boto3) , um ein serverloses System zu erstellen RESTAPI, das Amazon API Gateway und Amazon AWS Lambda DynamoDB verwendet. Das REST API simuliert ein System, das anhand fiktiver Daten tägliche Fälle von COVID -19 in den Vereinigten Staaten verfolgt. Lernen Sie Folgendes:

  • Verwenden Sie AWS Chalice, um Routen in Lambda-Funktionen zu definieren, die aufgerufen werden, um REST Anfragen zu bearbeiten, die über API Gateway eingehen.

  • Verwenden Sie Lambda-Funktionen, um Daten abzurufen und in einer DynamoDB-Tabelle zu speichern, um Anfragen zu bearbeiten. REST

  • Definieren Sie die Tabellenstruktur und die Ressourcen für Sicherheitsrollen in einer Vorlage. AWS CloudFormation

  • Verwenden Sie AWS Chalice und CloudFormation , um alle erforderlichen Ressourcen zu verpacken und bereitzustellen.

  • Wird verwendet CloudFormation , um alle erstellten Ressourcen zu bereinigen.

Den vollständigen Quellcode und Anweisungen zur Einrichtung und Ausführung finden Sie im vollständigen Beispiel unter GitHub.

In diesem Beispiel verwendete Dienste
  • APIGateway

  • AWS CloudFormation

  • DynamoDB

  • Lambda

Das folgende Codebeispiel zeigt, wie eine Leihbibliothek erstellt wird, in der Benutzer Bücher ausleihen und zurückgeben können, indem sie eine von Amazon Aurora REST API gestützte Datenbank verwenden.

SDKfür Python (Boto3)

Zeigt, wie AWS SDK for Python (Boto3) mit dem Amazon Relational Database Service (AmazonRDS) API und AWS Chalice eine von Amazon Aurora REST API unterstützte Datenbank erstellt wird. Der Webservice ist vollständig Serverless und stellt eine einfache Leihbibliothek dar, in der die Kunden Bücher ausleihen und zurückgeben können. Lernen Sie Folgendes:

  • Erstellen und verwalten Sie einen Serverless-Aurora-Datenbank-Cluster.

  • Wird AWS Secrets Manager zur Verwaltung von Datenbankanmeldedaten verwendet.

  • Implementieren Sie eine Datenspeicherebene, die Amazon verwendetRDS, um Daten in die Datenbank und aus der Datenbank zu verschieben.

  • Verwenden Sie AWS Chalice, um eine serverlose Lösung REST API für Amazon API Gateway bereitzustellen und. AWS Lambda

  • Verwenden Sie das Anforderungspaket, um Anfragen an den Webservice zu senden.

Den vollständigen Quellcode und Anweisungen zur Einrichtung und Ausführung finden Sie im vollständigen Beispiel unter. GitHub

In diesem Beispiel verwendete Dienste
  • APIGateway

  • Aurora

  • Lambda

  • Secrets Manager

Das folgende Codebeispiel zeigt, wie Sie eine Chat-Anwendung erstellen, die von einem auf Amazon API Gateway API erstellten Websocket bedient wird.

SDKfür Python (Boto3)

Zeigt, wie Sie AWS SDK for Python (Boto3) mit Amazon API Gateway V2 einen Websocket erstellen, der API sich in Amazon DynamoDB integrieren AWS Lambda lässt.

  • Erstellen Sie einen WebsocketAPI, der von Gateway bereitgestellt wird. API

  • Definieren Sie einen Lambda-Handler, der Verbindungen in DynamoDB speichert und Nachrichten an andere Chat-Teilnehmer sendet.

  • Stellen Sie eine Verbindung zur Websocket-Chat-Anwendung her und senden Sie Nachrichten mit dem Websockets-Paket.

Den vollständigen Quellcode und Anweisungen zur Einrichtung und Ausführung finden Sie im vollständigen Beispiel unter GitHub.

In diesem Beispiel verwendete Dienste
  • APIGateway

  • DynamoDB

  • Lambda

Wie das aussehen kann, sehen Sie am nachfolgenden Beispielcode:

  • Erstellen Sie ein von API Gateway REST API serviertes.

  • Fügen Sie Ressourcen REST API zur Darstellung eines Benutzerprofils hinzu.

  • Fügen Sie Integrationsmethoden hinzu, sodass die eine DynamoDB-Tabelle zum Speichern von Benutzerprofildaten REST API verwendet.

  • Senden Sie HTTP Anfragen an die REST API zum Hinzufügen und Abrufen von Benutzerprofilen.

SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie eine Klasse, die API Gateway-Operationen umschließt.

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

Stellen Sie a bereit REST API und rufen Sie es mit dem Requests-Paket auf.

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)

Das folgende Codebeispiel zeigt, wie eine von Amazon API Gateway aufgerufene AWS Lambda Funktion erstellt wird.

SDKfür Python (Boto3)

Dieses Beispiel zeigt, wie Sie ein Amazon API Gateway erstellen und verwenden RESTAPI, das auf eine AWS Lambda Funktion abzielt. Der Lambda-Handler demonstriert, wie das Routing auf der Grundlage von HTTP Methoden erfolgt, wie Daten aus der Abfragezeichenfolge, dem Header und dem Hauptteil abgerufen werden und wie eine JSON Antwort zurückgegeben wird.

  • Stellen Sie eine Lambda-Funktion bereit.

  • Erstellen Sie ein API Gateway RESTAPI.

  • Erstellen Sie eine REST Ressource, die auf die Lambda-Funktion abzielt.

  • Erteilen Sie die Erlaubnis, API Gateway die Lambda-Funktion aufrufen zu lassen.

  • Verwenden Sie das Requests-Paket, um Anfragen an die zu senden. REST API

  • Bereinigen Sie alle Ressourcen, die während der Demo erstellt wurden.

Dieses Beispiel lässt sich am besten auf ansehen GitHub. Den vollständigen Quellcode und Anweisungen zur Einrichtung und Ausführung finden Sie im vollständigen Beispiel unter GitHub.

In diesem Beispiel verwendete Dienste
  • APIGateway

  • Lambda