Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Integration with FastAPI

FastAPI Errors, Dependencies and Settings

Customize FastAPI's 422 error format, share validated parameters with Depends, inject BaseSettings and override dependencies in tests, all with Pydantic models.

The last two lessons showed FastAPI validating bodies and filtering responses. Real services also need a consistent error format, shared validated inputs such as pagination, and settings that tests can replace. Pydantic is behind all three. This lesson ties together the settings chapter and FastAPI.

As in the previous lessons, endpoints and dependencies are async def because the browser sandbox cannot run FastAPI's thread pool. In a normal environment plain def works as well, and the code is otherwise identical.

Customizing the 422 response

By default a failed validation returns {"detail": [...]} where each item has type, loc, msg and input. A front end may expect a different shape. FastAPI lets you register a handler for RequestValidationError, which wraps the Pydantic errors:

Python A custom validation error 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 handler groups messages by field, which maps neatly onto a form. Do not echo err["input"] back for sensitive fields such as passwords; the default format includes the input, which is why many projects replace it.

For errors that are not validation problems (a missing record, a permission failure) raise HTTPException(status_code, detail=...) or define your own exception class with its own handler.

Dependencies share validated inputs

A dependency is a function (or class) that FastAPI calls for you and whose result is passed into your route. Its parameters are validated just like route parameters. A common use is pagination, shared by many list endpoints:

Python A paging dependency built on a model

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.

Dependencies can depend on other dependencies, which is how authentication, database sessions and permission checks stack up. Because the paging rules live in one model, every endpoint gets the same limits and the same error messages.

Settings as a dependency

Combine get_settings with Depends. Routes ask for settings; FastAPI calls the cached function once. The key benefit follows: tests can replace the provider with app.dependency_overrides.

Python Injecting and overriding settings

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.

On a normal server get_settings is simply the cached function from the previous lesson. Here it is a thin async wrapper around one. The overriding function takes the place of get_settings for the whole app, with no environment changes and no cache clearing. Remember to clear overrides after a test.

flowchart LR
    R["request"] --> D["Depends(get_settings)"]
    D -->|normal| S1["cached Settings()<br/>from environment"]
    D -->|test override| S2["Settings(...)<br/>with test values"]
    S1 --> H["route function"]
    S2 --> H

A single provider function is the seam where tests substitute values.

Validating lifespan configuration

Validate settings at startup, not on the first request that happens to need them. Calling get_settings() in the app's startup (the lifespan function) makes a missing variable stop the deployment immediately, with the whole list of problems, instead of failing for the first unlucky visitor.

Python
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    get_settings()        # raises ValidationError here if configuration is wrong
    yield

app = FastAPI(lifespan=lifespan)

Testing the whole thing

Everything above is testable without a network, as these examples show with httpx.ASGITransport. In a normal project you would use FastAPI's TestClient (or the same httpx transport with pytest-asyncio), call the routes, assert status codes and JSON, and set dependency_overrides in a fixture. The next chapter goes deeper into speed and patterns: Performance Tips.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which exception does FastAPI raise internally when the request fails validation, so that you can write a handler for it?

    FastAPI wraps Pydantic's errors in RequestValidationError. Register it with @app.exception_handler to change the response.
  2. 2. What is a good reason to put paging parameters in a dependency or shared model?

    One definition of page and size, with ge and le limits, avoids copy-paste mistakes.
  3. 3. How can a test replace the settings that a route receives through Depends(get_settings)?

    dependency_overrides maps the original provider function to a replacement used for every request.
  4. 4. Why call get_settings() in the lifespan startup?

    Validation at startup reveals configuration problems immediately instead of at the first request.

Summary

  • Handle RequestValidationError to return your own 422 format; avoid echoing sensitive input.
  • Dependencies built on Pydantic models share validated parameters such as paging.
  • Inject settings with Depends(get_settings); tests use app.dependency_overrides.
  • Validate configuration at startup in lifespan.

Next: TypeAdapter and validate_call