BadRequestError
openai.BadRequestError (HTTP 400)
Stack trace
openai.BadRequestError: Error code: 400 - {'error': {'message': 'Invalid request body', 'type': 'invalid_request_error', 'param': null, 'code': 'invalid_request_body'}} Why it happens
This error occurs when the JSON payload sent to the OpenAI API is malformed, missing required fields, or contains unsupported parameters. It can also happen if the request body structure does not conform to the API specification, such as wrong data types or unexpected keys.
Detection
Validate the JSON request body before sending, and log the full request payload on errors to identify malformed or missing fields causing the 400 BadRequestError.
Causes & fixes
Malformed JSON in the request body (e.g., missing commas, brackets, or quotes)
Use a JSON validator or Python's json.dumps() to serialize the request body properly before sending.
Using deprecated or unsupported parameters in the request payload
Check the latest OpenAI API documentation and remove or update any deprecated parameters.
Missing required fields such as 'model' or 'messages' in chat completions
Ensure all required fields are included and correctly named in the request body according to the API spec.
Passing incorrect data types (e.g., string instead of list for messages)
Verify that each field matches the expected data type, such as a list of message dicts for 'messages'.
Code: broken vs fixed
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages="Hello, world!" # Incorrect type: should be a list of dicts
) # This line triggers BadRequestError
print(response) import os
from openai import OpenAI
os.environ["OPENAI_API_KEY"] = "your_api_key_here"
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello, world!"}] # Fixed: messages is a list of dicts
) # Correct request body
print(response) Workaround
Catch BadRequestError exceptions, log the full request payload, and manually inspect or fix the JSON structure before retrying the request.
Prevention
Use OpenAI SDK client methods with proper parameter types and always validate request payloads against the latest API schema before sending.