option
MaisonMaison Skill DevOps et CI/CD azure-mgmt-apimanagement-dotnet

azure-mgmt-apimanagement-dotnet

microsoft/skills microsoft/skills

Gérez les services Azure API Management, les API, les produits, les abonnements, les stratégies, les utilisateurs et les passerelles à l’aide du SDK de gestion .NET.

...Développer tout
0
Heure mise à jour 16 septembre 2026

Azure.ResourceManager.ApiManagement (.NET)

Kit SDK du plan de gestion pour le provisionnement et la gestion des ressources Azure API Management via Azure Resource Manager.

⚠️ Plan de gestion vs plan de données

  • Ce SDK (Azure.ResourceManager.ApiManagement) : Créer des services, des API, des produits, des abonnements, des stratégies, des utilisateurs, des groupes
  • Plan de données : Appels d'API directs vers les points de terminaison de votre passerelle APIM

Installation

dotnet add package Azure.ResourceManager.ApiManagement
dotnet add package Azure.Identity

Version actuelle : v1.3.0

Variables d'environnement

AZURE_SUBSCRIPTION_ID=<your-subscription-id> # Requis : ID d'abonnement Azure
AZURE_TOKEN_CREDENTIALS=prod  # Requis uniquement si DefaultAzureCredential est utilisé en production
AZURE_TENANT_ID=<tenant-id> # Pour l'authentification par principal de service (facultatif)
AZURE_CLIENT_ID=<client-id> # Pour l'authentification par principal de service (facultatif)
AZURE_CLIENT_SECRET=<client-secret> # Pour l'authentification par principal de service (facultatif)
</client-secret></client-id></tenant-id></your-subscription-id>

Authentification

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApiManagement;

// Développement local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou utiliser un identifiant spécifique directement en production :
// Voir https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var armClient = new ArmClient(credential);

// Obtenir l'abonnement
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var subscription = armClient.GetSubscriptionResource(
    new ResourceIdentifier($"/subscriptions/{subscriptionId}"));
</specific_credential>

Hiérarchie des ressources

ArmClient
└── SubscriptionResource
    └── ResourceGroupResource
        └── ApiManagementServiceResource
            ├── ApiResource
            │   ├── ApiOperationResource
            │   │   └── ApiOperationPolicyResource
            │   ├── ApiPolicyResource
            │   ├── ApiSchemaResource
            │   └── ApiDiagnosticResource
            ├── ApiManagementProductResource
            │   ├── ProductApiResource
            │   ├── ProductGroupResource
            │   └── ProductPolicyResource
            ├── ApiManagementSubscriptionResource
            ├── ApiManagementPolicyResource
            ├── ApiManagementUserResource
            ├── ApiManagementGroupResource
            ├── ApiManagementBackendResource
            ├── ApiManagementGatewayResource
            ├── ApiManagementCertificateResource
            ├── ApiManagementNamedValueResource
            └── ApiManagementLoggerResource

Flux de travail principal

1. Créer un service API Management

using Azure.ResourceManager.ApiManagement;
using Azure.ResourceManager.ApiManagement.Models;

// Obtenir le groupe de ressources
var resourceGroup = await subscription
    .GetResourceGroupAsync("my-resource-group");

// Définir le service
var serviceData = new ApiManagementServiceData(
    location: AzureLocation.EastUS,
    sku: new ApiManagementServiceSkuProperties(
        ApiManagementServiceSkuType.Developer, 
        capacity: 1),
    publisherEmail: "[email protected]",
    publisherName: "Contoso");

// Créer le service (opération de longue durée - peut prendre plus de 30 minutes)
var serviceCollection = resourceGroup.Value.GetApiManagementServices();
var operation = await serviceCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-apim-service",
    serviceData);

ApiManagementServiceResource service = operation.Value;

2. Créer une API

var apiData = new ApiCreateOrUpdateContent
{
    DisplayName = "My API",
    Path = "myapi",
    Protocols = { ApiOperationInvokableProtocol.Https },
    ServiceUri = new Uri("https://backend.contoso.com/api")
};

var apiCollection = service.GetApis();
var apiOperation = await apiCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-api",
    apiData);

ApiResource api = apiOperation.Value;

3. Créer un produit

var productData = new ApiManagementProductData
{
    DisplayName = "Starter",
    Description = "Niveau débutant avec accès limité",
    IsSubscriptionRequired = true,
    IsApprovalRequired = false,
    SubscriptionsLimit = 1,
    State = ApiManagementProductState.Published
};

var productCollection = service.GetApiManagementProducts();
var productOperation = await productCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "starter",
    productData);

ApiManagementProductResource product = productOperation.Value;

// Ajouter l'API au produit
await product.GetProductApis().CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-api");

4. Créer un abonnement

var subscriptionData = new ApiManagementSubscriptionCreateOrUpdateContent
{
    DisplayName = "My Subscription",
    Scope = $"/products/{product.Data.Name}",
    State = ApiManagementSubscriptionState.Active
};

var subscriptionCollection = service.GetApiManagementSubscriptions();
var subOperation = await subscriptionCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-subscription",
    subscriptionData);

ApiManagementSubscriptionResource subscription = subOperation.Value;

// Obtenir les clés d'abonnement
var keys = await subscription.GetSecretsAsync();
Console.WriteLine($"Clé principale : {keys.Value.PrimaryKey}");

5. Définir la stratégie de l'API

var policyXml = @"
<policies><inbound><rate-limit></rate-limit><set-header><value>CustomValue</value></set-header><base></base></inbound><backend><base></base></backend><outbound><base></base></outbound><on-error><base></base></on-error></policies>";

var policyData = new PolicyContractData
{
    Value = policyXml,
    Format = PolicyContentFormat.Xml
};

await api.GetApiPolicy().CreateOrUpdateAsync(
    WaitUntil.Completed,
    policyData);

6. Sauvegarde et restauration

// Sauvegarde
var backupParams = new ApiManagementServiceBackupRestoreContent(
    storageAccount: "mystorageaccount",
    containerName: "apim-backups",
    backupName: "backup-2024-01-15")
{
    AccessType = StorageAccountAccessType.SystemAssignedManagedIdentity
};

await service.BackupAsync(WaitUntil.Completed, backupParams);

// Restauration
await service.RestoreAsync(WaitUntil.Completed, backupParams);

Référence des types clés

TypeObjectif
`ArmClient`Point d'entrée pour toutes les opérations ARM
`ApiManagementServiceResource`Représente une instance de service APIM
`ApiManagementServiceCollection`Collection pour les opérations CRUD des services
`ApiResource`Représente une API
`ApiManagementProductResource`Représente un produit
`ApiManagementSubscriptionResource`Représente un abonnement
`ApiManagementPolicyResource`Stratégie au niveau du service
`ApiPolicyResource`Stratégie au niveau de l'API
`ApiManagementUserResource`Représente un utilisateur
`ApiManagementGroupResource`Représente un groupe
`ApiManagementBackendResource`Représente un service backend
`ApiManagementGatewayResource`Représente une passerelle auto-hébergée

Types de SKU

SKUObjectifCapacité
`Developer`Développement/test (pas de SLA)1
`Basic`Production de niveau entrée1-2
`Standard`Charges de travail moyennes1-4
`Premium`Haute disponibilité, multi-région1-12 par région
`Consumption`Sans serveur, paiement à l'appelN/A

Meilleures pratiques

  1. Utiliser WaitUntil.Completed pour les opérations qui doivent se terminer avant de poursuivre
  2. Utiliser WaitUntil.Started pour les opérations de longue durée comme la création de services (plus de 30 min)
  3. Toujours utiliser DefaultAzureCredential — ne jamais coder en dur les clés
  4. Gérer RequestFailedException pour les erreurs de l'API ARM
  5. Utiliser CreateOrUpdateAsync pour les opérations idempotentes
  6. Naviguer dans la hiérarchie via les méthodes Get* (par ex. service.GetApis())
  7. Format de stratégie — Utiliser le format XML pour les stratégies ; le JSON est également pris en charge
  8. Création de service — Le SKU Developer est le plus rapide pour les tests (environ 15-30 min)

Gestion des erreurs

using Azure;

try
{
    var operation = await serviceCollection.CreateOrUpdateAsync(
        WaitUntil.Completed, serviceName, serviceData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
    Console.WriteLine("Le service existe déjà");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Requête incorrecte : {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erreur ARM : {ex.Status} - {ex.ErrorCode} : {ex.Message}");
}

Fichiers de référence

FichierQuand lire
references/service-management.mdCRUD des services, SKUs, réseau, sauvegarde/restauration
references/apis-operations.mdAPIs, opérations, schémas, versionnement
references/products-subscriptions.mdProduits, abonnements, contrôle d'accès
references/policies.mdModèles de stratégie XML, étendues, stratégies courantes

Ressources connexes

RessourceObjectif
Documentation API ManagementDocumentation officielle Azure
Référence des stratégiesRéférence complète des stratégies
Référence du kit SDKRéférence de l'API .NET
Voir sur GitHub
---
name: azure-mgmt-apimanagement-dotnet
description: Manage Azure API Management services, APIs, products, subscriptions, policies, users, and gateways using the .NET management plane SDK.
license: MIT
---

# Azure.ResourceManager.ApiManagement (.NET)

Management plane SDK for provisioning and managing Azure API Management resources via Azure Resource Manager.

> **⚠️ Management vs Data Plane**
> - **This SDK (Azure.ResourceManager.ApiManagement)**: Create services, APIs, products, subscriptions, policies, users, groups
> - **Data Plane**: Direct API calls to your APIM gateway endpoints

## Installation

```bash
dotnet add package Azure.ResourceManager.ApiManagement
dotnet add package Azure.Identity
```

**Current Version**: v1.3.0

## Environment Variables

```bash
AZURE_SUBSCRIPTION_ID=<your-subscription-id> # Required: Azure subscription ID
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production
AZURE_TENANT_ID=<tenant-id> # For service principal auth (optional)
AZURE_CLIENT_ID=<client-id> # For service principal auth (optional)
AZURE_CLIENT_SECRET=<client-secret> # For service principal auth (optional)
```

## Authentication

```csharp
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApiManagement;

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var armClient = new ArmClient(credential);

// Get subscription
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var subscription = armClient.GetSubscriptionResource(
    new ResourceIdentifier($"/subscriptions/{subscriptionId}"));
```

## Resource Hierarchy

```
ArmClient
└── SubscriptionResource
    └── ResourceGroupResource
        └── ApiManagementServiceResource
            ├── ApiResource
            │   ├── ApiOperationResource
            │   │   └── ApiOperationPolicyResource
            │   ├── ApiPolicyResource
            │   ├── ApiSchemaResource
            │   └── ApiDiagnosticResource
            ├── ApiManagementProductResource
            │   ├── ProductApiResource
            │   ├── ProductGroupResource
            │   └── ProductPolicyResource
            ├── ApiManagementSubscriptionResource
            ├── ApiManagementPolicyResource
            ├── ApiManagementUserResource
            ├── ApiManagementGroupResource
            ├── ApiManagementBackendResource
            ├── ApiManagementGatewayResource
            ├── ApiManagementCertificateResource
            ├── ApiManagementNamedValueResource
            └── ApiManagementLoggerResource
```

## Core Workflow

### 1. Create API Management Service

```csharp
using Azure.ResourceManager.ApiManagement;
using Azure.ResourceManager.ApiManagement.Models;

// Get resource group
var resourceGroup = await subscription
    .GetResourceGroupAsync("my-resource-group");

// Define service
var serviceData = new ApiManagementServiceData(
    location: AzureLocation.EastUS,
    sku: new ApiManagementServiceSkuProperties(
        ApiManagementServiceSkuType.Developer, 
        capacity: 1),
    publisherEmail: "[email protected]",
    publisherName: "Contoso");

// Create service (long-running operation - can take 30+ minutes)
var serviceCollection = resourceGroup.Value.GetApiManagementServices();
var operation = await serviceCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-apim-service",
    serviceData);

ApiManagementServiceResource service = operation.Value;
```

### 2. Create an API

```csharp
var apiData = new ApiCreateOrUpdateContent
{
    DisplayName = "My API",
    Path = "myapi",
    Protocols = { ApiOperationInvokableProtocol.Https },
    ServiceUri = new Uri("https://backend.contoso.com/api")
};

var apiCollection = service.GetApis();
var apiOperation = await apiCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-api",
    apiData);

ApiResource api = apiOperation.Value;
```

### 3. Create a Product

```csharp
var productData = new ApiManagementProductData
{
    DisplayName = "Starter",
    Description = "Starter tier with limited access",
    IsSubscriptionRequired = true,
    IsApprovalRequired = false,
    SubscriptionsLimit = 1,
    State = ApiManagementProductState.Published
};

var productCollection = service.GetApiManagementProducts();
var productOperation = await productCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "starter",
    productData);

ApiManagementProductResource product = productOperation.Value;

// Add API to product
await product.GetProductApis().CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-api");
```

### 4. Create a Subscription

```csharp
var subscriptionData = new ApiManagementSubscriptionCreateOrUpdateContent
{
    DisplayName = "My Subscription",
    Scope = $"/products/{product.Data.Name}",
    State = ApiManagementSubscriptionState.Active
};

var subscriptionCollection = service.GetApiManagementSubscriptions();
var subOperation = await subscriptionCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-subscription",
    subscriptionData);

ApiManagementSubscriptionResource subscription = subOperation.Value;

// Get subscription keys
var keys = await subscription.GetSecretsAsync();
Console.WriteLine($"Primary Key: {keys.Value.PrimaryKey}");
```

### 5. Set API Policy

```csharp
var policyXml = @"
<policies>
    <inbound>
        <rate-limit calls=""100"" renewal-period=""60"" />
        <set-header name=""X-Custom-Header"" exists-action=""override"">
            <value>CustomValue</value>
        </set-header>
        <base />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>";

var policyData = new PolicyContractData
{
    Value = policyXml,
    Format = PolicyContentFormat.Xml
};

await api.GetApiPolicy().CreateOrUpdateAsync(
    WaitUntil.Completed,
    policyData);
```

### 6. Backup and Restore

```csharp
// Backup
var backupParams = new ApiManagementServiceBackupRestoreContent(
    storageAccount: "mystorageaccount",
    containerName: "apim-backups",
    backupName: "backup-2024-01-15")
{
    AccessType = StorageAccountAccessType.SystemAssignedManagedIdentity
};

await service.BackupAsync(WaitUntil.Completed, backupParams);

// Restore
await service.RestoreAsync(WaitUntil.Completed, backupParams);
```

## Key Types Reference

| Type | Purpose |
|------|---------|
| `ArmClient` | Entry point for all ARM operations |
| `ApiManagementServiceResource` | Represents an APIM service instance |
| `ApiManagementServiceCollection` | Collection for service CRUD |
| `ApiResource` | Represents an API |
| `ApiManagementProductResource` | Represents a product |
| `ApiManagementSubscriptionResource` | Represents a subscription |
| `ApiManagementPolicyResource` | Service-level policy |
| `ApiPolicyResource` | API-level policy |
| `ApiManagementUserResource` | Represents a user |
| `ApiManagementGroupResource` | Represents a group |
| `ApiManagementBackendResource` | Represents a backend service |
| `ApiManagementGatewayResource` | Represents a self-hosted gateway |

## SKU Types

| SKU | Purpose | Capacity |
|-----|---------|----------|
| `Developer` | Development/testing (no SLA) | 1 |
| `Basic` | Entry-level production | 1-2 |
| `Standard` | Medium workloads | 1-4 |
| `Premium` | High availability, multi-region | 1-12 per region |
| `Consumption` | Serverless, pay-per-call | N/A |

## Best Practices

1. **Use `WaitUntil.Completed`** for operations that must finish before proceeding
2. **Use `WaitUntil.Started`** for long operations like service creation (30+ min)
3. **Always use `DefaultAzureCredential`** — never hardcode keys
4. **Handle `RequestFailedException`** for ARM API errors
5. **Use `CreateOrUpdateAsync`** for idempotent operations
6. **Navigate hierarchy** via `Get*` methods (e.g., `service.GetApis()`)
7. **Policy format** — Use XML format for policies; JSON is also supported
8. **Service creation** — Developer SKU is fastest for testing (~15-30 min)

## Error Handling

```csharp
using Azure;

try
{
    var operation = await serviceCollection.CreateOrUpdateAsync(
        WaitUntil.Completed, serviceName, serviceData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
    Console.WriteLine("Service already exists");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Bad request: {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"ARM Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
```

## Reference Files

| File | When to Read |
|------|--------------|
| [references/service-management.md](references/service-management.md) | Service CRUD, SKUs, networking, backup/restore |
| [references/apis-operations.md](references/apis-operations.md) | APIs, operations, schemas, versioning |
| [references/products-subscriptions.md](references/products-subscriptions.md) | Products, subscriptions, access control |
| [references/policies.md](references/policies.md) | Policy XML patterns, scopes, common policies |

## Related Resources

| Resource | Purpose |
|----------|---------|
| [API Management Documentation](https://learn.microsoft.com/en-us/azure/api-management/) | Official Azure docs |
| [Policy Reference](https://learn.microsoft.com/en-us/azure/api-management/api-management-policies) | Complete policy reference |
| [SDK Reference](https://learn.microsoft.com/en-us/dotnet/api/azure.resourcemanager.apimanagement) | .NET API reference |

Installer azure-mgmt-apimanagement-dotnet

Téléchargez et extrayez les fichiers de compétences dans votre répertoire .claude/skills/.

Télécharger le ZIP

Clonez le dépôt et copiez les fichiers de compétence dans votre projet.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-mgmt-apimanagement-dotnet # Copy SKILL.md to your .claude/skills/ directory

Copier Copier
Configuration rapide: Copiez le dossier de la compétence dans .claude/skills/ Claude détectera et utilisera automatiquement la compétence

Compétences similaires

base44-cli
Heure mise à jour 29 juin 2026
klingai-upgrade-migration
Heure mise à jour 3 juillet 2026
Railway CLI Management
Heure mise à jour 2 juillet 2026
Verification &amp; Quality Assurance
Heure mise à jour 29 juin 2026
OR