Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 50 ยท Practice, interviews and cheat sheet

Common FastAPI pitfalls

Avoid the FastAPI mistakes that bite everyone: blocking calls in async code, shared defaults, leaking fields, route order, missing await and Pydantic v2 traps.

Most FastAPI bugs are not exotic. They come from a short list of mistakes that look harmless in code review and then show up as a slow server, a leaked password hash or a mysterious 422. This lesson walks through the ones that cost the most time, each with a small reproduction you can run, why it happens, and the fix.

Treat it as a checklist for code review. If you can explain each pitfall in your own words, you will avoid most of the trouble people report in production.

The usual suspects

Blocking in async One slow call stalls everyone.
Shared defaults Mutable values live across calls.
Leaky responses Secret fields escape.
Route order First match wins.
1 / 2

1. Blocking calls inside async def

An async def endpoint runs on the event loop, the single thread that serves every request. If it calls something that blocks (time.sleep, requests.get, a synchronous database driver, a long computation), the loop cannot serve anybody else until the call returns. A plain def endpoint would run in a thread pool and not have this problem; it is async def plus blocking code that hurts. async def vs def endpoints explains the model.

The experiment below sends two requests at the same time. The first endpoint blocks for 0.2 s (a busy loop stands in for time.sleep or a synchronous HTTP call, because browsers handle real sleeps differently), the second awaits asyncio.sleep(0.2). If requests overlap, the pair takes about 0.2 s; if they queue up, about 0.4 s.

Python Two concurrent requests: blocking vs awaiting

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 fixes, in order of preference: use an async library (httpx.AsyncClient, an async database driver), declare the endpoint with plain def so FastAPI uses a worker thread, or push heavy CPU work into another process or a task queue. The same rule applies inside async def dependencies.

2. Shared mutable defaults

A default value is created once, when the function is defined, not on every call. A mutable default such as [] is therefore shared by all callers. Pydantic is smarter: it copies a plain default for each model instance, and Field(default_factory=list) makes the intent explicit. Plain function parameters get no such help.

3. response_model leaks

Without a response_model, FastAPI serializes whatever you return. If you return a database row or a full user object, every field goes out, including password_hash. Declaring an output model makes FastAPI validate and filter the result: fields not in the model are dropped. Prefer separate input and output models over one model for both. See Response models and nested data.

4. Route order

Routes are tried in the order they were declared and the first match wins. /users/{user_id} matches /users/me with user_id="me", so a fixed path declared after a parameterized one is unreachable (and answers 422 when user_id is an int). Always declare the fixed paths first.

5. Pydantic v2 traps

Many older tutorials and Stack Overflow answers describe Pydantic v1. Pydantic v2 behaves differently in ways that cause silent bugs: an Optional[str] field with no default is now required (it only allows None as a value), and a list field is not shared between instances.

Python Four traps, reproduced and fixed

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 remaining renames between Pydantic v1 and v2 are mechanical, but old code keeps compiling with warnings until it does not:

Pydantic v1 Pydantic v2
.dict(), .json() .model_dump(), .model_dump_json()
parse_obj(), parse_raw() model_validate(), model_validate_json()
class Config: orm_mode = True model_config = ConfigDict(from_attributes=True)
@validator, @root_validator @field_validator, @model_validator
schema() model_json_schema()
regex= in Field pattern=

Also, v2 does not silently turn "5" into 5 in strict mode and rejects "yes" for booleans differently from some v1 habits, so test payloads against real behavior, not memory. Pydantic models for APIs covers coercion.

6. Forgetting await

Calling an async function without await does not run it. It creates a coroutine object that nobody schedules. In plain code Python prints "coroutine was never awaited" and the work is skipped; if you return the coroutine from an endpoint, serialization fails.

Python A coroutine that was never awaited

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 first response looks fine, which is the danger: nothing crashes, the data is simply missing. Linters (ruff's RUF006, mypy, pyright) catch most of these, so enable them. A related rule: dependencies and Depends(...) take the function itself, never a call: Depends(get_db), not Depends(get_db()).

7. Session lifetime

With SQLAlchemy, a session is tied to one request. Three mistakes recur. Keeping a global session shared by all requests (not safe under concurrency). Returning ORM objects after the session closed, then touching a lazy relationship (DetachedInstanceError). And forgetting that commit() expires loaded attributes by default, so a refresh happens on next access. Read-only sketch of the safe pattern:

Python
async def get_session():
    with Session(engine) as session:       # one session per request
        yield session                       # closed after the response

@app.post("/books", response_model=BookOut)
async def create_book(data: BookIn, session: Annotated[Session, Depends(get_session)]):
    book = Book(**data.model_dump())
    session.add(book)
    session.commit()
    session.refresh(book)                  # reload generated values (id, defaults)
    return book                            # response_model reads attributes now

Since the response is built from the object before the dependency's cleanup runs, the object is still usable. Details are in SQLAlchemy with FastAPI.

8. Smaller traps worth a line each

  • def endpoints and dependencies run in threads, so global mutable state needs care. In-memory dictionaries are fine for demos, not for multi-worker deployments, where every worker has its own copy.
  • Catching Exception too broadly hides HTTPException; re-raise it or catch narrower errors.
  • Returning the wrong status for creation: POST that creates should say status_code=201 on the decorator.
  • Trusting the client's Content-Length or body size: set limits at the proxy, see API keys and security practices.
  • Wildcard CORS with credentials: allow_origins=["*"] with cookies does not do what you think, see Middleware and CORS.
  • Running --reload in production and using the development server for real traffic: see Deployment.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when an async def endpoint calls time.sleep(2)?

    Blocking calls inside async code stop the single event-loop thread. Use await asyncio.sleep, an async library, or a plain def endpoint.
  2. 2. Why is GET /users/me unreachable when /users/{user_id} is declared first?

    The first matching route wins. Declare fixed paths before parameterized ones.
  3. 3. In Pydantic v2, what does city: Optional[str] (no default) mean?

    Optional only describes the allowed type. To make the field optional, give it a default: Optional[str] = None.
  4. 4. How do you stop a password_hash attribute from leaking out of an endpoint?

    The response model validates and filters the returned data, so fields it does not declare are never sent.
  5. 5. What is the bug in profile = load_profile() when load_profile is an async def?

    An async function must be awaited. Without await you only get a coroutine object.

Summary

  • Never block the event loop in async def: await async libraries, use plain def, or move heavy work elsewhere.
  • Mutable function defaults are shared; use None or Field(default_factory=...).
  • Always declare a response_model (separate output models) so internal fields cannot leak.
  • Declare fixed routes before parameterized ones.
  • In Pydantic v2, Optional[X] is not a default; learn the renamed APIs (model_dump, field_validator, from_attributes).
  • Always await coroutines and pass functions, not calls, to Depends.
  • Use one session per request and read what you need before it closes.

Ready to test your knowledge in conversation form? Continue with the FastAPI interview questions.