api management rest api

Working with the API Management REST API using .NET

Published on : Apr 4, 2017

Category : Microsoft Azure

steef

Author

API Management is one of the Azure Products categorized in the Enterprise Integration, which can easily be provisioned (set up) through the Azure Portal. You can choose based on your requirements a pricing tier (developer, standard and premium, for the different tiers see API Management Pricing and summary in the diagram below). azure api management pricing The pricing is based on consumption plan and prices above are monthly based. Once provisioned, you have the ability to publish API’s more securely through the use policies, and more reliable and scalable (see API Management).
You can download this article as a PDF document Download now.

REST API

Like many azure services, API Management has a REST API, which provides means to perform operations on selected entities, such as users, groups, products, and subscriptions. And to work with the REST API there are a few aspects you need to be aware of:
  • Enable access to the REST API
  • Default media type
  • Authentication
  • Base URL
  • Version Query Parameter
  • Entities

Enable access to the REST API

To leverage the REST API functionality, you need to enable access to it through the Azure Portal, select the Publisher portal. A new browser dialog will appear and here you select the Security menu item. enable api management rest api checkbox Here you have to check the Enable API Management REST API checkbox. You’ll then see credentials, which are necessary to generate a shared access token. This token is required in the Authorization header of each request to the API Management REST API. And the API Management REST API checkbox has to be checked, because if it is not checked, calls made to the REST API for that service instance (enterprisea) will fail. api management rest api access token Through the portal, you generate a token with a maximum time to live of 30 days to include in your request header. However, in this post we’ll programmatically generate the token.

Default media type

For each request to the API Management REST API the media type by default is application/json. However, for some operations like export the API definition the media type is application/vnd.swagger.doc+json.

Authentication

As described earlier the credentials are mandatory for generation of a shared access token, which can be generated manually in the API Management Instance Security tab. Yet you can programmatically generate it by the following code:
static private string CreateSharedAccessToken(string id, string key, DateTime expiry)
        {
            using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key)))
            {
                string dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);
                string x = string.Format("{0}\n{1}", id, expiry.ToString("O", CultureInfo.InvariantCulture));
                var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
                var signature = Convert.ToBase64String(hash);
                string encodedToken = string.Format("uid={0}&ex={1:o}&sn={2}", id, expiry, signature);
                return encodedToken;
            }
        }
The code above shows how the shared access token is generated based on the given id i.e. identifier of your API management instance, the belonging key and date time to set the expiry.

Base URL

A call (request) to API Management REST API is basically a call to an endpoint, which is an address. The base of that address is: https://{servicename} management.azure-api.net. The service name is the name of your API Management instance. A call to list operations, for instance looks like: https://enterprisea.management.azure-api.net/apis/57efb2129f86d70079040001/operations/57efb2129f86d70079080004?api-version=2015-09-15 The address starts with the base followed by apis (entity), identifier of the API, operations, identifier of the operation followed by api-version.
You can download this article as a PDF document Download now.

API Version

Each operation of the API Management REST API expects an api-version query parameter (see previous paragraph). The format of the parameter is YYYY-MM-DD. The version (latest) is 2015-09-15. Note that the documentation mentions two previous versions: 2014-02-14-preview and 2014-02-14.

Entities

The API Management Entities you can operate on are:
  • API
  • Authorization server
  • Backend
  • Certificate
  • Group
  • Logger
  • Product
  • Property
  • Report
  • Subscription
  • Tenant
  • User
To perform REST API calls manually on the API Management instance is possible by using for instance postman. The steps to follow are:
  • Obtain the shared access token manually through the security tab in your API Management instance publisher portal.
  • Paste the token to Authorization Header of the request.
  • Set Content-Type in the Header of the request to application/json.
  • Select GET VERB.
  • Choose an operation for instance get a list of APIs (the entity is an API).
  • Set URL: https://{service name}.management.azure-api.net/apis?api-version=2015-09-15, the relative request Uri for the API entity is apis.
  • Hit Send.
rest api calls manually on api management instance To manually perform all kinds of operations on the REST API to retrieve information of your API Management instance can be cumbersome and time consuming. To save time you can programmatically access the REST API operations and render the outcome in a user interface for instance a forms application.

API Management Explorer

The API Management REST API can be accessed programmatically and wrapped around PowerShell script or .NET code. In the latter case a User Interface (UI) can be created to access the REST API through the .NET code. The API Management Explorer is a forms application, which provides a UI to explore APIS, its operations, policies and products from an API Management instance. You can connect to an API Management instance (service) and explore in a few seconds (clicks) the API’s present in an instance, what type of operation each API has, and what policies are associated with the operation and what products resides in the API Management instance. myeventapi window in api management explorer The above screenshot show the API Management Explorer connected an API Management Instance, showing the API(s), details, operations, policy, and products. The calls to REST API are made through the APIRestCall function, see code below.
private JObject APIRestCall(string resource, string format = "application/json", string method = "GET",string contentType = "application/json")
        {
            // If an Operation Call get the response status
            string operationsResponse = string.Empty;
 
            // Get the URL from the form.
            Uri requestUri = new Uri(BaseURL + resource);
 
            // Create the request and specify attributes of the request.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
 
            // Define the required headers to specify the API version and operation type.
            request.Method = method;
            request.Headers.Add("Authorization", SharedAccessSignature);
            //Accept header can be set to application/vnd.sun.wadl+xml, application/vnd.swagger.doc+json, or application/json;
            request.ContentType = contentType;
            request.Accept = format;
 
            HttpWebResponse response;
            HttpStatusCode responseStatus;
            JObject o = null;
 
            try
            {
                // Make the call using the web request.
                response = (HttpWebResponse)request.GetResponse();
                responseStatus = response.StatusCode;
 
                // If the response is NULL nothing to show
                if (response.ContentLength > 0)
                {
                    // Parse the web response.
                    Stream responseStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(responseStream);
 
                    // Show the output
                    string json = reader.ReadToEnd();
 
                    o = JObject.Parse(json);
 
                    // Cleanup
                    responseStream.Close();
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
 
            return o;
        }
The code above shows how the call to REST API of API Management is setup, which is similar to the call through Postman.

Considerations

The API Management Explorer is not fully implemented all the operations of each entity; however, it is available in the MSDN Code gallery to be extended or examined for education purposes. It will not be maintained, supported or updated in the future. It merely demonstrates how to programmatically leverage the API Management REST API through .NET code. The code can be used to create your own customizable explorer/management tool built in for instance MVC, with capabilities to compare multiple API Management instances, in case you have dev/test and production instances for API Management. The tool is a proof of concept type of project and intended to explore some of the API Management REST API entity’s operations.

Call to action

The API Management Explorer tool is available through the MSDN code gallery. You can download the tool and explore the functionality, refactor and extend it to your own needs. As for more resource see:  
You can download this article as a PDF document Download now.
[adrotate banner=”8″]