High severity HTTP 400 beginner · Fix: 2-5 min

BadRequestError

anthropic.client.errors.BadRequestError

What this error means
Anthropic's API rejects the request because the message format does not conform to the expected schema, causing a BadRequestError.

Stack trace

traceback
anthropic.client.errors.BadRequestError: 400 Bad Request - invalid message format: expected list of messages with 'content' keys only
QUICK FIX
Ensure messages is a list of dicts with only 'content' keys and no 'role' keys before calling client.messages.create().

Why it happens

Anthropic's API expects messages to be passed as a list of dictionaries with specific keys like 'content' and no 'role' key. Using an incorrect message structure, such as including 'role' or passing a single dict instead of a list, triggers this error.

Detection

Validate that the messages parameter is a list of dicts with only 'content' keys before sending; log the request payload on failure to catch format issues early.

Causes & fixes

1

Passing messages as a single dictionary instead of a list of dictionaries

✓ Fix

Wrap your message dict inside a list to match the expected format, e.g. messages=[{...}]

2

Including 'role' keys in messages, which Anthropic API does not accept

✓ Fix

Remove 'role' keys from message dicts; only include 'content' keys as strings

3

Using the wrong parameter name or structure for the messages argument

✓ Fix

Use the Anthropic SDK's client.messages.create() method with messages as a list of dicts containing only 'content'

Code: broken vs fixed

Broken - triggers the error
python
from anthropic import Anthropic
client = Anthropic(api_key='sk-...')

# Incorrect: messages is a dict with 'role' key
response = client.messages.create(
    model='claude-2',
    messages={"role": "user", "content": "Hello"}  # triggers BadRequestError
)
print(response)
Fixed - works correctly
python
import os
from anthropic import Anthropic

client = Anthropic(api_key=os.environ['ANTHROPIC_API_KEY'])

# Fixed: messages is a list of dicts with only 'content' keys
response = client.messages.create(
    model='claude-2',
    messages=[{"content": "Hello"}]  # fixed message format
)
print(response)
Changed messages from a single dict with 'role' key to a list of dicts containing only 'content' keys, matching Anthropic API's expected message format.

Workaround

Catch BadRequestError exceptions, then log and manually transform your messages to a list of dicts with only 'content' keys before retrying the request.

Prevention

Always follow Anthropic's message format specification: pass messages as a list of dicts with only 'content' keys, and avoid including 'role' keys or other unexpected fields.

Python 3.9+ · anthropic >=0.20.0 · tested on 0.20.x
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.