-2

I'm trying to make a POST request to Azure with the following code:

import requests

api_url = https://management.azure.com/subscriptions/subscription_id/resourcegroups/resourcegroup_id/providers/Microsoft.DataFactory/factories/datafactory_id/airflow/sync?api-version=2018-06-01"
todo = {
    "IntegrationRuntimeName": "Airflow",
    "LinkedServiceName": "LAIRFLOW",
    "StorageFolderPath": "airflow/dev/",
    "CopyFolderStructure": "true",
    "Overwrite": "true",
}
response = requests.post(api_url, json=todo)
print(response.json())
print(response.status_code)

But I'm getting the following error:

{'error': {'code': 'AuthenticationFailed', 'message': "Authentication failed. The 'Authorization' header is missing."}}
401

I've tried to include the client and secret id:

response = requests.post(api_url, json=todo, auth=(AZURE_CLIENT_ID, AZURE_CLIENT_SECRET))

But I got the following error:

{'error': {'code': 'AuthenticationFailedInvalidHeader', 'message': "Authentication failed. The 'Authorization' header is provided in an invalid format."}}
401

How should I make the request?

Luiz
  • 229
  • 1
  • 9
  • Please see this link for acquiring an authorization token and make REST API calls: https://learn.microsoft.com/en-us/rest/api/azure/. – Gaurav Mantri Mar 24 '23 at 01:17
  • 1
    also request library != Azure Python SDK. I recommend changing tagging but edit queue is too long. – jikuja Mar 24 '23 at 21:26

1 Answers1

0

First, generate an access token using the code below, and then include it in the authorization header when sending a Management API request.

import requests

# Replace these with your Azure AD tenant ID, client ID, and client secret
tenant_id = '<your_tenant_id>'
client_id = '<your_client_id>'
client_secret = '<your_client_secret>'

# Construct the OAuth2 token endpoint URL
token_endpoint = f'https://login.microsoftonline.com/{tenant_id}/oauth2/token'

# Define the required parameters for the token endpoint
data = {
    'grant_type': 'client_credentials',
    'client_id': client_id,
    'client_secret': client_secret,
    'resource': 'https://management.azure.com/'
}

# Make a request to the token endpoint to obtain an access token
response = requests.post(token_endpoint, data=data)

# Extract the access token from the response
access_token = response.json()['access_token']

api_url = "https://management.azure.com/subscriptions/subscription_id/resourcegroups/resourcegroup_id/providers/Microsoft.DataFactory/factories/datafactory_id/airflow/sync?api-version=2018-06-01"
todo = {
    "IntegrationRuntimeName": "Airflow",
    "LinkedServiceName": "LAIRFLOW",
    "StorageFolderPath": "airflow/dev/",
    "CopyFolderStructure": "true",
    "Overwrite": "true",
}
access_token = access_token
headers = {'Authorization': f'Bearer {access_token}'}
response = requests.post(api_url, json=todo, headers=headers)
print(response.json())
print(response.status_code)
alex
  • 51
  • 4
  • 10