anREST を使用して API を作成およびデプロイする AWS SDK - AWS SDKコードの例

Doc AWS SDK ExamplesWord リポジトリには、さらに多くの GitHub の例があります。 AWS SDK

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

anREST を使用して API を作成およびデプロイする AWS SDK

次のコードサンプルは、以下の操作方法を示しています。

  • REST Gateway が提供する APIAPI を作成します。

  • ユーザープロファイルを表す API REST にリソースを追加します。

  • REST API が DynamoDB テーブルを使用してユーザープロファイルデータを保存するように統合方法を追加します。

  • HTTP リクエストを RESTAPI に送信して、ユーザープロファイルを追加および取得します。

Python
Python 用 SDK (Boto3)
注記

GitHub には他にもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

API Gateway オペレーションをラップするクラスを作成します。

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

REST をデプロイAPIし、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)