Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 50 ยท Responses, errors and docs

Status codes and error handling

Choose the right HTTP status codes in FastAPI, raise HTTPException, write custom exception handlers, reshape 422 validation errors and return one consistent error format.

A good API tells clients exactly what happened. The HTTP status code is the first signal: 201 means "created", 404 means "no such thing", 409 means "that conflicts with what exists". The body of an error response then explains the details. If every endpoint reports problems in its own style, client developers suffer; if every error looks the same, they can write one piece of code to handle them all.

In this lesson you will set status codes, raise HTTPException, write handlers for your own exception types, override the default validation error response, and settle on one consistent error shape.

Status codes in families

2xx It worked. 200, 201, 204.
4xx The client made a mistake. 400, 401, 403, 404, 409, 422.
5xx The server failed. 500, 503.

Pick the family first, then the most specific code.

1 / 2

Setting the success status

By default FastAPI answers 200. Pass status_code= to the decorator to say something more precise. The constants in fastapi.status are readable alternatives to bare numbers.

Python Choosing success codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A 204 No Content response has no body at all, so the function returns nothing. Use 201 for resource creation, ideally with a Location header pointing at the new resource.

Raising HTTPException

When something is wrong inside an endpoint, raise HTTPException(status_code=..., detail=...). It stops the function immediately, wherever it is called from, even inside a helper or a dependency. The detail can be any JSON-serializable value, and headers lets you attach response headers.

Python 404, 409 and extra headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the shape: {"detail": "..."}. That is FastAPI's default, and it is the same key used by the validation error response, where detail is a list.

Use HTTPException for errors the client can cause. Don't use it for real bugs: an unexpected exception becomes a 500, which is the correct signal for "this is our fault".

Custom exception classes and handlers

Raising HTTPException everywhere tangles web concerns into your business logic. A cleaner design is to raise your own exception from the logic and translate it in one place with an exception handler. The handler receives the request and the exception and returns a response.

Python A domain exception and its handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The function reserve knows nothing about HTTP. Any endpoint, background job or test can call it, and the one handler decides what the client sees.

Overriding validation errors

When a request doesn't match your parameters or models, FastAPI raises RequestValidationError and answers 422 with a detail list. You can replace that response by registering a handler for the exception class. The raw problems are in exc.errors().

Python A friendlier 422 response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

loc[0] is where the value came from (body, query, path), so dropping it leaves a clean field name such as guests.

One consistent error shape

Pick a single format and use it for every error: your own exceptions, HTTPException and validation errors. A popular design, loosely inspired by RFC 9457 "problem details", has a stable machine code, a short message, and optional extra details. Register one handler for Starlette's HTTPException (the base class of FastAPI's), so even automatic errors such as the 404 for an unknown URL or 405 for a wrong method follow the format.

Python Every error in the same format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The unknown URL and the wrong method both pass through the same handler, because Starlette raises its HTTPException for them. Registering the handler for the Starlette class, not FastAPI's subclass, is what catches them.

Never put stack traces, SQL or file paths in an error body. Log them on the server and give the client a code and a safe message. For 500 errors you can add a catch-all handler for Exception, but note that in tests the original exception is still raised by the test client.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which status code fits a successful DELETE that returns no body?

    204 No Content means success with an empty body.
  2. 2. A logged-in user tries to open another user's private page. Which code is correct?

    401 means not authenticated; 403 means authenticated but not permitted.
  3. 3. How do you change the response FastAPI sends for invalid request data?

    app.exception_handler(RequestValidationError) lets you build any response from exc.errors().
  4. 4. Why register a handler for Starlette's HTTPException instead of FastAPI's?

    FastAPI's HTTPException is a subclass, so a handler for the Starlette base class catches both your errors and the framework's own.

Summary

  • Pick precise status codes: 201 for creation, 204 for empty success, 401 vs 403, 404, 409, 422.
  • raise HTTPException(status_code, detail, headers) ends the request with an error response.
  • Raise your own exception types from business logic and translate them with @app.exception_handler.
  • Override RequestValidationError to reshape 422 responses.
  • Handle Starlette's HTTPException as well to give every error, even the automatic ones, the same shape.

Next: control response types and read the generated docs in response classes and OpenAPI docs.