How to manage Azure services through the Azure service Management REST API

Source: Internet
Author: User

Through this article you will learn:

What is the azure Service Management REST API

How to get a Microsoft Azure subscription number

How to obtain an Azure management certificate

How to call the Azure Service Management REST API

What is the azure Service Management REST API

The Azure Service Management Rest API (hereafter referred to as the Azure Rest API) is a set of rest APIs open to Microsoft that allows Azure users to manage not only the services running on Azure from the Azure portal site, You can also manage services on Azure through your own or other third-party programs.

One of the biggest benefits of rest-based rest API is that it is invoked with HTTP requests, allowing you to develop services and applications based on Azure service management in a variety of development languages and development tools. (including Microsoft's Azure PowerShell is also developed based on this API.)

All Azure REST APIs are encrypted via SSL and are invoked with an v3 certificate for interactive authentication.

At least two messages are required when you call the Azure REST API.

1. Microsoft Azure Subscription number.

2. The V3 certificate that exists in the Azure Certificate Management Service.

How to get a Microsoft Azure subscription number

Microsoft Azure Subscription Number (Subscription ID) is the user name that Microsoft Azure uses to identify users. It is a string of IDs, and each call to the Azure REST API contains the ID within the URL. This is how the Azure REST API identifies the user identity.

The way to get this ID is also simple:

1. Sign in to the Azure portal

2. Locate the settings option in the left sidebar click Open

3. Find the subscription ID for the account on the right, which is the subscription number for Azure, which is used when calling the Auzre REST API.

How to obtain an Azure management certificate

Azure Management certificate is a V3 certificate that is used to authenticate agents (such as Visual Studio Tools for Windows Azure or client applications that use the service management API) to manage subscription resources on behalf of the subscription owner. Azure Management certificates are uploaded to Azure and stored at the subscription level.

When you call the Azure REST API, you need to use a client certificate that is the same as the certificate in Auzre Certificate Manager to pass validation.

There are two ways to get this certificate

First: Create a certificate locally and upload it to azure

For a detailed procedure of this method, please refer to MSDN:

Create and upload a certificate for Azure

After the upload is complete, your Azure management certificate will be stored in the local machine "personal" certificate store.

You can use the thumbprint of this certificate to find the certificate.

1. Open the Azure Management page

2. Locate the settings option in the left sidebar click Open

3. Find the "Manage certificate" option in the right directory option and click Open

4. Find the certificate you uploaded by typing the name you uploaded and get its fingerprint

5. Get the Certificate object from the "personal" certificate store by fingerprint in the program

The code to get the certificate object in the code is as follows:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public static string CertificateThumbprint = "f70dee7fec7364a57c09f09811c7519bc4402c56";//通过上面第四步可以获得指纹的字符串。 public static X509Certificate2 Certificate;X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certificateStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = certificateStore.Certificates.Find( X509FindType.FindByThumbprint, CertificateThumbprint, false);if (certs.Count == 0) { Console.WriteLine("Can‘t find the certificate in your local computer."); Console.ReadKey(); return; } else { Certificate = certs[0]; }

  

Second: Obtain the management certificate by downloading the publishsettings file

1. Download the publishsettings file via the link below (login required to download)

Https://manage.windowsazure.com/publishsettings/index?client=vs&schemaversion=2.0&whr=azure.com

2. Open the file as text with the title of the user ID and the string after the Azure Management certificate is converted to BASE64.

3. Convert the Base64 string of this certificate into a certificate object.

The relevant code is as follows:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 private const string SettingsFilePath = @"{publish settings file path}";        private const string SubscriptionID = "{Subscription ID}";private static X509Certificate2 getCertificateBySubscriptionID(string settingsFilePath, string subscriptionID)        {            XElement xElement = XElement.Load(settingsFilePath);            var subscriptionElements = xElement.Descendants("Subscription");            var base64cer = subscriptionElements                .Where(e => e.Attribute("Id").Value.ToString() == subscriptionID)                .FirstOrDefault()                .Attribute("ManagementCertificate").Value.ToString();            return new X509Certificate2(Convert.FromBase64String(base64cer));        }

  

The first approach is that MSDN describes the methods in the documentation, but I personally think the second approach is more convenient and simpler, because using the second method, your program only needs to save the certificate as a string when it is running elsewhere, and if you use the first type, You will need to import the certificate into the certificate Manager on other machines, which can be very troublesome and sometimes there are some inexplicable errors.

How to call the Azure Service Management REST API

The way to invoke the API is to use HttpWebRequest to send HTTP requests

We can refer to the following sample documentation to make the call.

Http://msdn.microsoft.com/zh-cn/library/azure/hh264518.aspx

This example document lists the information needed to create a cloud storage account.

Below the request in this document we can get the URL of the sending request, as well as the method of the HTTP request.

Below the request Header We can get the required headers for the request

Note: It is noteworthy here that X-ms-version

X-ms-version

Necessary. Specifies the version of the action used for this request. The value for this header must be set to 2011-06-01 or later. For more information about version control headers, see Service Management versioning.

It is important to note that since the reference documentation is not updated very quickly, it is possible that the latest REST API for Azure is not already supported by the old version of X-ms-version, and it is recommended that you refer to service management versioning for direct access to the latest version.

Request Body An example is a request body that contains all the required and non-mandatory parameters, and the table lists whether each parameter must be, and what their functions and roles are.

The status code describes the status code returned by the response request. It is convenient for us to determine the success of the invocation operation when we get the response.

Finally, we can find sample code that calls the rest API in the sample code.

In this official example, there are many techniques for using the rest API, which are summarized as follows:

I. How to obtain a Certificate object using a program. (as already mentioned earlier in this article, you can replace it with a way to obtain management certificates by downloading the publishsettings file )

Two. How to create a public method that sends an HTTP request. (The Invokerequest method in the example)

Three. How to obtain the information returned by an HTTP request, including how to obtain the error information returned by the exception. You can refer to (the code in the last part of the Invokerequest method in the example)

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 try {     response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) {     // GetResponse throws a WebException for 4XX and 5XX status codes     response = (HttpWebResponse)ex.Response; }try {     statusCode = response.StatusCode;     if (response.ContentLength > 0)     {         using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))         {             responseBody = XDocument.Load(reader);         }     }    if (response.Headers != null)     {         requestId = response.Headers["x-ms-request-id"];     } } finally {     response.Close(); }if (!statusCode.Equals(expectedCode)) {     throw new ApplicationException(string.Format(         "Call to {0} returned an error:{1}Status Code: {2} ({3}):{1}{4}",         uri.ToString(),         Environment.NewLine,         (int)statusCode,         statusCode,         responseBody.ToString(SaveOptions.OmitDuplicateNamespaces))); }return requestId;

Four. How to get status information for an operation (refer to the Getoperationstates method)

Summarize:

Benefits of the Azure REST API:

The Azure Rest API is a rest service based on SOA development, and developers can use any development language that supports the HTTP protocol to develop programs based on that service.

Azure REST API Disadvantages:

Directly as with the example Azure REST API but its programming pattern is not like object-oriented programming, so when the invocation of reusability, and extensibility is not very strong, it is necessary for developers to build their own objects to increase the scalability.

(Fortunately, Microsoft developers have introduced a C # class library based on the REST API to make it easier for. NET developers to invoke the Azure Rest API indirectly in a way they are familiar with.) For details, please refer to:

Azure Management API takes advantage of Windows Azure Management Libraries to control Azure platform)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.