다음을 통해 공유


Azure API Management REST API using .NET

Introduction

API Management is an Azure Service you can provision 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). Once provisioned, you have the ability to publish API’s more securely through the use policies, and more reliable and scalable (see API Management).

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 i.e. the classic portal. Log into the Azure Portal and go to the classic portal, find your API management instance, and click Manage in the bottom bar. 

http://ultraimg.com/images/2016/11/01/xia3.md.png

In API Management instance, select Security and in the API tab you’ll see a check box “Enable API Management REST API”.

http://ultraimg.com/images/2016/11/01/xiWa.md.png

Once you have checked the API Management you’ll 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 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 will fail.

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.

http://ultraimg.com/images/2016/11/01/xiWU.md.png

Or 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;
            }
        }

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://steef.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.

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, see Authentication.
  • Paste the token to Authorization Header of the request.
  • Set Content-Type in the Header of the request.
  • 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.

http://ultraimg.com/images/2016/11/01/xiaH.md.png

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. 

http://ultraimg.com/images/2016/11/01/xiWW.md.png

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

Considerations

The API Management Explorer is not fully implements all the operations of each entity, however 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.

See Also