BadRequestError
anthropic.client.errors.BadRequestError
Stack trace
anthropic.client.errors.BadRequestError: 400 Bad Request - invalid message format: expected list of messages with 'content' keys only
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
Passing messages as a single dictionary instead of a list of dictionaries
Wrap your message dict inside a list to match the expected format, e.g. messages=[{...}]
Including 'role' keys in messages, which Anthropic API does not accept
Remove 'role' keys from message dicts; only include 'content' keys as strings
Using the wrong parameter name or structure for the messages argument
Use the Anthropic SDK's client.messages.create() method with messages as a list of dicts containing only 'content'
Code: broken vs fixed
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) 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) 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.