How to create an API in APIM programmatically using Azure SDK for .Net
Published Apr 12 2022 10:14 PM 9,471 Views
Microsoft

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.

  • ARM template
  • Powershell or Azure CLI
  • Bicep
  • Visual Studio Code
  • .Net SDK

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.

  1. Authentication- grant permission for your API client to access APIM.
  2. API client creation - create an API client to send HTTP requests.
  3. API creation – set the API properties & send the HTTP request.

This article will provide friendly guidance for new APIM users.

 

Prerequisite:

  • Microsoft Visual Studio 2019. Visual Studio 2019, including the free community edition, can be downloaded here.
  • Microsoft Azure subscription. To use Azure services, including APIM and App registration, you need a subscription.
  • Create an APIM service. You could also use the C# code to create a new APIM instance. However, this article focuses on creating a new API via .net SDK, so we suppose you already have an APIM instance. If you don’t have an existing APIM instance, you can create it by following instructions from this article.

 

Package Installation:

1. In visual studio, create a console application: start visual studio 2019 ->select create a new project -> select Console Application 

 

Hildat_0-1649782760765.png

 

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.IdentityModel.Clients.ActiveDirectory package.

 

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 5.2.9

 

 

Authentication:

 

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.

Hildat_0-1649778179258.png

e. On the app Overview page, find the Application(client) ID value and record it for later.

Hildat_1-1649778179270.png

 

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.

Hildat_2-1649778179282.png

 

Step3. Grant delegated permission to your Application in APIM Access control (IAM)

  1. Navigate to your APIM.
  2. Under Access control (IAM), select Add -> Add role assignment.
  3. Assign a role to the above created application, which should be able to create or update API in this APIM, such as APIM service contributor.

Hildat_3-1649778179292.png

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.

Hildat_4-1649778179304.png

 

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

 

 

APIM Client creation:

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]";

 

 

Create API

 

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.

 

Hildat_0-1649780310948.png

 

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);

 

 

Test result:

In the Azure portal, you can find the API has been created successfully.

Hildat_10-1649778179347.png

 

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);

        }
    }
}

 

 

 

 

 

 

 

 

 

 

2 Comments
Co-Authors
Version history
Last update:
‎Apr 12 2022 10:17 AM
Updated by: