Azure API Management (APIM) helps organizations publish APIs to external, partner, and internal developers to unlock the potential of their data and services.
It is easy for us to add the API manually in the Azure portal, or there are several options for you to create the API programmatically.
In this article, we will provide a sample for creating an API via Azure SDK for .Net – APIManagement. and will use the latest preview package: Microsoft.Azure.Management.ApiManagement v8.0.0-preview
The complete code is shown at the end of this article.
To implement importing an API in APIM by .net SDK, the primary method is to create an API client to call REST API. It is like what we do in other ways. Basically, we need an API client and call the Create or Update REST API.
Considering a service credential is needed when the API client interacts with Azure resources, we need first to create an App on behalf of the API client and then grant permission in APIM.
In summary, there are mainly 3 steps to creating an API via.Net SDK.
This article will provide friendly guidance for new APIM users.
1. In visual studio, create a console application: start visual studio 2019 ->select create a new project -> select Console Application
2.select Tools > NuGet Package Manager > Package Manager Console from the menu.
3. Run the following command to install the Microsoft.Azure.Management.ApiManagement package:
Install-Package Microsoft.Azure.Management.ApiManagement -Version 8.0.0-preview
4. Run the below command to install Microsoft.
Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 5.2.9
To construct an API client, Credentials is required for the client to connect to Azure. This section will introduce how to get the value of servicecredential.
Step1. Register an application in Azure AD to represent the API client.
a. In the Azure portal, search for and select App registrations.
b. Select New registration.
c. In the Register an application page, enter your application’s registration information.
-Name. You can select a meaningful name for this app. In my sample, I use APIM-client.
-Select an option that suits your scenario in the Supported account types section.
-Leave the Redirect URI section empty.
d. Click Register to create the application.
e. On the app Overview page, find the Application(client) ID value and record it for later.
Step2. Create a client secret for this application to use in a subsequent step.
a. Under the Manage section of the side menu, select Certificates&secrets.
b. Under Client secrets, select New client secret.
c. In the Add a client secret page, enter the Description and the expiration time.
d. Click on Add.
e. You can find the client secret Value in the portal, and you need to record it for later use.
Step3. Grant delegated permission to your Application in APIM Access control (IAM)
If you want to understand the permission for a different role, you can click on view, and all permissions under the selected role will be displayed.
Now, we can use the above created application to get access to APIM. To get the value of service credentials, we need the Azure tenant ID, the above created application client ID and client seceret value.
The sample code below provides how to get the servicecredential token and initial an API client.
//create service credentials
public class AzureApiManagementServiceCredentials : ServiceClientCredentials
{
private readonly string _tenantId;
private readonly string _clientId;
private readonly string _clientSecret;
public AzureApiManagementServiceCredentials(string tenantId, string clientId, string clientSecret)
{
_tenantId = tenantId;
_clientId = clientId;
_clientSecret = clientSecret;
}
public override void InitializeServiceClient<T>(ServiceClient<T> client)
{
var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{_tenantId}");
var credential = new ClientCredential(clientId: _clientId, clientSecret: _clientSecret);
var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
if (result == null)
{
throw new InvalidOperationException($"Failed to obtain the JWT token for Azure API Management Rest connection for user {_clientId}");
}
client.HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
}
}
// ref github-https://github.com/Azure/azure-sdk-for-net/issues/4727
After getting the value of servicecredential, we can create an API client by using ApiManagementClient Class.
Don’t forget to assign your subscription ID to the subscriptionId properties.
string tenantId = "[Azure tenant ID]";
string clientId = "[application client ID]";
string clientSecret = "[application client secret]";
//construct client
var serviceCredentials = new AzureApiManagementServiceCredentials(tenantId, clientId, clientSecret);
apiClient = new ApiManagementClient(serviceCredentials);
apiClient.SubscriptionId = "[APIM subscription ID]";
Step 1. APIManagementmodel Construction – set API properties
Similar to putting API properties in the Request body when creating API via Create or Update REST API, we need to construct an API parameter model to define your API via using ApiCreateOrUpdateParameter Class.
You could set your API properties in this part—for example, API display name, API path, and protocols.
Below is the sample. I just created an open API called “test-httpbin2”.
apiProperties = new ApiCreateOrUpdateParameter();
apiProperties.DisplayName = "test-httpbin2";
apiProperties.Path = "testhttpbin2";
apiProperties.ApiType = "http";
var protocols = new List<string>();
protocols.Add("http");
protocols.Add("https");
apiProperties.Protocols = protocols;
Also, you could customize your API by adding the value for the properties below. For more details, please see this document.
Step 2. Send Request to create API in APIM
Set the value of your resource group name, APIM service name, and apiID.
string resourceGroupName = "start";
string APIMserviceName = "apim-study-Hilda";
string apiID = "api01";
Now we can use the APIM client to send an HTTP request to create our API
var response = await apiClient.Api.CreateOrUpdateAsync(resourceGroupName, APIMserviceName, apiID, apiProperties);
In the Azure portal, you can find the API has been created successfully.
The complete code is shown below:
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.Models;
using Microsoft.Rest;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace createAPI
{
//create service credentials
public class AzureApiManagementServiceCredentials : ServiceClientCredentials
{
private readonly string _tenantId;
private readonly string _clientId;
private readonly string _clientSecret;
public AzureApiManagementServiceCredentials(string tenantId, string clientId, string clientSecret)
{
_tenantId = tenantId;
_clientId = clientId;
_clientSecret = clientSecret;
}
public override void InitializeServiceClient<T>(ServiceClient<T> client)
{
var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{_tenantId}");
var credential = new ClientCredential(clientId: _clientId, clientSecret: _clientSecret);
var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
if (result == null)
{
throw new InvalidOperationException($"Failed to obtain the JWT token for Azure API Management Rest connection for user {_clientId}");
}
client.HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
}
}
// ref github-https://github.com/Azure/azure-sdk-for-net/issues/4727
class Program
{
//API client
static ApiManagementClient apiClient;
//APIManagementmodel, for request body
static ApiCreateOrUpdateParameter apiProperties;
static async Task Main()
{
string tenantId = "[Azure tenant ID]";
string clientId = "[application client ID]";
string clientSecret = "[application client secret]";
//construct client
var serviceCredentials = new AzureApiManagementServiceCredentials(tenantId, clientId, clientSecret);
apiClient = new ApiManagementClient(serviceCredentials);
apiClient.SubscriptionId = "[APIM subscription ID]";
//construct api properties <-
apiProperties = new ApiCreateOrUpdateParameter();
apiProperties.DisplayName = "[API Name]";
apiProperties.Path = "[API path]";
apiProperties.ApiType = "[API type]";
var protocols = new List<string>();
protocols.Add("http");
protocols.Add("https");
apiProperties.Protocols = protocols;
//create api
string resourceGroupName = "[resource group name]";
string APIMserviceName = "[APIM service name]";
string apiID = "[API ID]";
var response = await apiClient.Api.CreateOrUpdateAsync(resourceGroupName, APIMserviceName, apiID, apiProperties);
}
}
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.