Access Business Central API in Python using MSAL (S2S)
This is a minimalist way to access the Business Central API in Python using the Service 2 Service authentication (Client_Credentials). It is based on the Microsoft Authentication Library for Python:
In the first step, we create a function to obtain a fresh token:
import requests, msal
def getToken(tenant, client_id, client_secret):
authority = "https://login.microsoftonline.com/" + tenant
scope = ["https://api.businesscentral.dynamics.com/.default"]
app = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential = client_secret)
try:
accessToken = app.acquire_token_for_client(scopes=scope)
if accessToken['access_token']:
print('New access token retreived....')
else:
print('Error aquiring authorization token.')
except Exception as err:
print(err)
return accessToken
Now you could, for example, get all companies with a couple of lines:
import requests
# Setup variables
tenant_id = ''
environment = 'Sandbox'
client_id = ''
client_secret = ''
# Fetch the token as json object
reqToken = getToken(tenant_id, client_id, client_secret)
# Build the request URL
url_companies = f"https://api.businesscentral.dynamics.com/v2.0/{tenant_id}/{environment}/api/v2.0/companies"
# Build the request Headers
reqHeaders = {"Accept-Language": "en-us", "Authorization": f"Bearer {reqToken['access_token']}"}
# Fetch the data
response = requests.get(url_companies, headers=reqHeaders)