Appearance
如何使用 Python 自动化管理 Azure API Management (APIM)
通过 Python SDK 自动化 Azure API Management (APIM) 的全生命周期管理,包括服务实例化、API 导入、产品定义、策略实施以及订阅发放。
为什么需要这个技能
在企业级架构中,手动在 Azure 门户中配置 API 网关(APIM)不仅效率低下,且难以实现版本控制和环境一致性。
通过 azure-mgmt-apimanagement 库,开发者可以将 API 网关的配置转化为代码(IaC)。这意味着你可以快速地在开发、测试和生产环境之间同步 API 定义、限流策略和访问控制,避免人为配置错误导致的服务中断。
适用场景
- 自动化部署:在 CI/CD 流水线中自动将 OpenAPI 定义文件导入到 APIM。
- 动态策略更新:通过代码批量更新 API 的限流(Rate Limit)或 Header 转换策略。
- 订阅管理:为新客户或新应用自动创建 API 订阅并分发密钥。
- 环境迁移:将 API 及其关联的产品、命名值(Named Values)快速迁移至新区域。
核心工作流
1. 环境准备与认证
安装必要的 SDK 并配置订阅 ID:
bash
pip install azure-mgmt-apimanagement
pip install azure-identitypython
from azure.identity import DefaultAzureCredential
from azure.mgmt.apimanagement import ApiManagementClient
import os
client = ApiManagementClient(
credential=DefaultAzureCredential(),
subscription_id=os.environ["AZURE_SUBSCRIPTION_ID"]
)2. 资源创建与 API 导入
创建 APIM 实例并从 OpenAPI URL 导入接口定义:
python
from azure.mgmt.apimanagement.models import ApiCreateOrUpdateParameter, ContentFormat, Protocol
api = client.api.begin_create_or_update(
resource_group_name="my-resource-group",
service_name="my-apim",
api_id="petstore",
parameters=ApiCreateOrUpdateParameter(
display_name="Petstore API",
path="petstore",
protocols=[Protocol.HTTPS],
format=ContentFormat.OPENAPI_LINK,
value="https://petstore.swagger.io/v2/swagger.json"
)
).result()3. 策略配置与访问控制
定义 XML 策略(如限流)并绑定到 API,同时创建产品(Product)以封装 API 访问权限:
python
from azure.mgmt.apimanagement.models import PolicyContract, ProductContract
# 设置 API 策略
policy_xml = "<policies><inbound><rate-limit calls="100" renewal-period="60" /></inbound></policies>"
client.api_policy.create_or_update(
resource_group_name="my-resource-group",
service_name="my-apim",
api_id="my-api",
policy_id="policy",
parameters=PolicyContract(value=policy_xml, format="xml")
)
# 创建产品
product = client.product.create_or_update(
resource_group_name="my-resource-group",
service_name="my-apim",
product_id="premium",
parameters=ProductContract(display_name="Premium", state="published")
)下载和安装
下载 azure-mgmt-apimanagement-py 中文版 Skill ZIP
解压后将目录放入你的 AI 工具 skills 文件夹,重启工具后即可使用。具体路径参考内附的 USAGE.zh.md。
你可能还需要
暂无推荐