mcpField
A
azure-mgmt-apicenter-dotnet

azure-mgmt-apicenter-dotnet

github.com/sickn33云与 DevOps48.7k52 次安装今天更新
代码仓库

关于 azure-mgmt-apicenter-dotnet

用于通过 .NET 管理 Azure API Center API 清单与治理的技能,涵盖 API 分组、版本、规范、环境和部署记录。

主要功能

  1. 01创建工作区和 API 记录
  2. 02管理 API 版本与定义
  3. 03导出 API 规范
  4. 04跟踪环境与部署
  5. 05定义元数据架构
  6. 06列出工作区中的 API

适用场景

  1. 01按团队或产品编目 API
  2. 02上传和导出 API 规范
  3. 03记录 API 生命周期与部署信息

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-mgmt-apicenter-dotnet

安装后在 Claude Code 中输入/azure-mgmt-apicenter-dotnet确认已加载。

详细介绍

Azure.ResourceManager.ApiCenter (.NET)

用于管理组织内各类 API 的集中式 API 清单与治理 SDK。

安装

dotnet add package Azure.ResourceManager.ApiCenter
dotnet add package Azure.Identity

示例面向历史版本的 1.0 API 系列。请固定使用经过审核的程序包,并根据官方参考确认准确的生成类型/API 版本;这并不表示使用的是最新版本。

环境变量

AZURE_SUBSCRIPTION_ID=<your-subscription-id>
AZURE_RESOURCE_GROUP=<your-resource-group>
AZURE_APICENTER_SERVICE_NAME=<your-apicenter-service>

身份验证

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApiCenter;

ArmClient client = new ArmClient(new DefaultAzureCredential());

资源层级结构

Subscription
└── ResourceGroup
    └── ApiCenterService                    # API inventory service
        ├── Workspace                       # Logical grouping of APIs
        │   ├── Api                         # API definition
        │   │   └── ApiVersion              # Version of the API
        │   │       └── ApiDefinition       # OpenAPI/GraphQL/etc specification
        │   ├── Environment                 # Deployment target (dev/staging/prod)
        │   └── Deployment                  # API deployed to environment
        └── MetadataSchema                  # Custom metadata definitions

这些是相互独立的代码片段,需要导入 Azure/Azure.Core/Resources,并使用固定版本的 SDK 进行编译。请确认准确的订阅/资源 ID、权限和成本,然后再预配资源。API Center 记录用于记录部署情况;创建部署记录并不会部署可正常运行的 API。上传前,请检查规范中是否包含嵌入的凭据/内部数据。

核心工作流

1. 创建 API Center 服务
using Azure.ResourceManager.ApiCenter;
using Azure.ResourceManager.ApiCenter.Models;

// Resolve the explicitly selected subscription, avoiding sync-over-async/default-account ambiguity.
var subscription = client.GetSubscriptionResource(new ResourceIdentifier(
    $"/subscriptions/{Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID")}"));
ResourceGroupResource resourceGroup = (await subscription
    .GetResourceGroupAsync("my-resource-group")).Value;

ApiCenterServiceCollection services = resourceGroup.GetApiCenterServices();

ApiCenterServiceData data = new ApiCenterServiceData(AzureLocation.EastUS)
{
    Identity = new ManagedServiceIdentity(ManagedServiceIdentityType.SystemAssigned)
};

ArmOperation<ApiCenterServiceResource> operation = await services
    .CreateOrUpdateAsync(WaitUntil.Completed, "my-api-center", data);

ApiCenterServiceResource service = operation.Value;
2. 创建工作区
ApiCenterWorkspaceCollection workspaces = service.GetApiCenterWorkspaces();

ApiCenterWorkspaceData workspaceData = new ApiCenterWorkspaceData
{
    Title = "Engineering APIs",
    Description = "APIs owned by the engineering team"
};

ArmOperation<ApiCenterWorkspaceResource> operation = await workspaces
    .CreateOrUpdateAsync(WaitUntil.Completed, "engineering", workspaceData);

ApiCenterWorkspaceResource workspace = operation.Value;
3. 创建 API
ApiCenterApiCollection apis = workspace.GetApiCenterApis();

ApiCenterApiData apiData = new ApiCenterApiData
{
    Title = "Orders API",
    Description = "API for managing customer orders",
    Kind = ApiKind.Rest,
    LifecycleStage = ApiLifecycleStage.Production,
    TermsOfService = new ApiTermsOfService
    {
        Uri = new Uri("https://example.com/terms")
    },
    ExternalDocumentation = 
    {
        new ApiExternalDocumentation
        {
            Title = "Documentation",
            Uri = new Uri("https://docs.example.com/orders")
        }
    },
    Contacts =
    {
        new ApiContact
        {
            Name = "API Support",
            Email = "[email protected]"
        }
    }
};

// Add custom metadata
apiData.CustomProperties = BinaryData.FromObjectAsJson(new
{
    team = "orders-team",
    costCenter = "CC-1234"
});

ArmOperation<ApiCenterApiResource> operation = await apis
    .CreateOrUpdateAsync(WaitUntil.Completed, "orders-api", apiData);

ApiCenterApiResource api = operation.Value;
4. 创建 API 版本
ApiCenterApiVersionCollection versions = api.GetApiCenterApiVersions();

ApiCenterApiVersionData versionData = new ApiCenterApiVersionData
{
    Title = "v1.0.0",
    LifecycleStage = ApiLifecycleStage.Production
};

ArmOperation<ApiCenterApiVersionResource> operation = await versions
    .CreateOrUpdateAsync(WaitUntil.Completed, "v1-0-0", versionData);

ApiCenterApiVersionResource version = operation.Value;
5. 创建 API 定义(上传 OpenAPI 规范)
ApiCenterApiDefinitionCollection definitions = version.GetApiCenterApiDefinitions();

ApiCenterApiDefinitionData definitionData = new ApiCenterApiDefinitionData
{
    Title = "OpenAPI Specification",
    Description = "Orders API OpenAPI 3.0 definition"
};

ArmOperation<ApiCenterApiDefinitionResource> operation = await definitions
    .CreateOrUpdateAsync(WaitUntil.Completed, "openapi", definitionData);

ApiCenterApiDefinitionResource definition = operation.Value;

// Import specification
string openApiSpec = await File.ReadAllTextAsync("orders-api.yaml");

ApiSpecImportContent importContent = new ApiSpecImportContent
{
    Format = ApiSpecImportSourceFormat.Inline,
    Value = openApiSpec,
    Specification = new ApiSpecImportSpecification
    {
        Name = "openapi",
        Version = "3.0.1"
    }
};

await definition.ImportSpecificationAsync(WaitUntil.Completed, importContent);
6. 导出 API 规范
ApiCenterApiDefinitionResource definition = await client
    .GetApiCenterApiDefinitionResource(definitionResourceId)
    .GetAsync();

ArmOperation<ApiSpecExportResult> operation = await definition
    .ExportSpecificationAsync(WaitUntil.Completed);

ApiSpecExportResult result = operation.Value;

// result.Format - e.g., "inline"
// result.Value - the specification content
7. 创建环境
ApiCenterEnvironmentCollection environments = workspace.GetApiCenterEnvironments();

ApiCenterEnvironmentData envData = new ApiCenterEnvironmentData
{
    Title = "Production",
    Description = "Production environment",
    Kind = ApiCenterEnvironmentKind.Production,
    Server = new ApiCenterEnvironmentServer
    {
        ManagementPortalUris = { new Uri("https://portal.azure.com") }
    },
    Onboarding = new EnvironmentOnboardingModel
    {
        Instructions = "Contact platform team for access",
        DeveloperPortalUris = { new Uri("https://developer.example.com") }
    }
};

ArmOperation<ApiCenterEnvironmentResource> operation = await environments
    .CreateOrUpdateAsync(WaitUntil.Completed, "production", envData);
8. 创建部署
ApiCenterDeploymentCollection deployments = workspace.GetApiCenterDeployments();

// Get environment resource ID
ResourceIdentifier envResourceId = ApiCenterEnvironmentResource.CreateResourceIdentifier(
    subscriptionId, resourceGroupName, serviceName, workspaceName, "production");

// Get API definition resource ID
ResourceIdentifier definitionResourceId = ApiCenterApiDefinitionResource.CreateResourceIdentifier(
    subscriptionId, resourceGroupName, serviceName, workspaceName, 
    "orders-api", "v1-0-0", "openapi");

ApiCenterDeploymentData deploymentData = new ApiCenterDeploymentData
{
    Title = "Orders API - Production",
    Description = "Production deployment of Orders API v1.0.0",
    EnvironmentId = envResourceId,
    DefinitionId = definitionResourceId,
    State = ApiCenterDeploymentState.Active,
    Server = new ApiCenterDeploymentServer
    {
        RuntimeUris = { new Uri("https://api.example.com/orders") }
    }
};

ArmOperation<ApiCenterDeploymentResource> operation = await deployments
    .CreateOrUpdateAsync(WaitUntil.Completed, "orders-api-prod", deploymentData);
9. 创建元数据架构
ApiCenterMetadataSchemaCollection schemas = service.GetApiCenterMetadataSchemas();

string jsonSchema = """
{
    "type": "object",
    "properties": {
        "team": {
            "type": "string",
            "title": "Owning Team"
        },
        "costCenter": {
            "type": "string",
            "title": "Cost Center"
        },
        "dataClassification": {
            "type": "string",
            "enum": ["public", "internal", "confidential"],
            "title": "Data Classification"
        }
    },
    "required": ["team"]
}
""";

ApiCenterMetadataSchemaData schemaData = new ApiCenterMetadataSchemaData
{
    Schema = jsonSchema,
    AssignedTo =
    {
        new MetadataAssignment
        {
            Entity = MetadataAssignmentEntity.Api,
            Required = true
        }
    }
};

ArmOperation<ApiCenterMetadataSchemaResource> operation = await schemas
    .CreateOrUpdateAsync(WaitUntil.Completed, "api-metadata", schemaData);
10. 列出和搜索 API
// List all APIs in a workspace
ApiCenterWorkspaceResource workspace = await client
    .GetApiCenterWorkspaceResource(workspaceResourceId)
    .GetAsync();

await foreach (ApiCenterApiResource api in workspace.GetApiCenterApis().GetAllAsync())
{
    Console.WriteLine($"API: {api.Data.Title}");
    Console.WriteLine($"  Kind: {api.Data.Kind}");
    Console.WriteLine($"  Stage: {api.Data.LifecycleStage}");
    
    // List versions
    await foreach (ApiCenterApiVersionResource version in api.GetApiCenterApiVersions().GetAllAsync())
    {
        Console.WriteLine($"  Version: {version.Data.Title}");
    }
}

// List environments
await foreach (ApiCenterEnvironmentResource env in workspace.GetApiCenterEnvironments().GetAllAsync())
{
    Console.WriteLine($"Environment: {env.Data.Title} ({env.Data.Kind})");
}

// List deployments
await foreach (ApiCenterDeploymentResource deployment in workspace.GetApiCenterDeployments().GetAllAsync())
{
    Console.WriteLine($"Deployment: {deployment.Data.Title}");
    Console.WriteLine($"  State: {deployment.Data.State}");
}

关键类型参考

类型用途
ApiCenterServiceResourceAPI Center 服务实例
ApiCenterWorkspaceResourceAPI 的逻辑分组
ApiCenterApiResource单个 API
ApiCenterApiVersionResourceAPI 的版本
ApiCenterApiDefinitionResourceAPI 规范(OpenAPI 等)
ApiCenterEnvironmentResource部署环境
ApiCenterDeploymentResourceAPI 在环境中的部署
ApiCenterMetadataSchemaResource自定义元数据架构
ApiKindrest、graphql、grpc、soap、webhook、websocket、mcp
ApiLifecycleStagedesign、development、testing、preview、production、deprecated、retired
ApiCenterEnvironmentKinddevelopment、testing、staging、production
ApiCenterDeploymentStateactive、inactive

最佳实践

  1. 使用工作区进行组织 — 按团队、领域或产品对 API 分组
  2. 使用元数据架构 — 定义用于治理的自定义属性
  3. 跟踪生命周期阶段 — 及时更新 API 状态(design → production → deprecated)
  4. 记录环境信息 — 包含入门说明和门户 URI
  5. 统一版本管理 — 对 API 版本采用语义化版本控制
  6. 导入规范 — 上传 OpenAPI/GraphQL 规范,以便发现 API
  7. 关联部署 — 将 API 关联到其运行时环境
  8. 使用托管标识 — 启用 SystemAssigned 标识,以实现安全集成

错误处理

using Azure;

try
{
    ArmOperation<ApiCenterApiResource> operation = await apis
        .CreateOrUpdateAsync(WaitUntil.Completed, "my-api", apiData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
    Console.WriteLine("API already exists with conflicting configuration");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Invalid request: {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Azure error: {ex.Status} - {ex.Message}");
}

相关 SDK

SDK用途安装
Azure.ResourceManager.ApiCenterAPI Center 管理(此 SDK)dotnet add package Azure.ResourceManager.ApiCenter
Azure.ResourceManager.ApiManagementAPI 网关和策略dotnet add package Azure.ResourceManager.ApiManagement

参考链接

资源URL
NuGet 程序包https://www.nuget.org/packages/Azure.ResourceManager.ApiCenter
API 参考https://learn.microsoft.com/dotnet/api/azure.resourcemanager.apicenter
产品文档https://learn.microsoft.com/azure/api-center/
GitHub 源代码https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/apicenter/Azure.ResourceManager.ApiCenter

适用场景

当需要执行概述中描述的工作流或操作时,可使用此技能。

限制

  • 仅当任务明确符合上述范围时,才使用此技能。
  • 不要将输出视为环境特定验证、测试或专家审查的替代品。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。

评论

支持 Markdown