如何为Localstack中的API Gateway设置永久固定访问URL
解决方案
方案1:硬编码固定API Gateway ID
Localstack原生支持通过特殊标签指定API网关的固定ID,你只需要在创建REST API时添加键为_custom_id_的标签即可,不同工具的配置方式如下:
- 用AWS CLI创建时的命令示例:
aws apigateway create-rest-api \ --name 你的API名称 \ --tags _custom_id_=myfixedid001 \ --endpoint-url http://localhost:4566
配置完成后访问路径就固定为http://localhost:4566/restapis/myfixedid001/local/_user_request_,重启Localstack或者更换设备部署都不会变更ID。
- 用Serverless Framework部署时,在配置文件中添加标签:
provider: name: aws tags: _custom_id_: myfixedid001
- 用AWS CDK部署时,在API构造参数中添加标签:
const api = new apigateway.RestApi(this, 'LocalTestApi', { restApiName: '你的API名称', tags: { _custom_id_: 'myfixedid001' } });
方案2:使用简化路径省略随机ID
Localstack支持直接用API名称代替随机ID访问服务,不需要额外配置,访问格式为:http://localhost:4566/restapis/<你的API名称>/local/_user_request_
比如你创建的API名称为user-service,直接访问http://localhost:4566/restapis/user-service/local/_user_request_即可,完全不需要关心生成的随机ID。
方案3:启动脚本动态获取ID
如果不想修改API配置,也可以在前端启动脚本中先调用接口拉取当前的API ID再拼接地址,示例shell脚本如下:
# 拉取API列表过滤出对应API的ID API_ID=$(aws apigateway get-rest-apis --endpoint-url http://localhost:4566 | jq -r '.items[] | select(.name == "你的API名称") | .id') # 把完整接口地址写入前端环境变量文件 echo "REACT_APP_API_ENDPOINT=http://localhost:4566/restapis/${API_ID}/local/_user_request_" > .env.local # 启动前端服务 npm run start
内容的提问来源于stack exchange,提问作者Konstantin Bodnia
相关产品推荐
相关产品推荐

