Azure and the REST API

by ingvar 13. April 2011 21:09


In this post I’ll write about the interesting things i discovered when doing REST to Azure. And I’ll also post the code needed to; create a hosted server, created a new deplyment and upgrade an existing deployment.

The three most important findings for me was how to get meaningfull error messages when the web request failed. The right way to use Uri for some REST operations and the right way to encode service configuration files in the body of the request.

Documentation for the Azure REST API can be found here:


You need a certificate to identify you REST commands to Auzre.

You can create a new certificate by issuing this command:

makecert -r -pe -a sha1 -n CN=AzureMgmt -ss My “AzureMgmt.cer"

The file 'AzureMgmt.ce' that was created by this command should be added to your Azure subscribtion. You can do this through the Azure Management Portal.

Generic setup

Here is a generic setup for issuing REST operations. 

Edit (2011-04-13): Setting the request method to "POST" should only be done if there is a body to send, thanks to Christian Horsdal for pointing this out.

string requestUrl = "";
string certificatePath = "";
string headerVersion = "";
string requestBody = "";

HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(requestUrl, true));
httpWebRequest.ClientCertificates.Add(new X509Certificate2(certificatePath));
httpWebRequest.Headers.Add("x-ms-version", headerVersion);
httpWebRequest.ContentType = "application/xml";

if (!string.IsNullOrEmpty(requestBody))
   httpWebRequest.Method = "POST";
   byte[] requestBytes = Encoding.UTF8.GetBytes(requestBody);
   httpWebRequest.ContentLength = requestBytes.Length;

   using (Stream stream = httpWebRequest.GetRequestStream())
      stream.Write(requestBytes, 0, requestBytes.Length);

   using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
      Console.WriteLine("Response status code: " + httpWebResponse.StatusCode);       WriteRespone(httpWebResponse);
catch (WebException ex)
   Console.WriteLine("Response status code: " + ex.Status);

Here is the code for the WriteRepsonse method:

static void WriteRespone(WebResponse webResponse)
   using (Stream responseStream = webResponse.GetResponseStream())
      if (responseStream == null) return;

      using (StreamReader reader = new StreamReader(responseStream))
         Console.WriteLine("Response output:");

The three variables; requestUrl, headerVersion and requestBody) are the only things you need to change to do any REST operation. 

The certificatePath variable is the same for all operations, it just need to be the path to your certificate file. 

The requestUrl variable is constructed to match the specific REST operation. See the the documentation for the different REST operations here [].

The headerVersion varies from operation to operation. Some operations has the same version. You can find the correct version in the documentation.

The requestBody is a small XML document. Not all operations needs a body and this is handled by the generic code above. See the documentation [] if the body is needed and if it is, how its constructed.


Important findings

Here is a short list of the problems I ran into when doing REST operations and the solutions to them:

  • WebException.Response.GetResponseStream() is your friend! When a operation fails with an exception and the error code 400, reading the WebExceptions response stream can help you finding the reason why.
  • The Uri constructor should have dontEscape=false for the request URL. If this is not the case, REST operations like Upgrade Deployment fails.
  • The ordering of the elements in the body matters, it is XML, so not so supprising.
  • If a Azure deployment package is needed, this should be located in a blob store. This is also documented in the documentation.
  • If an Azure service configuration is needed, this should be read as a string and base64 encoded like i did in the code. My first try i read the file as byte (File.ReadBytes) but this made the operation fail.


Create Hosted Service Example

Here is the value of the needed three variables:

string requestUrl = "<subscription-id>/services/hostedservices";
string headerVersion = "2010-10-28";
string requestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
   "<CreateHostedService xmlns=\"\">" +
      "<ServiceName>myservicename</ServiceName>" +
      "<Label>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("myservicename")) + "</Label>" +
      "<Location>North Central US</Location>" +

Create Deployment Example

Here is the value of the needed three variables:

string requestUrl = "<subscription-id>/services/hostedservices/myservicename/deploymentslots/staging";
string headerVersion = "2009-10-01";
string requestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
   "<CreateDeployment xmlns=\"\">" +
      "<Name>mydeployment</Name>" +
      "<PackageUrl></PackageUrl>" +
      "<Label>" +
      Convert.ToBase64String(Encoding.UTF8.GetBytes("mydeployment")) +
      "</Label>" +
      "<Configuration>" +
         File.ReadAllText(@"C:\MyServiceConfiguration.cscfg"))) +
      "</Configuration>" +
      "<StartDeployment>true</StartDeployment>" +

Upgrade Deployment Example

Here is the value of the needed three variables:

string requestUrl = "<subscription-id>/services/hostedservices/myservicename/deploymentslots/staging/?comp=upgrade";
string headerVersion = "2009-10-01";
string requestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
   "<UpgradeDeployment xmlns=\"\">" +
      "<PackageUrl></PackageUrl>" +
      "<Configuration>" +
            File.ReadAllText(@"C:\MyServiceConfiguration.cscfg"))) +
      "</Configuration>" + "<Mode>auto</Mode>" +
      Convert.ToBase64String(Encoding.UTF8.GetBytes("mydeployment")) + 
      "</Label>" +


.NET | Azure | C#

Comments (3) -

Christian Horsdal
Christian Horsdal Denmark
4/14/2011 12:02:43 PM #

I n the first code snippet you set

httpWebRequest.Method = "POST";

is that always the case? -if so that's not exactly RESTful.

ingvar Denmark
4/14/2011 12:25:56 PM #

I pretty sure its needed when there is a body (requestBod) to send. Just for the fun of it i tried with PUT and GET and got the following errors:
PUT: ProtocolError
GET: Cannot send a content-body with this verb-type.

But for operations without any body, POST will actually make it fail. Thx for the input Smile

Christian Horsdal
Christian Horsdal Denmark
4/14/2011 1:29:46 PM #

Right, and in your cases do actually want to post something up to Azure, so that makes sense in REST terms.

Pingbacks and trackbacks (1)+

About the author

Martin Ingvar Kofoed Jensen

Architect and Senior Developer at Composite on the open source project Composite C1 - C#/4.0, LINQ, Azure, Parallel and much more!

Follow me on Twitter

Read more about me here.

Read press and buzz about my work and me here.

Stack Overflow

Month List