How to Get Customers with the Microsoft Dynamics 365 Business Central API in Python

by Endgrate Team 2024-06-20 5 min read

Microsoft Dynamics 365 Business Central homepage

Introduction to Microsoft Dynamics 365 Business Central

Microsoft Dynamics 365 Business Central is a comprehensive business management solution designed for small to medium-sized enterprises. It integrates various business processes, including finance, sales, service, and operations, into a single platform, enabling organizations to streamline their operations and make data-driven decisions.

Developers may want to connect with Microsoft Dynamics 365 Business Central to access and manage customer data efficiently. By leveraging its API, developers can automate tasks such as retrieving customer information, which can be used to enhance customer relationship management and improve service delivery. For example, a developer might use the API to fetch customer details and integrate them into a custom CRM system, ensuring that sales teams have up-to-date information at their fingertips.

Setting Up a Microsoft Dynamics 365 Business Central Sandbox Account

Before you can start interacting with the Microsoft Dynamics 365 Business Central API, you'll need to set up a sandbox account. This environment allows you to test API calls without affecting live data, providing a safe space to develop and refine your integration.

Creating a Microsoft Dynamics 365 Business Central Sandbox Account

  1. Visit the Microsoft Dynamics 365 Business Central website and sign up for a free trial if you don't already have an account.
  2. Once logged in, navigate to the Admin Center and select Environments.
  3. Click on New to create a new environment and choose Sandbox as the type.
  4. Follow the prompts to complete the setup. Your sandbox environment will be ready in a few minutes.

Registering an Application for OAuth Authentication

To interact with the API, you'll need to register an application in Microsoft Entra ID (formerly Azure AD) to obtain the necessary credentials for OAuth authentication.

  1. Go to the Azure Portal and sign in with your Microsoft account.
  2. Navigate to Azure Active Directory and select App registrations.
  3. Click on New registration and fill in the required details, such as the application name and redirect URI.
  4. Once registered, note down the Application (client) ID and Directory (tenant) ID.
  5. Under the app's settings, navigate to Certificates & secrets and create a new client secret. Save this secret securely as it will not be shown again.

Configuring API Permissions

To access customer data, you'll need to configure the appropriate API permissions for your registered application.

  1. In the Azure Portal, go to your app registration and select API permissions.
  2. Click on Add a permission and choose Dynamics 365 Business Central.
  3. Select the permissions required for accessing customer data, such as user_impersonation, and grant admin consent.

With your sandbox environment and application registration set up, you're now ready to start making API calls to Microsoft Dynamics 365 Business Central.

Microsoft Dynamics 365 Business Central authentication documentation page.
sbb-itb-96038d7

Making API Calls to Retrieve Customers from Microsoft Dynamics 365 Business Central Using Python

To interact with the Microsoft Dynamics 365 Business Central API and retrieve customer data, you'll need to use Python. This section will guide you through the necessary steps, including setting up your environment, writing the code, and handling potential errors.

Setting Up Your Python Environment

Before making API calls, ensure you have the following prerequisites installed on your machine:

  • Python 3.11.1 or later
  • The Python package installer, pip

Next, install the requests library, which will be used to make HTTP requests to the API:

pip install requests

Writing the Python Code to Retrieve Customers

Create a new Python file named get_customers.py and add the following code:

import requests

# Set the API endpoint and headers
base_url = "https://yourbusinesscentral.api.dynamics.com"
company_id = "your_company_id"
endpoint = f"{base_url}/api/v2.0/companies({company_id})/customers"
headers = {
    "Authorization": "Bearer Your_Access_Token",
    "Content-Type": "application/json"
}

# Make a GET request to the API
response = requests.get(endpoint, headers=headers)

# Check if the request was successful
if response.status_code == 200:
    customers = response.json()
    for customer in customers['value']:
        print(f"Customer Name: {customer['displayName']}, Email: {customer['email']}")
else:
    print(f"Failed to retrieve customers: {response.status_code} - {response.text}")

Replace Your_Access_Token with the token obtained during the OAuth authentication process. Similarly, replace yourbusinesscentral.api.dynamics.com and your_company_id with your actual Business Central API endpoint and company ID.

Running the Code and Verifying the Output

Run the script using the following command:

python get_customers.py

If successful, the script will print out the names and emails of the customers retrieved from your Microsoft Dynamics 365 Business Central sandbox environment. You can verify the data by checking the sandbox account to ensure it matches the output.

Handling Errors and Common Issues

When making API calls, you may encounter errors. Here are some common HTTP status codes and their meanings:

  • 200 OK: The request was successful.
  • 401 Unauthorized: Authentication failed. Check your access token.
  • 404 Not Found: The requested resource does not exist. Verify the endpoint URL and company ID.
  • 500 Internal Server Error: An error occurred on the server. Try again later.

For more detailed error handling, refer to the Microsoft Dynamics 365 Business Central API documentation.

Microsoft Dynamics 365 Business Central API call documentation page.

Conclusion and Best Practices for Integrating with Microsoft Dynamics 365 Business Central API

Integrating with the Microsoft Dynamics 365 Business Central API allows developers to efficiently manage customer data, enhancing CRM systems and improving service delivery. By following the steps outlined in this guide, you can successfully set up your environment, authenticate using OAuth, and retrieve customer information using Python.

Best Practices for Secure and Efficient API Integration

  • Securely Store Credentials: Always store your OAuth tokens and client secrets securely. Consider using environment variables or secure vaults to protect sensitive information.
  • Handle Rate Limiting: Be aware of API rate limits to avoid throttling. Implement retry logic with exponential backoff to handle rate limit responses gracefully.
  • Data Transformation and Standardization: Ensure that data retrieved from the API is transformed and standardized to fit your application's requirements, maintaining consistency across systems.
  • Error Handling: Implement robust error handling to manage different HTTP status codes and unexpected responses, ensuring your application can recover gracefully from failures.

Streamlining Integration Development with Endgrate

While building integrations can be complex and time-consuming, tools like Endgrate simplify the process by providing a unified API endpoint for multiple platforms, including Microsoft Dynamics 365 Business Central. By leveraging Endgrate, you can save time and resources, allowing you to focus on your core product development while ensuring a seamless integration experience for your customers.

Explore how Endgrate can enhance your integration strategy by visiting Endgrate and discover how you can build once for each use case instead of multiple times for different integrations.

Read More

Ready to get started?

Book a demo now

Book Demo