FastAPI
FastAPI 是一个用于在 Python 中构建 API 的框架。
FastAPI 生成器创建一个新的 FastAPI,并配置 AWS CDK 或 Terraform 基础设施。生成的后端通过 AWS API Gateway API 公开。它设置了 AWS Lambda Powertools 以实现可观测性,包括结构化日志记录和 CloudWatch 指标。
后端使用 AWS Lambda 进行无服务器部署,并且还设置了 AWS X-Ray 追踪。
您的 API 作为长期运行的 uvicorn 服务器在 Amazon ECS 上的容器中运行,位于 API Gateway HTTP API 后面,而不是在 Lambda 函数中。请参阅在 Amazon ECS 上运行了解这会改变什么,包括为什么 X-Ray 追踪在那里不产生追踪。
生成 FastAPI
Section titled “生成 FastAPI”您可以通过两种方式生成新的 FastAPI:
运行此生成器@aws/nx-plugin:py#api
pnpm nx g @aws/nx-plugin:py#api --framework=fastapi yarn nx g @aws/nx-plugin:py#api --framework=fastapi npx nx g @aws/nx-plugin:py#api --framework=fastapi bunx nx g @aws/nx-plugin:py#api --framework=fastapi- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - py#api - 填写必需参数
- framework: fastapi
- 点击
Generate
构建你的命令11
必需
name必需string要生成的 API 项目名称
frameworkenum默认值:fastapi要使用的API框架。
fastapiintegrationPatternenumAPI Gateway 集成如何为 API 生成。在 isolated 和 shared 之间选择。默认为 isolated。http-ecs 基础设施始终使用 shared,因为一个容器服务响应所有操作,因此 isolated 在此情况下会被忽略并显示警告。
isolatedsharedauthenum默认值:iam用于对 API 进行身份验证的方法。可选择 iam(默认)、cognito 或 custom。
iamcognitocustomdirectorystring默认值:packages存储应用程序的目录。
iacenum默认值:inherit首选的 IaC 提供商。默认情况下,这将继承您的初始选择。
inheritcdkterraforminfraenum默认值:rest-lambda用于部署此 API 的基础设施类型。http-ecs(实验性)将 API 作为容器服务运行在 Amazon ECS 上,位于 API Gateway HTTP API 后面,并且需要 CDK IaC 提供程序。它始终使用 integrationPattern shared,因为一个容器服务响应所有操作。
rest-lambdahttp-lambdahttp-ecsnonesubDirectorystring项目所在的子目录。默认情况下为项目名称。
moduleNamestringPython 模块名称
architectureenum容器镜像构建所针对的 CPU 架构以及其 ECS 任务运行的架构。适用于 http-ecs 基础设施。ARM64 运行在 AWS Graviton 上,在 AWS Fargate 上每个任务的成本更低。默认情况下,这是您运行生成器的机器的架构,重新运行时会保持已生成的架构。
ARM64X86_64preferInstallDependenciesboolean默认值:true是否在生成器运行后优先安装依赖项。设置为 false 可在批量运行多个生成器时延迟安装(如果后续生成器需要计算 Nx 项目图,仍会运行安装);在最后统一安装一次。
生成器将在 <directory>/<api-name> 目录中创建以下项目结构:
- project.json 项目配置和构建目标
- pyproject.toml Python 项目配置和依赖项
- run.sh Lambda Web Adapter 引导脚本,通过 uvicorn 启动 FastAPI 应用
文件夹<module_name>
- __init__.py 模块初始化
- init.py 设置 FastAPI 应用并配置 powertools 中间件
- main.py API 实现
文件夹scripts
- generate_open_api.py 从 FastAPI 应用生成 OpenAPI 架构的脚本
当 infra 设置为 http-ecs 时,API 作为自己的 HTTP 服务器运行,而不是在 Lambda Web Adapter 后面,因此不会生成 run.sh。取而代之的是,您会在模块内获得一个容器文件夹,以您的 API 命名:
文件夹<module_name>
文件夹<api_name>_container
- main.py 入口点:添加
GET /health,写出 API 收集的指标,并在HOST和PORT上启动 uvicorn。bundle、镜像和serve目标都从此文件开始 - Dockerfile 容器镜像定义
- .dockerignore 镜像构建上下文中排除的文件
- main.py 入口点:添加
您的 init.py、main.py 以及您添加到它们的操作对于每个 infra 值都是相同的。
由于此生成器根据您选择的 iac 提供基础设施即代码,它将在 packages/common 中创建一个项目,其中包含相关的 CDK 构造或 Terraform 模块。
通用基础设施即代码项目的结构如下:
文件夹packages/common/constructs
文件夹src
文件夹app/ Constructs for infrastructure specific to a project/generator
- …
文件夹core/ Generic constructs which are reused by constructs in
app- …
- index.ts Entry point exporting constructs from
app
- project.json Project build targets and configuration
文件夹packages/common/terraform
文件夹src
文件夹app/ Terraform modules for infrastructure specific to a project/generator
- …
文件夹core/ Generic modules which are reused by modules in
app- …
- project.json Project build targets and configuration
为了部署您的 API,会生成以下文件:
文件夹packages/common/constructs/src
文件夹app
文件夹apis
- <project-name>.ts CDK construct for deploying your API
文件夹core
文件夹api
- http-api.ts CDK construct for deploying an HTTP API (if you selected to deploy an HTTP API)
- rest-api.ts CDK construct for deploying a REST API (if you selected to deploy a REST API)
- utils.ts Utilities for the API constructs
文件夹packages/common/terraform/src
文件夹app
文件夹apis
文件夹<project-name>
- <project-name>.tf Module for deploying your API
文件夹core
文件夹api
文件夹http-api
- http-api.tf Module for deploying an HTTP API (if you selected to deploy an HTTP API)
文件夹rest-api
- rest-api.tf Module for deploying a REST API (if you selected to deploy a REST API)
已部署的应用程序具有以下架构:在运行您的处理程序的 Lambda 函数前面有一个 API Gateway API。
REST API 在 API Gateway 阶段前包含一个 AWS WAFv2 Web ACL,并启用了 AWS 托管的默认规则集。
HTTP API 不直接支持 WAF——如果您需要 WAF 保护,请选择 REST API,或者在 HTTP API 前面使用 CloudFront 分配。
实现您的 FastAPI
Section titled “实现您的 FastAPI”主要的 API 实现在 main.py 中。这是您定义 API 路由及其实现的地方。以下是一个示例:
from pydantic import BaseModelfrom .init import app, tracer
class Item(BaseModel): name: str
@app.get("/items/{item_id}")@tracer.capture_methoddef get_item(item_id: int) -> Item: return Item(name=f"Item {item_id}")
@app.post("/items")@tracer.capture_methoddef create_item(item: Item) -> Item: return item生成器会自动设置几个功能:
- AWS Lambda Powertools 集成以实现可观测性
- 错误处理中间件
- 请求/响应关联
- 指标收集
类型安全的流式传输也已设置,仅适用于 rest-lambda 基础设施。
应用程序在 Lambda 函数中由运行 uvicorn 的 Lambda Web Adapter 提供服务。
应用程序由容器中的 uvicorn 提供服务,没有 Lambda Web Adapter。请参阅在 Amazon ECS 上运行。
使用 AWS Lambda Powertools 实现可观测性
Section titled “使用 AWS Lambda Powertools 实现可观测性”生成器使用 AWS Lambda Powertools 配置结构化日志记录。您可以在路由处理程序中访问日志记录器:
from .init import app, logger
@app.get("/items/{item_id}")def read_item(item_id: int): logger.info("Fetching item", extra={"item_id": item_id}) return {"item_id": item_id}日志记录器会自动包含:
- 用于请求追踪的关联 ID
- 请求路径、匹配的路由和方法
AWS X-Ray 追踪会自动配置。您可以向追踪添加自定义子段:
from .init import app, tracer
@app.get("/items/{item_id}")@tracer.capture_methoddef read_item(item_id: int): # Creates a new subsegment with tracer.provider.in_subsegment("fetch-item-details"): # Your logic here return {"item_id": item_id}CloudWatch 指标会自动为每个请求收集。您可以添加自定义指标:
from .init import app, metricsfrom aws_lambda_powertools.metrics import MetricUnit
@app.get("/items/{item_id}")def read_item(item_id: int): metrics.add_metric(name="ItemViewed", unit=MetricUnit.Count, value=1) return {"item_id": item_id}默认指标包括:
- 请求计数
- 成功/失败计数
- 按路由的指标(通过
<method> <path>的route维度)
生成器包含全面的错误处理:
from fastapi import HTTPException
@app.get("/items/{item_id}")def read_item(item_id: int): if item_id < 0: raise HTTPException(status_code=400, detail="Item ID must be positive") return {"item_id": item_id}未处理的异常会被中间件捕获并:
- 记录完整的异常和堆栈跟踪
- 记录失败指标
- 向客户端返回安全的 500 响应
- 保留关联 ID
访问调用用户
Section titled “访问调用用户”在 ECS 上没有 Lambda Web Adapter 和 API Gateway 请求上下文标头:API Gateway 不会将授权器的声明转发到私有负载均衡器集成。授权器仍然决定请求是否到达容器,但您的处理程序无法从请求中读取调用者,如下所述。
要在操作中读取调用者的身份,请将授权器的上下文映射到 API 构造中的请求标头,并从 FastAPI Request 中读取该标头。
当您的 API 受身份验证保护时,您的路由处理程序通常需要知道谁在调用。生成的 FastAPI 通过 Lambda Web Adapter 在 AWS Lambda 内运行,它将 API Gateway 请求上下文作为 JSON 转发到 x-amzn-request-context 标头。您可以从 FastAPI Request 中读取它以提取调用者的身份。
例如,让我们添加一个 /me 端点,返回有关调用用户的详细信息。我们将提取实现为 FastAPI 依赖项,以便可以在路由之间重用。请求上下文的形状——因此您如何提取身份——取决于您选择的 auth 方法以及您是否部署了 REST 或 HTTP API。
对于 IAM 身份验证,我们使用从 API Gateway 请求上下文中提取的 sub 在 Cognito 中查找调用者,这需要 boto3。将其添加到您的 API 项目:
pnpm nx run my-api:add boto3==1.44.15yarn nx run my-api:add boto3==1.44.15npx nx run my-api:add boto3==1.44.15bunx nx run my-api:add boto3==1.44.15在 main.py 旁边创建 identity.py:
import jsonimport osfrom typing import Annotated
from boto3 import clientfrom fastapi import Depends, HTTPException, Requestfrom pydantic import BaseModel
cognito = client("cognito-idp")
class Identity(BaseModel): sub: str username: str
def get_identity(request: Request) -> Identity: # The Lambda Web Adapter forwards the API Gateway request context as JSON request_context_header = request.headers.get("x-amzn-request-context") if not request_context_header: raise HTTPException(status_code=403, detail="Unable to determine calling user")
request_context = json.loads(request_context_header) provider = request_context.get("identity", {}).get("cognitoAuthenticationProvider")
sub = provider.split(":")[-1] if provider else None if not sub: raise HTTPException(status_code=403, detail="Unable to determine calling user")
users = cognito.list_users( # Assumes user pool id is configured in lambda environment UserPoolId=os.environ["USER_POOL_ID"], Limit=1, Filter=f'sub="{sub}"', ).get("Users", [])
if len(users) != 1: raise HTTPException(status_code=403, detail=f"No user found with subjectId {sub}")
return Identity(sub=sub, username=users[0]["Username"])
CurrentUser = Annotated[Identity, Depends(get_identity)]import jsonimport osfrom typing import Annotated
from boto3 import clientfrom fastapi import Depends, HTTPException, Requestfrom pydantic import BaseModel
cognito = client("cognito-idp")
class Identity(BaseModel): sub: str username: str
def get_identity(request: Request) -> Identity: # The Lambda Web Adapter forwards the API Gateway request context as JSON request_context_header = request.headers.get("x-amzn-request-context") if not request_context_header: raise HTTPException(status_code=403, detail="Unable to determine calling user")
request_context = json.loads(request_context_header) amr = ( request_context.get("authorizer", {}) .get("iam", {}) .get("cognitoIdentity", {}) .get("amr", []) ) sign_in = next((s for s in amr if ":CognitoSignIn:" in s), None) sub = sign_in.split(":")[-1] if sign_in else None
if not sub: raise HTTPException(status_code=403, detail="Unable to determine calling user")
users = cognito.list_users( # Assumes user pool id is configured in lambda environment UserPoolId=os.environ["USER_POOL_ID"], Limit=1, Filter=f'sub="{sub}"', ).get("Users", [])
if len(users) != 1: raise HTTPException(status_code=403, detail=f"No user found with subjectId {sub}")
return Identity(sub=sub, username=users[0]["Username"])
CurrentUser = Annotated[Identity, Depends(get_identity)]使用 auth: 'cognito' 时,API Gateway Cognito User Pools 授权器会验证调用者在 Authorization 标头中提供的 JWT,并将验证的声明放在请求上下文中。
在 main.py 旁边创建 identity.py:
import jsonfrom typing import Annotated
from fastapi import Depends, HTTPException, Requestfrom pydantic import BaseModel
class Identity(BaseModel): sub: str username: str
def get_identity(request: Request) -> Identity: # The Lambda Web Adapter forwards the API Gateway request context as JSON request_context_header = request.headers.get("x-amzn-request-context") if not request_context_header: raise HTTPException(status_code=403, detail="Unable to determine calling user")
request_context = json.loads(request_context_header) claims = request_context.get("authorizer", {}).get("claims", {})
sub = claims.get("sub") username = claims.get("username")
if not sub or not username: raise HTTPException(status_code=403, detail="Unable to determine calling user")
return Identity(sub=sub, username=username)
CurrentUser = Annotated[Identity, Depends(get_identity)]HTTP API 使用 JWT 授权器,它将验证的声明放在 authorizer.jwt.claims 下:
import jsonfrom typing import Annotated
from fastapi import Depends, HTTPException, Requestfrom pydantic import BaseModel
class Identity(BaseModel): sub: str username: str
def get_identity(request: Request) -> Identity: # The Lambda Web Adapter forwards the API Gateway request context as JSON request_context_header = request.headers.get("x-amzn-request-context") if not request_context_header: raise HTTPException(status_code=403, detail="Unable to determine calling user")
request_context = json.loads(request_context_header) claims = request_context.get("authorizer", {}).get("jwt", {}).get("claims", {})
sub = claims.get("sub") username = claims.get("username")
if not sub or not username: raise HTTPException(status_code=403, detail="Unable to determine calling user")
return Identity(sub=sub, username=username)
CurrentUser = Annotated[Identity, Depends(get_identity)]然后,您可以将 CurrentUser 依赖项注入到任何需要调用者身份的路由中:
from .identity import CurrentUser, Identityfrom .init import app, tracer
@app.get("/me")@tracer.capture_methoddef me(identity: CurrentUser) -> Identity: return identity使用 REST API 时,生成的 FastAPI 开箱即支持流式响应。基础设施配置为使用 AWS Lambda Web Adapter 通过 uvicorn 在 Lambda 内运行您的 FastAPI,并在 API Gateway 中为所有 REST API 操作使用 ResponseTransferMode.STREAM,这使得流式传输可以与非流式操作一起工作。
使用 JsonStreamingResponse
Section titled “使用 JsonStreamingResponse”生成的 init.py 导出一个 JsonStreamingResponse 类,它提供类型安全的流式传输和正确的 OpenAPI 架构生成。这确保 connection 生成器 可以生成正确类型的流式客户端方法。
from pydantic import BaseModelfrom .init import app, JsonStreamingResponse
class Chunk(BaseModel): message: str
async def generate_chunks(): for i in range(100): yield Chunk(message=f"This is chunk {i}")
@app.post( "/stream", response_class=JsonStreamingResponse, responses={200: JsonStreamingResponse.openapi_response(Chunk, "Stream of chunks")},)async def my_stream() -> JsonStreamingResponse: return JsonStreamingResponse(generate_chunks())JsonStreamingResponse 类:
- 将 Pydantic 模型序列化为 JSON Lines 格式(
application/jsonl) - 提供一个
openapi_response辅助函数,生成带有itemSchema的正确 OpenAPI 架构,使connection生成器 能够生成类型安全的流式客户端方法
要消费响应流,您可以使用 connection 生成器,它将提供一个类型安全的方法来迭代您的流式块。
部署您的 FastAPI
Section titled “部署您的 FastAPI”FastAPI 生成器根据您选择的 iac 创建 CDK 或 Terraform 基础设施即代码。您可以使用它来部署您的 FastAPI。
用于部署 API 的 CDK 构造在 common/constructs 文件夹中。您可以在 CDK 应用程序中使用它:
import { MyApi } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Add the api to your stack const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(), }); }}这会设置:
- FastAPI 应用程序中每个操作的 AWS Lambda 函数
- API Gateway HTTP/REST API 作为函数触发器
- IAM 角色和权限
- CloudWatch 日志组
- X-Ray 追踪配置
- CloudWatch 指标命名空间
defaultIntegrations 接受您的服务运行所在的 VPC,并在其中构建所有内容:ECS 服务、其前面的内部负载均衡器以及 API Gateway 通过其到达该负载均衡器的 VPC 链接。该构造从不创建 VPC,因此您在堆栈中创建或导入一个。
import { MyApi } from '@my-scope/common-constructs';import { Stack } from 'aws-cdk-lib';import { Vpc } from 'aws-cdk-lib/aws-ec2';import { Construct } from 'constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { super(scope, id);
const vpc = new Vpc(this, 'Vpc', { natGateways: 1 });
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this, { vpc }).build(), }); }}要使用现有 VPC,请使用 Vpc.fromLookup(this, 'Vpc', { vpcId: '<vpc-id>' }) 查找它并将其作为 vpc 传递。
传递 service 以更改容器服务本身——其 cpu、memoryLimitMiB、desiredCount、environment,或 grantTaskRole 以授予任务角色权限:
MyApi.defaultIntegrations(this, { vpc, service: { cpu: 512, memoryLimitMiB: 1024, grantTaskRole: (taskRole) => myTable.grantReadWriteData(taskRole), },}).build();这会设置一个基于您选择的 auth 方法进行身份验证的 AWS API Gateway HTTP API、运行您的容器的 Amazon ECS 服务、其前面的内部负载均衡器以及 API Gateway 通过其到达该负载均衡器的 VPC 链接。
用于部署 API 的 Terraform 模块在 common/terraform 文件夹中。您可以在 Terraform 配置中使用它。
API 模块将其 Lambda 部署 zip 暂存在共享的 S3 资产存储桶中——有关详细信息,请参阅 Terraform 基础设施指南。每次部署实例化一次 core/asset-bucket 模块,并通过 asset_bucket_name 输入将其 bucket_name 输出传递到每个 API / Lambda 模块:
module "asset_bucket" { source = "../../common/terraform/src/core/asset-bucket"}
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
# Environment variables for the Lambda function env = { ENVIRONMENT = var.environment LOG_LEVEL = "INFO" }
# Additional IAM policies if needed additional_iam_policy_statements = [ # Add any additional permissions your API needs ]
tags = local.common_tags}这会设置:
- 为所有 FastAPI 路由提供服务的 AWS Lambda 函数
- API Gateway HTTP/REST API 作为函数触发器
- IAM 角色和权限
- CloudWatch 日志组
- X-Ray 追踪配置
- CORS 配置
Terraform 模块提供了几个您可以使用的输出:
# Access the API endpoint (the custom domain URL, if one is configured)output "api_url" { value = module.my_api.api_url}
# Access Lambda function detailsoutput "lambda_function_name" { value = module.my_api.lambda_function_name}
# Access IAM role for granting additional permissionsoutput "lambda_execution_role_arn" { value = module.my_api.lambda_execution_role_arn}您可以通过向模块传递变量来自定义 CORS 设置:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
# Custom CORS configuration cors_allow_origins = ["https://myapp.com", "https://staging.myapp.com"] cors_allow_methods = ["GET", "POST", "PUT", "DELETE"] cors_allow_headers = [ "authorization", "content-type", "x-custom-header" ]
tags = local.common_tags}对于 REST API,生成的构造默认会将 AWS WAFv2 Web ACL 与 API Gateway 阶段关联。Web ACL 使用 AWS 托管的默认规则集(AWSManagedRulesCommonRuleSet 和 AWSManagedRulesKnownBadInputsRuleSet),提供针对常见 Web 漏洞(包括 OWASP Top 10)的保护。WAF 请求日志会写入 CloudWatch Logs 日志组。
您可以编辑生成的 rest-api 构造来添加、删除或调整规则(例如,添加基于速率的规则或其他托管规则组)。
要选择退出(例如,附加您自己的 Web ACL),请将 enableWaf 设置为 false:
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(), enableWaf: false,});要选择退出(例如,附加您自己的 Web ACL),请将 enable_waf 设置为 false:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name enable_waf = false}访问日志记录
Section titled “访问日志记录”对于 REST API,生成的基础设施默认启用访问日志,为每个请求向专用的 CloudWatch Logs 日志组写入一行结构化的 JSON。该日志组使用客户管理的 KMS 密钥加密,并保留一年。
API Gateway 使用账户级别的 CloudWatch Logs 角色写入访问日志。此角色在 AWS::ApiGateway::Account 设置上配置,该设置是每个区域每个账户的单例 — 区域中的每个 REST API 只有一个角色。为了在多个独立部署的堆栈中安全地管理此角色,生成的基础设施:
- 仅在尚未设置有效角色时创建共享的 CloudWatch Logs 角色并在账户上配置它,因此部署永远不会覆盖另一个堆栈拥有的角色。
- 在拆除时保持账户设置不变,因此销毁一个堆栈永远不会禁用区域中其他 REST API 的日志记录。
账户角色由 ApiGatewayAccount 构造管理,这是一个通过 ApiGatewayAccount.ensure(scope) 解析的堆栈范围单例。每个 REST API 的阶段都依赖于它,该角色由 Lambda 支持的自定义资源配置。
访问日志格式由您的 API 扩展的 RestApi 构造设置。要自定义它,请在生成的 packages/common/constructs/src/app/apis/my-api.ts 中将 deployOptions 传递给 super,同时保留构造已设置的 tracingEnabled:
super(scope, id, { apiName: 'MyApi', // ... deployOptions: { tracingEnabled: true, accessLogFormat: AccessLogFormat.clf(), }, ...props,});AccessLogFormat 从 aws-cdk-lib/aws-apigateway 导入。任何未设置的内容都会保留构造的默认值 — 一个包含标准字段的 JSON 格式。
账户角色由 core/api/api-gateway-account 模块管理,该模块由生成的 API 模块实例化。它以幂等方式配置账户,并且在 terraform destroy 时永远不会重置。
您可以通过编辑生成的 API 模块中 aws_api_gateway_stage 资源上的 access_log_settings 块来自定义访问日志格式。
默认情况下,您的 API 从 API Gateway 为其生成的端点提供服务(https://<id>.execute-api.<region>.amazonaws.com/...)。要改为从您自己的域名提供服务,请提供您的域名和相应的 ACM 证书。自定义域名默认使用区域端点,因此证书必须与您的 API 位于同一区域。默认使用最低 TLS 版本 1.2。
配置自定义域名后,运行时配置中的 API URL 将是自定义域名 URL,因此您的网站和其他客户端将调用您的域名而不是生成的端点。
在生成的 packages/common/constructs/src/app/apis/my-api.ts 中将域名传递给 super:
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
super(scope, id, { apiName: 'MyApi', // ... domainName: { domainName: 'api.example.com', certificate: Certificate.fromCertificateArn( scope, 'MyApiCertificate', 'arn:aws:acm:<region>:123456789012:certificate/...', ), }, ...props,});API 在域名的根路径提供服务,不带阶段路径前缀(/prod/)。要改为在路径下提供服务,请在 domainName 上设置 basePath;运行时配置中的 URL 将包含它。basePath 仅在 CDK 中可用;Terraform 模块始终在域名的根路径提供 API 服务。
import { DomainName } from 'aws-cdk-lib/aws-apigatewayv2';import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
super(scope, id, { apiName: 'MyApi', // ... defaultDomainMapping: { domainName: new DomainName(scope, 'MyApiDomainName', { domainName: 'api.example.com', certificate: Certificate.fromCertificateArn( scope, 'MyApiCertificate', 'arn:aws:acm:<region>:123456789012:certificate/...', ), }), }, ...props,});配置自定义域名后,堆栈会输出 MyApiDomainNameAlias(要将 DNS 记录指向的域名)和 MyApiDomainNameAliasHostedZoneId。
在 API 模块上设置 custom_domain_name 和 acm_certificate_arn 变量:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api" # ...
custom_domain_name = "api.example.com" acm_certificate_arn = "arn:aws:acm:<region>:123456789012:certificate/..."}该模块输出 custom_domain_target_domain_name(要将 DNS 记录指向的区域域名)和 custom_domain_hosted_zone_id。其 api_url 输出是客户端应调用的 URL:配置自定义域名时为自定义域名 URL,否则为阶段调用 URL。
最后,为您的域名创建 DNS 记录。使用任何 DNS 提供商,创建一个 CNAME 记录,将您的域名指向上面输出的域名。如果您的域名托管在 Route 53 中,您可以改为创建别名记录,使用托管区域 ID 输出,这也适用于区域顶点(例如 example.com)。
REST/HTTP API CDK 构造被配置为提供类型安全的接口,用于为每个操作定义集成。
您可以使用静态方法 defaultIntegrations 来使用默认模式,该模式为每个操作定义一个单独的 AWS Lambda 函数:
new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(),});生成的模块已经为生成 API 时使用的模式定义了默认集成,因此不需要额外的配置:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
tags = local.common_tags}使用默认的 isolated 模式,这会为每个操作创建一个 Lambda 函数。
您可以通过 API 构造的 integrations 属性以类型安全的方式访问底层的 AWS Lambda 函数。例如,如果您的 API 定义了一个名为 sayHello 的操作,并且您需要向该函数添加一些权限,可以按如下方式操作:
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(),});
// sayHello is typed to the operations defined in your APIapi.integrations.sayHello.handler.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: [...], resources: [...],}));如果您的 API 使用 shared 模式,共享的路由器 Lambda 将作为 api.integrations.$router 公开:
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(),});
api.integrations.$router.handler.addEnvironment('LOG_LEVEL', 'DEBUG');请注意,如果您通过 withOverrides 覆盖了每个操作,$router 将不再可用,因为没有操作继续使用默认路由器集成。
使用 isolated 模式,模块的输出是以操作名称为键的映射,因此您可以访问单个操作的资源。例如,要为一个操作的 Lambda 函数授予额外权限:
# Grant additional permissions to just the sayHello operation's functionresource "aws_iam_role_policy" "say_hello_permissions" { name = "say-hello-additional-permissions" role = module.my_api.lambda_execution_role_names["sayHello"]
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = [ "s3:GetObject", "s3:PutObject" ] Resource = "arn:aws:s3:::my-bucket/*" } ] })}要为每个操作授予相同的权限,可以迭代 operations 输出:
resource "aws_iam_role_policy" "additional_permissions" { for_each = toset(module.my_api.operations)
name = "additional-api-permissions" role = module.my_api.lambda_execution_role_names[each.key]
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = ["s3:GetObject"] Resource = "arn:aws:s3:::my-bucket/*" } ] })}模块还公开了 lambda_function_names、lambda_function_arns、lambda_invoke_arns、integration_ids 和 lambda_log_group_names 作为以操作名称为键的映射。使用 shared 模式时,会公开等效的单数输出(lambda_execution_role_name、lambda_function_name、…),因为只有一个函数。
每个操作都需要的权限最好传递给模块,模块会将它们应用到每个函数的角色:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
additional_iam_policy_statements = [ { Effect = "Allow" Action = ["s3:GetObject"] Resource = ["arn:aws:s3:::my-bucket/*"] } ]}自定义默认选项
Section titled “自定义默认选项”如果您想自定义创建每个默认集成的 Lambda 函数时使用的选项,可以使用 withDefaultOptions 方法。例如,如果您希望所有 Lambda 函数都驻留在 Vpc 中:
const vpc = new Vpc(this, 'Vpc', ...);
new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withDefaultOptions({ vpc, }) .build(),});VPC 配置已由生成的模块支持 — 设置 enable_vpc 以及 vpc_id 和 subnet_ids,模块会将每个 Lambda 函数部署到您的 VPC 中,并为您创建一个共享的安全组:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
# VPC configuration enable_vpc = true vpc_id = aws_vpc.main.id subnet_ids = [aws_subnet.private_a.id, aws_subnet.private_b.id]
tags = local.common_tags}对于模块未公开的选项,请直接编辑生成的 Terraform 模块中的 aws_lambda_function 资源。使用 isolated 模式时,该单个资源声明为 for_each = local.operations,因此在那里进行的编辑会应用于每个操作。
按操作自定义选项
Section titled “按操作自定义选项”要自定义用于创建_特定_操作的默认集成的选项(而不影响其他操作),可以使用 withOperationOptions 方法。例如,如果您想仅为一个操作增加 Lambda 函数超时时间:
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withOperationOptions({ sayHello: { timeout: Duration.seconds(60), }, }) .build(),});
// The selected operations remain default integrations, so they're still typed accordingly:api.integrations.sayHello.handler.addToRolePolicy(new PolicyStatement({ ... }));您指定的选项将与默认集成选项(以及通过 withDefaultOptions 设置的任何选项)合并。请注意,您不能为通过 withOverrides 替换的操作指定选项,因为这些操作不再使用默认集成。
如果同一操作同时被 withOperationOptions 和 withOverrides 针对,无论您调用它们的顺序如何,都会遇到类型错误。
使用 isolated 模式时,Lambda 函数资源已经是按操作的,因此可以按操作名称变化选项。例如,要为一个操作提供更长的超时时间,请编辑生成的模块中的 aws_lambda_function 资源:
resource "aws_lambda_function" "api_lambda" { for_each = local.operations
# Default to 30 seconds, but allow longer for specific operations timeout = lookup({ sayHello = 60 }, each.key, 30)
# ... rest of configuration}您还可以使用 withOverrides 方法覆盖特定操作的集成。每个覆盖必须指定一个 integration 属性,该属性的类型对应于 HTTP 或 REST API 的适当 CDK 集成构造。withOverrides 方法也是类型安全的。例如,如果您想覆盖 getDocumentation API 以指向某个外部网站托管的文档,可以按如下方式实现:
new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withOverrides({ getDocumentation: { integration: new HttpIntegration('https://example.com/documentation'), }, }) .build(),});您还会注意到,当通过 api.integrations.getDocumentation 访问时,被覆盖的集成不再具有 handler 属性。
您可以向集成添加额外的属性,这些属性也将相应地进行类型化,从而允许其他类型的集成被抽象但保持类型安全。例如,如果您为 REST API 创建了 S3 集成,并且稍后希望引用特定操作的存储桶,可以按如下方式操作:
const storageBucket = new Bucket(this, 'Bucket', { ... });
const apiGatewayRole = new Role(this, 'ApiGatewayS3Role', { assumedBy: new ServicePrincipal('apigateway.amazonaws.com'),});
storageBucket.grantRead(apiGatewayRole);
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withOverrides({ getFile: { bucket: storageBucket, integration: new AwsIntegration({ service: 's3', integrationHttpMethod: 'GET', path: `${storageBucket.bucketName}/{fileName}`, options: { credentialsRole: apiGatewayRole, requestParameters: { 'integration.request.path.fileName': 'method.request.querystring.fileName', }, integrationResponses: [{ statusCode: '200' }], }, }), options: { requestParameters: { 'method.request.querystring.fileName': true, }, methodResponses: [{ statusCode: '200', }], } }, }) .build(),});
// Later, perhaps in another file, you can access the bucket property we defined// in a type-safe mannerapi.integrations.getFile.bucket.grantRead(...);要将特定操作指向不同的集成类型,请将其从默认的 for_each 中排除,并单独声明其集成。例如,要从外部网站提供 getDocumentation:
# Exclude the overridden operation from the default per-operation resourceslocals { overridden_operations = ["getDocumentation"] default_operations = { for op, details in local.operations : op => details if !contains(local.overridden_operations, op) }}
# Then use local.default_operations in place of local.operations for the# aws_lambda_function, aws_iam_role, aws_apigatewayv2_integration and# aws_lambda_permission resources, and add the override:resource "aws_apigatewayv2_integration" "get_documentation" { api_id = module.http_api.api_id integration_type = "HTTP_PROXY" integration_uri = "https://example.com/documentation" integration_method = "GET"}
resource "aws_apigatewayv2_route" "get_documentation" { api_id = module.http_api.api_id route_key = local.route_key["getDocumentation"] target = "integrations/${aws_apigatewayv2_integration.get_documentation.id}"}您还可以在集成中提供 options 来覆盖特定的方法选项,例如授权器。例如,如果您希望为 getDocumentation 操作使用 Cognito 身份验证:
new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withOverrides({ getDocumentation: { integration: new HttpIntegration('https://example.com/documentation'), options: { authorizer: new CognitoUserPoolsAuthorizer(...) // for REST, or HttpUserPoolAuthorizer for an HTTP API } }, }) .build(),});授权在每个操作的路由(HTTP API)或方法(REST API)上设置,因此可以按操作名称变化。例如,要在 HTTP API 上保留一个操作未经身份验证:
resource "aws_apigatewayv2_route" "operation_routes" { for_each = local.operations
# ... rest of configuration
authorization_type = each.key == "getDocumentation" ? "NONE" : "AWS_IAM"}对于 IAM 身份验证的 REST API,还要添加资源策略语句,允许未经身份验证访问该操作的路径。
如果您愿意,可以选择不使用默认集成,而是直接为每个操作提供一个集成。这在以下情况下很有用,例如,每个操作需要使用不同类型的集成,或者您希望在添加新操作时收到类型错误:
new MyApi(this, 'MyApi', { integrations: { sayHello: { integration: new LambdaIntegration(...), }, getDocumentation: { integration: new HttpIntegration(...), }, },});将 isolated 模式使用的 for_each 替换为每个操作的 Lambda 函数、集成和权限的显式实例化。
生成的 API 支持两种集成模式:
isolated为每个操作创建一个 Lambda 函数。这是 API 的默认和推荐选项。shared创建一个默认路由器 Lambda 并将其重用于每个操作,除非您覆盖特定集成。
isolated 为您提供更细粒度的每个操作权限和配置,以及更好的日志和跟踪分离。shared 减少了低使用率 API 遇到冷启动的可能性。
集成模式可以随时在 CDK 中通过更新 API 构造来更改。例如,将 pattern 设置为 'shared' 会创建一个函数,而不是每个集成一个函数:
export class MyApi<...> extends ... {
public static defaultIntegrations = (scope: Construct) => { ... return IntegrationBuilder.rest({ pattern: 'shared', ... }); };}与 CDK 不同,集成模式被烘焙到生成的模块中。要更改集成模式:
- 删除
packages/common/terraform/src/app/apis中先前生成的 API 模块 - 使用其他集成模式重新运行创建 API 的生成器(例如
--integrationPattern=shared)
使用 isolated 模式时,模块从生成的文件中读取操作:
locals { operations_file = "${path.module}/../../../generated/my-api/operations.json" operations = fileexists(local.operations_file) ? jsondecode(file(local.operations_file)) : {}}此文件是从您的 API 生成的,因此您无需手动编辑它。在 API 应用程序代码中添加操作会在下次部署时添加路由和 lambda 函数。默认情况下它被 .gitignore;如果您希望将其签入,请删除该条目。
Terraform REST API 路径深度限制
Section titled “Terraform REST API 路径深度限制”由于 FastAPI 中的操作是用 Python 定义的,而 CDK 基础设施是用 TypeScript 定义的,我们使用代码生成来向 CDK 构造提供元数据,以提供类型安全的集成接口。
一个 generate:<ApiName>-metadata 目标被添加到公共构造的 project.json 中以促进此代码生成,它会生成一个文件,例如 packages/common/constructs/src/generated/my-api/metadata.gen.ts。由于这是在构建时生成的,因此在版本控制中被忽略。
授予访问权限(仅限 IAM)
Section titled “授予访问权限(仅限 IAM)”如果您选择使用 IAM 身份验证,您可以使用 grantInvokeAccess 方法授予对 API 的访问权限:
api.grantInvokeAccess(myIdentityPool.authenticatedRole);# Create an IAM policy to allow invoking the APIresource "aws_iam_policy" "api_invoke_policy" { name = "MyApiInvokePolicy" description = "Policy to allow invoking the FastAPI"
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = "execute-api:Invoke" Resource = "${module.my_api.api_execution_arn}/*/*" } ] })}
# Attach the policy to an IAM role (e.g., for authenticated users)resource "aws_iam_role_policy_attachment" "api_invoke_access" { role = aws_iam_role.authenticated_user_role.name policy_arn = aws_iam_policy.api_invoke_policy.arn}
# Or attach to an existing role by nameresource "aws_iam_role_policy_attachment" "api_invoke_access_existing" { role = "MyExistingRole" policy_arn = aws_iam_policy.api_invoke_policy.arn}您可以用于 IAM 策略的 API 模块的关键输出是:
module.my_api.api_execution_arn- 用于授予 execute-api:Invoke 权限module.my_api.api_arn- API Gateway ARNmodule.my_api.lambda_function_arn- Lambda 函数 ARN
生成器配置了一个本地开发服务器,您可以使用以下命令运行:
pnpm nx serve <project-name>yarn nx serve <project-name>npx nx serve <project-name>bunx nx serve <project-name>这会启动一个本地 FastAPI 开发服务器,具有:
- 代码更改时自动重新加载
/docs或/redoc上的交互式 API 文档/openapi.json上的 OpenAPI 架构
这会启动容器的入口点,即镜像运行的同一文件,具有:
GET /health,像为负载均衡器响应一样响应/docs或/redoc上的交互式 API 文档/openapi.json上的 OpenAPI 架构
服务器绑定 127.0.0.1,因此它仅在您自己的机器上响应。它不会重新加载任何内容:重新启动它以获取代码更改。要从另一台机器、VM 或容器访问它,请在 serve 目标上设置 HOST=0.0.0.0——这使得 API 可以被任何可以访问您的机器的东西访问,且未经身份验证。
在 Amazon ECS 上运行
Section titled “在 Amazon ECS 上运行”当 infra 设置为 http-ecs 时,您的 API 作为长期运行的 uvicorn 服务器在容器中运行,而不是在 Lambda Web Adapter 后面的 Lambda 函数中。请求采用以下路径:
- 调用者对 API Gateway HTTP API 签名请求,这是唯一的公共入口点。每个路由都带有您选择的
auth的授权器,因此未经身份验证的请求会在边缘被拒绝。 - API Gateway 通过 VPC 链接转发请求,这是它进入您的 VPC 的私有路径。
- VPC 链接到达内部负载均衡器。负载均衡器没有公共地址,其唯一的入站规则允许 VPC 链接的安全组在侦听器端口上。
- 负载均衡器将请求转发到任务。任务的唯一入站规则允许负载均衡器的安全组在容器端口上,因此 VPC 中的其他任何东西都无法打开与它们的连接。
任务在私有子网中运行,永远不会获得公共 IP 地址。此路径中没有任何内容允许地址范围入站。
默认情况下,服务、负载均衡器和 VPC 链接位于 VPC 的 PRIVATE_WITH_EGRESS 子网中,这些子网通过 NAT 网关到达 AWS。将 vpcSubnets: { subnetType: SubnetType.PRIVATE_ISOLATED } 传递给 defaultIntegrations 会删除 NAT 网关及其每小时费用,但隔离的子网没有出站路由,因此 VPC 需要四个 VPC 端点才能启动任务:用于拉取镜像的 ecr.api 和 ecr.dkr 的接口端点,一个 S3 网关端点(因为镜像层是 S3 对象),以及一个用于 logs 的接口端点,以便 awslogs 驱动程序可以写入。没有它们,任务无法拉取其镜像,ECS 会在断路器上回滚部署而不说明原因。
VPC 链接、负载均衡器、其侦听器、目标组以及负载均衡器将其访问日志写入的存储桶由一个构造创建,即 common/constructs 中的 core/api/ecs-http-endpoint.ts,每个托管在 ECS 上的 API 都共享它。您的 API 自己的构造命名其容器服务并将每个操作路由到该端点。
容器中运行的内容
Section titled “容器中运行的内容”<module_name>/<api_name>_container/main.py 从您的 main.py 导入应用程序,因此您编写的每个操作都像在 Lambda 上一样提供服务。它添加了两个自己的东西:
GET /health,负载均衡器的目标组和容器健康检查调用它。它被声明为include_in_schema=False,因此它不会出现在您的 OpenAPI 规范中,因此也不会出现在 API Gateway 路由和生成的客户端中。它也被排除在请求指标之外,因此目标组每 15 秒的调用不会计为 API 请求。- 一个中间件,写出 API 自己的中间件收集的指标。在 Lambda 上,处理程序在每次调用结束时执行此操作;此服务器跨请求存在,因此它自己刷新它们。
API Gateway 路由仍然来自您的 OpenAPI 规范,因此一旦 nx build 重新生成规范,您添加的操作就会被部署。
日志和指标的工作方式与在 Lambda 上相同:容器写入自己的 CloudWatch 日志组,指标以嵌入式指标格式写入,供 CloudWatch Logs 提取。
关于指标,这里有一点不同,在您阅读仪表板或添加自己的指标之前值得了解。metrics,即上面的指标部分告诉您从 .init 导入的对象,是一个 Powertools Metrics,进程中的每个 Metrics 对象共享一个指标存储。在 Lambda 上,一次调用从头到尾拥有该存储。uvicorn 服务器同时处理请求,API 自己的每个请求指标和您添加的任何指标都进入该一个存储,因此同时进行的两个请求可以将它们的指标写入一个文档中,并归因于首先添加的路由。另一个请求的文档可能根本没有 route 维度,只保存第一次刷新后添加的指标,当发生这种情况时,Powertools 会记录 PowertoolsUserWarning: Dimension 'route' has already been added。在轻流量下,请求很少重叠的地方,您不会看到它。
因此,在 ECS 上将每个路由的 RequestCount 和 Success 视为近似值。如果您需要将指标精确归因于一个请求,请将其添加到您在请求中创建的 EphemeralMetrics 并在返回之前刷新,它保留自己的存储:
from aws_lambda_powertools.metrics import EphemeralMetrics, MetricUnit
@app.get("/items/{item_id}")def read_item(item_id: int): request_metrics = EphemeralMetrics() request_metrics.add_metric(name="ItemViewed", unit=MetricUnit.Count, value=1) request_metrics.flush_metrics() return {"item_id": item_id}AWS X-Ray 追踪则不然。@tracer.capture_method 在 Lambda 之外是无操作的,任务中也没有 X-Ray 守护进程来接收段。如果您需要追踪,请在容器服务中添加一个作为 sidecar。
API Gateway HTTP API 的访问日志记录到达 API 的每个请求。负载均衡器将其自己的访问日志写入 EcsHttpEndpoint 构造创建的存储桶,您可以在其中查看哪个任务为请求提供服务以及它的响应。
镜像构建和扫描
Section titled “镜像构建和扫描”容器生成器提供镜像目标,以您的 API 命名:
<api-name>-container-docker为architecture选项中的 CPU 架构构建镜像,linux/arm64或linux/amd64。该选项默认为运行生成器的机器的架构,您可以使用--architecture设置它。该目标首先运行匹配的 bundle 目标,bundle-arm或bundle-x86,因此镜像包含为该架构构建的包及其依赖项。<api-name>-container-trivy扫描该镜像的漏洞。
请参阅 Python Container Service 了解镜像的构建方式,以及 Docker Bundling 了解它在部署时的发布方式。
deploy-sandbox 在 CloudFormation 快速模式下部署,一旦应用每个资源的配置就返回,而不是等待 ECS 服务达到稳定状态。因此,目标可以在第一个任务仍在启动时完成,在任务通过两次相隔十五秒的健康检查之前,负载均衡器没有目标可以发送请求,并回答 503。部署返回后预计大约一分钟。等待一两分钟后再次调用。永远不会清除的 503 是真正的失败而不是缓慢启动:当没有任务变得健康时,服务的部署断路器会回滚它。
ECS 在容器内运行自己的健康检查。它每 30 秒调用一次 GET /health,任务启动后前 30 秒内的失败不计入其中。在该检查首次报告之前,aws ecs describe-tasks 给任务一个 UNKNOWN 的 healthStatus,一旦通过就变为 HEALTHY。UNKNOWN 意味着检查尚未报告,而不是它失败了。
API 的 URL 是堆栈输出,但不在您猜测的名称下。CfnOutput 在您的 API 构造内创建,没有任何东西覆盖其逻辑 ID,因此 CDK 从构造的路径加上八个字符的哈希构建输出键:添加为 new MyApi(this, 'MyApi', …) 的 API 输出 MyApiMyApiUrl 和该哈希,而不是 MyApiUrl。cdk deploy 打印该值,脚本应该匹配后缀而不是整个键:
aws cloudformation describe-stacks --stack-name <stack-name> \ --query "Stacks[0].Outputs[?contains(OutputKey, 'Url')].OutputValue" --output textdestroy-sandbox 会留下 HTTP API 的访问日志组和加密它的客户管理的 KMS 密钥。两者都没有设置删除策略,因此 CDK 的默认 Retain 适用,CloudFormation 跳过它们而不是删除它们。在拆除堆栈之前列出它们,因为已删除的堆栈不再报告其资源:
aws cloudformation describe-stack-resources --stack-name <stack-name> \ --query "StackResources[?contains(LogicalResourceId, 'AccessLogs') && (ResourceType=='AWS::Logs::LogGroup' || ResourceType=='AWS::KMS::Key')].[ResourceType,PhysicalResourceId]" \ --output text然后使用 aws logs delete-log-group --log-group-name <log-group-name> 和 aws kms schedule-key-deletion --key-id <key-id> --pending-window-in-days 7 删除它们,七天是 KMS 接受的最短窗口。
API Gateway 每个账户每 30 秒接受一次 VPC 链接删除,并且该配额无法提高。使用同一 VPC 的堆栈中的每个 http-ecs API 共享一个 VPC 链接,因此无论堆栈包含多少个这些 API,堆栈都会删除单个链接。堆栈边界之间不共享任何内容,嵌套堆栈算作自己的堆栈,因此在一个账户中同时拆除的堆栈仍然可能发生冲突。如果堆栈在 VPC 链接上以 DELETE_FAILED 结束,请等待 30 秒并再次删除堆栈。
从为每个 API 提供自己链接的版本升级需要一次检查,如果堆栈已经在一个 VPC 上部署了三个或更多这些 API。下一次部署会保留第一个 API 的链接并在单个清理阶段删除其他链接,因此第二次删除会在第一次删除后几秒钟发出,API Gateway 会限制它。然后堆栈事件会在 VPC 链接及其安全组上显示 DELETE_FAILED,在链接仍在使用时无法删除安全组,更新会花费大约 20 分钟更长的时间,而 CloudFormation 在同一清理中重试两者。它会在稍后的尝试中删除它们,更新以 UPDATE_COMPLETE 结束。完成后,检查堆栈事件或 API Gateway 控制台中的 VPC 链接列表,查找仍处于 DELETE_FAILED 状态的链接。等待 30 秒并删除处于该状态的任何链接,然后删除其安全组。留下的链接会计入每个区域十个的配额,直到它消失;其安全组则不会。
- 集成超时。 API Gateway HTTP API 将集成限制在大约 30 秒。无论容器工作多长时间,超过该时间的操作都会在网关处失败。
- 无流式传输。 流式操作需要
rest-lambda基础设施。HTTP API 无法流式传输响应。 - 有效负载大小。 请求和响应遵循 API Gateway 的 10 MB 限制。
- 每个区域的 VPC 链接。 API Gateway 每个账户每个区域允许十个 VPC 链接,可通过 Service Quotas 提高。共享堆栈和 VPC 的 API 共享一个链接,因此计入配额的是堆栈和 VPC 而不是 API。
- 每个操作一个服务。
integrationPattern是shared:有一个容器服务,每个路由都路由到它。该选项始终解析为此基础设施的shared,isolated会被忽略并发出警告。
与 Lambda 相比,负载均衡器是新的固定成本,在 Lambda 中您按请求付费,空闲时不付费。us-east-1 中的大致月度数字,数据传输之前:
| 项目 | 大约 |
|---|---|
| 内部负载均衡器 | $16 加上负载均衡器容量单位 |
| Fargate 任务,0.25 vCPU / 0.5 GB | 在 ARM64 上每个任务 $7,在 X86_64 上更多,Fargate 对每个 vCPU 和每 GB 的收费率更高 |
| NAT 网关,如果您的 VPC 有一个 | $33 |
| VPC 链接 | 无每小时费用 |
| 负载均衡器访问日志的 S3 存储 | 每月每 GB 几美分 |
因此,一个单任务服务在 ARM64 上任何流量之前每月花费大约 $23,如果您传入的 VPC 有 NAT 网关,则更多。访问日志随流量增长:向 endpoint.accessLogsBucket 添加生命周期规则以使其过期。查看 Elastic Load Balancing 和 AWS Fargate 定价页面以获取您所在区域的当前价格。
调用您的 FastAPI
Section titled “调用您的 FastAPI”要从 React 网站调用您的 API,您可以使用 connection 生成器。
使用 connection 生成器将此项目与工作区中的其他项目集成。以下连接涉及此项目: