AWS API网关是一个可扩展的云服务,用于构建、部署和管理RESTful API和WebSocket应用程序。AWS API网关支持REST API和HTTP API两种类型的API。但许多人不知道这两种API的区别以及何时使用它们。
REST API是在Web上有广泛应用的一种API类型。它基于HTTP协议和REST原则,具有灵活性和可扩展性,支持多种协议(如JSON和XML)。它使用HTTP方法(如GET、POST、PUT和DELETE)和URL路由来处理客户端请求。以下是使用Python和Boto3 SDK创建AWS API Gateway REST API的示例代码:
import boto3
import json
client = boto3.client('apigateway')
api_name = 'my-api'
api_description = 'My API description'
rest_api = client.create_rest_api(name=api_name, description=api_description)
resources = [
('/hello', 'GET', 'HelloWorldFunction'),
('/world', 'GET', 'WorldFunction')
]
for path, method, function_name in resources:
resource = client.create_resource(restApiId=rest_api['id'], pathPart=path[1:])
response = client.put_method(
restApiId=rest_api['id'],
resourceId=resource['id'],
httpMethod=method,
authorizationType='NONE'
)
uri = 'arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{account_id}:function:{name}/invocations'.format(
region=client.meta.region_name,
account_id=client.meta.aws_account_id,
name=function_name,
)
client.put_integration(
restApiId=rest_api['id'],
resourceId=resource['id'],
httpMethod=method,
type='AWS',
integrationHttpMethod='POST',
uri=uri,
)
client.create_deployment(
restApiId=rest_api['id'],
stageName='prod',
)
print("API Gateway REST API created with ID:",