How to properly structure the request body and send it to REST API
Introduction
Sometimes, when you are trying to send a REST API request you get a 400 error response for no apparent reason.
Specifics
In the vast majority of cases, the issue stems from a wrong content type used in your whole request. For example, in the back-end side, the following log might appear:
REST API EXCEPTION: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supportedThat would indicate that the request you are sending is using the application/x-www-form-urlencoded content type.
However, the API expects the request body to be in JSON format, and thus the Content-Type should be set to application/json.
For your convenience, below you see a sample Python script that demonstrates how to structure your request body properly and send it to the API:
The following Python script presents a request for updating custom fields in a particular XTM Cloud project.
import requests
base_url = 'https://pcl1.xtm.cloud' # Replace with your XTM Cloud instance URL
project_id = 123456 # Replace with your project ID
token = 'XXXXX' # Replace with your authorization token
url = f'{base_url}/project-manager-api-rest/projects/{project_id}/custom-fields'
headers = {
'Authorization': f'XTM-Basic {token}', # Auth type, adjust as needed
'Content-Type': 'application/json'
}
payload = [
{
"id": 123456,
"value": {
"value": "EXAMPLE"
}
},
{
"id": 123456,
"value": {
"ids": [123456],
"value": "EXAMPLE"
}
},
{
"id": 123456,
"value": {
"ids": [123456],
"value": "EXAMPLE"
}
}
]
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
print('Custom fields updated successfully')
else:
print(f'Failed to update custom fields. Status code: {response.status_code}, Response: {response.text}')Ensure that:
The URL is correct and points to the right API endpoint.
The Authorization token is valid and included in the headers.
The request body (JSON data) is structured as expected by the API
All payload values are correct (such as IDs and values keys).
If your code is similar to this and you will still be encountering the 400 error, it might be helpful to check the error message returned in the response, which should provide more details about the issue.