Handling API Errors
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 12 of 22.
A request can fail, and the SDK raises an exception when it does. Each HTTP error has its own class: BadRequestError (400, the request itself is wrong), AuthenticationError (401, a bad key), NotFoundError (404, for example a model id that does not exist), RateLimitError (429, too many requests) and InternalServerError (500). All of them are subclasses of APIStatusError, which carries status_code and the server's body.
try:
response = client.messages.create(
model="claude-opus-5",
max_tokens=999999,
messages=[{"role": "user", "content": "Hi"}],
)
except anthropic.BadRequestError as e:
print(e.status_code)
print(e.body["error"]["message"])
except anthropic.APIStatusError as e:
print("Other API error:", e.status_code)This prints 400 and the message, which says the limit for that model is 128000. Put the specific classes first: Python runs the first except that matches, and APIStatusError matches them all.
The SDK retries a 429 or a 5xx error twice by itself before raising (set max_retries on the client to change that). A 400 or 404 is never retried, because sending the same request again fails the same way.
Challenge
MediumMake a program that reports a failed request instead of crashing. The starter reads a model id, a max_tokens number and a question.
- Send the question with that
modelandmax_tokens. When it works, printAnswer:and the reply text. - On
anthropic.NotFoundError, printUnknown model: <model>. - On
anthropic.BadRequestError, printBad request (<status code>): <message>, where the message ise.body["error"]["message"]. - On any other
anthropic.APIStatusError, printAPI error <status code>.
For example, for the input claude-opus-5-5, 200000 and Hi the program prints:
Bad request (400): max_tokens: 200000 > 128000, which is the maximum allowed number of output tokens for claude-opus-5-5Try it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
model = input()
max_tokens = int(input())
question = input()
# Send the question with this model and max_tokens.
# Print "Answer: <text>" when it works, and catch the errors as the task says.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Calling Models From Code
3Tokens and Structure
Counting Tokens and CostHandling API ErrorsJSON Schema OutputClassifying With EnumsRecap: Review SorterPractice on your own: Online Python compiler