Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Small and medium business | Business Central, N...
Answered

BadRequest error returned posting customer via BC API

(0) ShareShare
ReportReport
Posted on by 20

I'm trying to create a customer with the following URL and data and receiving the followig error.

Error:

{"error":{"code":"BadRequest","message":"Invalid Request Body  CorrelationId:  6f64a809-4a74-4bbb-a2a7-73349b923dee."}}

Endpoint:

api.businesscentral.dynamics.com/.../customers

Data:

{
"number": "TEST1000",
"displayName": "Test Customer",
"type": "Company",
"addressLine1": "",
"addressLine2": "",
"city": "",
"state": "",
"country": "",
"postalCode": "",
"phoneNumber": "",
"email": "",
"website": "",
"salespersonCode": "",
"balanceDue": 0,
"creditLimit": 0,
"taxLiable": false,
"taxAreaId": <taxAreaId-guid>,
"taxAreaDisplayName": "",
"taxRegistrationNumber": "",
"currencyId": "00000000-0000-0000-0000-000000000000",
"currencyCode": "USD",
"paymentTermsId": <paymentTermsId-guid>,
"shipmentMethodId": "00000000-0000-0000-0000-000000000000",
"paymentMethodId": "00000000-0000-0000-0000-000000000000"
}

To get the data in my customer, I manually created one in the app, retrieved that data with the api and changed the number and displayName,

I also removed fields:       "@odata.etag",  "id", "blocked", and "lastModifiedDateTime"

Any help would be appreciated.

  • Pat Arneson Profile Picture
    20 on at
    RE: BadRequest error returned posting customer via BC API

    When I tried that it worked in Postman, but not my code so it helped me fix a problem I was missing. Then I was able to take it back to the full json file from the beginning of this post and that worked successfully.

    Thanks so much.

  • Verified answer
    DAnny3211 Profile Picture
    9,276 Moderator on at
    RE: BadRequest error returned posting customer via BC API

    hi

    try only this

    {

        "number": "WHATEVAH",

        "displayName": "Test",

        "type": "Company"

    }

    DAniele

  • Pat Arneson Profile Picture
    20 on at
    RE: BadRequest error returned posting customer via BC API

    I'm wondering if I'm specifying the data incorrectly. I'm posting directly as listed above, I'm wondering if I need to it differently, perhaps similar to how responses are formatted:

    {

     "value": [

       {

         "@odata.etag": "W/\"JzE5Ozc4NTY5ODU2ODUwNTYxOTUzOTMxOzAwOyc=\"",

         "id": "a8df6d47-1bb2-ed11-9a88-000d3a3055e1",

         "number": "WHATEVAH",

         "displayName": "Test",

         "type": "Company",

         "addressLine1": "",

         "addressLine2": "",

         "city": "",

         "state": "",

         "country": "",

         "postalCode": "",

         "phoneNumber": "",

         "email": "",

         "website": "",

         "salespersonCode": "",

         "balanceDue": 0,

         "creditLimit": 0,

         "taxLiable": false,

         "taxAreaId": "8d8c91d2-13b2-ed11-9a88-000d3a3055e1",

         "taxAreaDisplayName": "",

         "taxRegistrationNumber": "",

         "currencyId": "00000000-0000-0000-0000-000000000000",

         "currencyCode": "USD",

         "paymentTermsId": "bb3c01e4-2756-ec11-bb7d-000d3aaa1396",

         "shipmentMethodId": "00000000-0000-0000-0000-000000000000",

         "paymentMethodId": "00000000-0000-0000-0000-000000000000",

         "blocked": "_x0020_",

         "lastModifiedDateTime": "2023-02-21T19:10:30.37Z"

       }

     ]

    }

  • Pat Arneson Profile Picture
    20 on at
    RE: BadRequest error returned posting customer via BC API

    import msal
    import logging
    import json
    
    import requests
    
    customer_id = 'removed'
    
    
    def acquire_token():
        config = json.load(open("parameters.json"))
        app = msal.ConfidentialClientApplication(
            config["client_id"], authority=config["authority"],
            client_credential=config["secret"],
        )
    
        result = None
        result = app.acquire_token_silent(config["scope"], account=None)
        if not result:
            logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
            result = app.acquire_token_for_client(scopes=config["scope"])
        return result['access_token']
    
    
    class Customer:
        json = ""
    
        def __init__(self, json):
            self.json = json
            print(self.json)
    
        @staticmethod
        def get_customers():
            access_token = acquire_token()
            url = f"https://api.businesscentral.dynamics.com/v2.0/production/api/v2.0/companies({customer_id})/customers"
            result = requests.get(
                url,
                headers={'Authorization': 'Bearer '   access_token}, )
            print("status: %s" % result.status_code)
            result_json = result.json()
            print("Result: ")
            print(json.dumps(result_json, indent=2))
    
        @staticmethod
        def query_customer(customer_number):
            access_token = acquire_token()
            url = f"https://api.businesscentral.dynamics.com/v2.0/production/api/v2.0/companies({customer_id})/customers?$filter=number eq '{customer_number}'"
            result = requests.get(
                url,
                headers={'Authorization': 'Bearer '   access_token}, )
            print("status: %s" % result.status_code)
            result_json = result.json()
            print("Result: ")
            print(json.dumps(result_json, indent=2))
    
        @classmethod
        def create_customer(cls):
            print(cls.json)
            access_token = acquire_token()
            url = f"https://api.businesscentral.dynamics.com/v2.0/production/api/v2.0/companies({customer_id})/customers"
            result = requests.post(
                url,
                data=cls.json,
                headers={'Authorization': 'Bearer '   access_token, 'Content-type': 'application/json'}, )
            print("status: %s" % result.status_code)
            print("messsage: %s" % result.text)
            result_json = result.json()
            print("Result: ")
            print(json.dumps(result_json, indent=2))
    
    
    Customer.get_customers()
    Customer.query_customer("WHATEVAH")
    
    customer = Customer(open('test_customer.json').read())
    customer.create_customer()

  • Pat Arneson Profile Picture
    20 on at
    RE: BadRequest error returned posting customer via BC API

    I just added that after I started chatting with you because somebody else had it specified in their postman call, it doesn't need to be there and didn't change anything.

  • Suggested answer
    Nitin Verma Profile Picture
    21,544 Moderator on at
    RE: BadRequest error returned posting customer via BC API

    Hi,

    Thanks for sharing, but I am not Python expert, but I doubt this line

     'Content-Length': str(len(cls.json))}, )

  • Pat Arneson Profile Picture
    20 on at
    RE: BadRequest error returned posting customer via BC API

    Here's my python code:

    import msal

    import logging

    import json

    import requests

    customer_id = 'removed'

    def acquire_token():

       config = json.load(open("parameters.json"))

       app = msal.ConfidentialClientApplication(

           config["client_id"], authority=config["authority"],

           client_credential=config["secret"],

       )

       result = None

       result = app.acquire_token_silent(config["scope"], account=None)

       if not result:

           logging.info("No suitable token exists in cache. Let's get a new one from AAD.")

           result = app.acquire_token_for_client(scopes=config["scope"])

       return result['access_token']

    class Customer:

       json = ""

       def __init__(self, json):

           self.json = json

           print(self.json)

       @staticmethod

       def get_customers():

           access_token = acquire_token()

           url = f"api.businesscentral.dynamics.com/.../customers"

           result = requests.get(

               url,

               headers={'Authorization': 'Bearer ' + access_token}, )

           print("gd: %s" % result)

           result_json = result.json()

           print("Graph API call result: ")

           print(json.dumps(result_json, indent=2))

       @staticmethod

       def query_customer(customer_number):

           access_token = acquire_token()

           url = f"api.businesscentral.dynamics.com/.../customers eq '{customer_number}'"

           result = requests.get(

               url,

               headers={'Authorization': 'Bearer ' + access_token}, )

           print("status: %s" % result.status_code)

           result_json = result.json()

           print("result data: ")

           print(json.dumps(result_json, indent=2))

       @classmethod

       def create_customer(cls):

           print(cls.json)

           access_token = acquire_token()

           url = f"api.businesscentral.dynamics.com/.../customers"

           result = requests.post(

               url,

               data=cls.json,

               headers={'Authorization': 'Bearer ' + access_token, 'Content-type': 'application/json',

                        'Content-Length': str(len(cls.json))}, )

           print("status: %s" % result.status_code)

           print("messsage: %s" % result.text)

    Customer.get_customers()

    Customer.query_customer("WHATEVAH")

    customer = Customer(open('test_customer.json').read())

    customer.create_customer()

    And the current contents of my data file:

    {

    "number": "TEST1000",

    "displayName": "Test Customer",

    "type": "Company",

    "addressLine1": "",

    "addressLine2": "",

    "city": "",

    "state": "",

    "country": "",

    "postalCode": "",

    "phoneNumber": "",

    "email": "",

    "website": "",

    "salespersonCode": "",

    "creditLimit": 0,

    "taxLiable": false,

    "taxRegistrationNumber": "",

    "currencyId": "00000000-0000-0000-0000-000000000000",

    "currencyCode": "USD",

    "shipmentMethodId": "00000000-0000-0000-0000-000000000000",

    "paymentMethodId": "00000000-0000-0000-0000-000000000000"

    }

  • Suggested answer
    Nitin Verma Profile Picture
    21,544 Moderator on at
    RE: BadRequest error returned posting customer via BC API

    share me everything what you are using

  • Pat Arneson Profile Picture
    20 on at
    RE: BadRequest error returned posting customer via BC API

    URLs I'm using. These work fine as get requests.

    url = f"api.businesscentral.dynamics.com/.../customers"

    url = f"api.businesscentral.dynamics.com/.../customers eq '{customer_number}'"

  • Pat Arneson Profile Picture
    20 on at
    RE: BadRequest error returned posting customer via BC API

    Yes, I've successfully gotten a customer list and queried on a specific number using a filter.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

🌸 Community Spring Festival 2025 Challenge 🌸

WIN Power Platform Community Conference 2025 tickets!

Jonas ”Jones” Melgaard – Community Spotlight

We are honored to recognize Jonas "Jones" Melgaard as our April 2025…

Kudos to the March Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 294,099 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 232,866 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,158 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans