Menu
CoddyTech

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 icon

Challenge

Medium

Make a program that reports a failed request instead of crashing. The starter reads a model id, a max_tokens number and a question.

  1. Send the question with that model and max_tokens. When it works, print Answer: and the reply text.
  2. On anthropic.NotFoundError, print Unknown model: <model>.
  3. On anthropic.BadRequestError, print Bad request (<status code>): <message>, where the message is e.body["error"]["message"].
  4. On any other anthropic.APIStatusError, print API 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-5

Try 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.
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Calling Models From Code

Practice on your own: Online Python compiler