API-Gateway-Beispiele unter Verwendung von SDK für Python (Boto3) - AWS-SDK-Codebeispiele

Weitere AWS-SDK-Beispiele sind im GitHub-Repository Beispiele für AWS Doc SDKs verfügbar.

API-Gateway-Beispiele unter Verwendung von SDK für Python (Boto3)

Die folgenden Codebeispiele zeigen, wie Sie Aktionen durchführen und gängige Szenarien implementieren, indem Sie AWS SDK für Python (Boto3) mit API Gateway nutzen.

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

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

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

Aktionen

Die folgenden Codebeispiele zeigen, wie CreateDeployment verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter CreateDeployment in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie CreateResource verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter CreateResource in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie CreateRestApi verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter CreateRestApi in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie DeleteRestApi verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter DeleteRestApi in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie GetResources verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter GetResources in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie GetRestApis verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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"]
  • Weitere API-Informationen finden Sie unter GetRestApis in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie PutIntegration verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter PutIntegration in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie PutIntegrationResponse verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter PutIntegrationResponse in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie PutMethod verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter PutMethod in der API-Referenz zum AWS-SDK für Python (Boto3).

Die folgenden Codebeispiele zeigen, wie PutMethodResponse verwendet wird.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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
  • Weitere API-Informationen finden Sie unter PutMethodResponse in der API-Referenz zum AWS-SDK für Python (Boto3).

Szenarien

Das folgende Codebeispiel zeigt, wie eine REST-API erstellt wird, die ein System zur Verfolgung der täglichen COVID-19-Fälle in den Vereinigten Staaten unter Verwendung fiktiver Daten simuliert.

SDK für Python (Boto3)

Zeigt die Verwendung von AWS Chalice mit AWS SDK für Python (Boto3), um eine Serverless-REST-API zu erstellen, die Amazon API Gateway, AWS Lambda und Amazon DynamoDB verwendet. Die REST-API simuliert ein System, das die täglichen COVID-19-Fälle in den Vereinigten Staaten unter Verwendung fiktiver Daten simuliert. Lernen Sie Folgendes:

  • Verwenden von AWS Chalice zum Definieren von Routen in Lambda-Funktionen, die zur Bearbeitung von über API Gateway erfolgenden REST-Anfragen aufgerufen werden.

  • Verwenden Sie Lambda-Funktionen zum Abrufen und Speichern von Daten in einer DynamoDB-Tabelle, um REST-Anforderungen zu bearbeiten.

  • Definieren Sie Tabellenstruktur und Sicherheitsrollenressourcen in einer AWS CloudFormation-Vorlage.

  • Verwenden Sie AWS Chalice und CloudFormation zum Verpacken und Bereitstellen aller notwendigen Ressourcen.

  • Verwenden Sie CloudFormation, um alle erstellten Ressourcen zu bereinigen.

Den kompletten Quellcode und Anweisungen zum Einrichten und Ausführen finden Sie im vollständigen Beispiel unter GitHub.

In diesem Beispiel verwendete Services
  • API Gateway

  • CloudFormation

  • DynamoDB

  • Lambda

Im folgenden Codebeispiel wird veranschaulicht, wie man eine Leihbibliothek erstellt, in der Kunden Bücher mithilfe einer REST-API ausleihen und zurückgeben können, die von einer Amazon-Aurora-Datenbank unterstützt wird.

SDK für Python (Boto3)

Veranschaulicht, wie man AWS SDK für Python (Boto3) mit der API von Amazon Relational Database Service (Amazon RDS) und AWS Chalice verwendet, um eine REST-API zu erstellen, die von einer Amazon-Aurora-Datenbank unterstützt 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.

  • Verwenden Sie AWS Secrets Manager, um Datenbankanmeldeinformationen zu verwalten.

  • Implementieren Sie einen Datenspeicher-Layer, der Amazon RDS verwendet, um Daten in die und aus der Datenbank zu verschieben.

  • Verwenden Sie AWS Chalice zur Bereitstellung einer Serverless-REST-API auf Amazon API Gateway und AWS Lambda.

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

Den kompletten Quellcode und Anweisungen zum Einrichten und Ausführen finden Sie im vollständigen Beispiel unter GitHub.

In diesem Beispiel verwendete Services
  • API Gateway

  • Aurora

  • Lambda

  • Secrets Manager

Das folgende Codebeispiel zeigt, wie eine Chat-Anwendung erstellt wird, die von einer auf Amazon API Gateway basierenden Websocket-API bereitgestellt wird.

SDK für Python (Boto3)

Veranschaulicht die Verwendung von AWS SDK für Python (Boto3) mit Amazon API Gateway V2, um eine Websocket-API zu erstellen, die mit AWS Lambda und Amazon DynamoDB integriert werden kann.

  • Erstellen Sie eine WebSocket-API, die von API Gateway bereitgestellt wird.

  • 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 kompletten Quellcode und Anweisungen zum Einrichten und Ausführen finden Sie im vollständigen Beispiel unter GitHub.

In diesem Beispiel verwendete Services
  • API Gateway

  • DynamoDB

  • Lambda

Wie das aussehen kann, sehen Sie am nachfolgenden Beispielcode:

  • Erstellen Sie eine REST-API, die von API Gateway bereitgestellt wird.

  • Fügen Sie der REST-API Ressourcen hinzu, um ein Benutzerprofil darzustellen.

  • Fügen Sie Integrationsmethoden hinzu, damit die REST-API eine DynamoDB-Tabelle verwendet, um Benutzerdatenprofile zu speichern.

  • Senden Sie HTTP-Anfragen an die REST-API, um Benutzerprofile hinzuzufügen und abzurufen.

SDK für Python (Boto3)
Anmerkung

Auf GitHub finden Sie noch mehr. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Codebeispiel-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 eine REST-API bereit und rufen Sie sie 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)

Die folgenden Codebeispielen zeigen, wie eine AWS Lambda-Funktion erstellt wird, die von Amazon API Gateway aufgerufen wird.

SDK für Python (Boto3)

Dieses Beispiel veranschaulicht, wie eine REST-API für Amazon API Gateway erstellt und verwendet wird, die auf eine AWS Lambda-Funktion verweist. Der Lambda-Handler veranschaulicht, wie basierend auf HTTP-Methoden weitergeleitet wird, wie Daten aus der Abfragezeichenfolge, dem Header und dem Text abgerufen werden und wie eine JSON-Antwort zurückgegeben wird.

  • Stellen Sie eine Lambda-Funktion bereit.

  • REST-API für API Gateway erstellen

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

  • Erteilen Sie API Gateway die Berechtigung, die Lambda-Funktion aufzurufen.

  • Verwenden Sie das Anforderungspaket, um Anforderungen an die REST-API zu senden.

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

Dieses Beispiel wird am besten auf GitHub angesehen. Den kompletten Quellcode und Anweisungen zum Einrichten und Ausführen finden Sie im vollständigen Beispiel unter GitHub.

In diesem Beispiel verwendete Services
  • API Gateway

  • DynamoDB

  • Lambda

  • Amazon SNS