Blog
January 29, 2016 Marie H.

Python Authenticating with Azure REST API

Python Authenticating with Azure REST API

Photo by <a href="https://unsplash.com/@zulfugarkarimov?utm_source=cloudista&utm_medium=referral" target="_blank" rel="noopener">Zulfugar Karimov</a> on <a href="https://unsplash.com/?utm_source=cloudista&utm_medium=referral" target="_blank" rel="noopener">Unsplash</a>

The past few days I have been working on trying to wrap my head around Microsoft Azure’s Cloud Service REST API. I must say starting out I really was against all of the things they were doing (but I’m bias as a Linux person). But after actually sitting down and trying to read the documentation it was surprisingly easy to start working with Azure’s API.

Setup certificate

openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout test_cert.pem -out test_cert.pem
openssl x509 -inform pem -in test_cert.pem -outform der -out test_cert.cer

Upload certificate to Azure

  • Go to (Make sure you replace domain.com with your Microsoft Domain)
    https://manage.windowsazure.com/domain.com#Workspaces/AdminTasks/ListManagementCertificates

  • At the very bottom click Upload

  • Browse to the .cer file you just generated

  • Hit the checkmark(ok) button in the bottom right of the modal

Once this is done you can use the PEM file to authenticate with the Azure REST API.

Basic authentication

Updated 2026-03-20: print r.content updated to Python 3 syntax. Also note: the Azure Classic Management API (management.core.windows.net) used here is legacy — modern Azure uses the Resource Manager API at management.azure.com with OAuth2 tokens via azure-identity and azure-mgmt-compute.

Yes, I used Basic Authentication but in reality I used Certificate based authentication because that is all the Azure allows at this point and time. And yes… It returns XML… because when you’re Microsoft you can pretend its 1999 and not use Tokens or JSON.

#!/usr/bin/env python
import requests

# Variables for Authentication
subscription_id = ''
pem_file = 'test_cert.pem'

# Build URL
base_url = 'https://management.core.windows.net'
url = '{}/{}/services/hostedservices'.format(base_url, subscription_id)

# Microsoft Requires the x-ms-version header
# because its apparently 1999
headers = {
    'x-ms-version': '2015-04-01',
    'embed-detail': True,
}

# Authenticate to Azure
r = requests.get(url, cert=pem_file, headers=headers)
print(r.content.decode('utf-8'))

As I continue to dig into Azure’s API and hack around until I can at least do basic things like list which Virtual Machines I have and then Create, Stop and Delete VM’s I will be trying to continually provide what I will call “actual” documentation to their API.