Skip to content
Tutorials Center
My learning

Topics

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

FastAPI interview questions

Prepare for FastAPI interviews with 28 questions and clear answers on ASGI, dependency injection, async, Pydantic, auth, testing and FastAPI vs Flask and Django.

Interviewers rarely ask you to recite the documentation. They ask why FastAPI works the way it does, what happens when you misuse a feature, and how you would choose it over another framework. The 28 questions below follow that pattern, grouped by topic, with answers short enough to say out loud and precise enough to be correct.

Two live demos sit in the middle, because showing that FastAPI is "just an ASGI callable" and that dependencies are cached per request are two of the most convincing things you can do in an interview.

What interviewers probe

Concepts ASGI, async, type hints.
Design Dependencies and layering.
Security Auth, hashing, permissions.
Judgment When to pick what.
1 / 2

Fundamentals

1. What is FastAPI and what is it built on?

A Python web framework for APIs. It is a thin layer over Starlette (the ASGI toolkit: routing, requests, responses, middleware, WebSockets) and Pydantic (validation and serialization). Its own contribution is reading your type hints and turning them into request parsing, validation, dependency injection and an OpenAPI schema. See What FastAPI is and how to set it up.

2. What is ASGI, and how is it different from WSGI?

WSGI is a synchronous interface: one callable per request, returns a response, no native support for long-lived connections. ASGI is the asynchronous successor: an async callable taking scope, receive and send, which supports HTTP, WebSockets, streaming and lifespan events. FastAPI needs an ASGI server such as uvicorn (or hypercorn).

3. Is a FastAPI application really just a callable?

Yes. app(scope, receive, send) is all an ASGI server does. The demo shows it without any server: the test sends a hand-made scope and collects the messages the app sends back.

Python Calling the app as a bare ASGI callable

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 server's job is only to turn network bytes into this scope and these messages. Everything else is the framework.

4. How does FastAPI generate the interactive docs?

From the same type hints it uses for validation. It builds an OpenAPI 3.1 JSON document at /openapi.json; Swagger UI (/docs) and ReDoc (/redoc) are static pages that read it. See Response classes and OpenAPI docs.

5. Where do path, query and body parameters come from?

From the signature. A name that appears in the path template is a path parameter; a simple type (int, str, bool, list with Query) is a query parameter; a Pydantic model is the JSON body. Header, Cookie, Form and File select other sources explicitly. See Request parameters.

6. What status code do validation errors return, and why?

422 Unprocessable Content, with a JSON body whose detail is a list of objects containing loc (where), msg and type. The request was syntactically fine but semantically invalid. You can change the shape with an exception handler for RequestValidationError.

Async and concurrency

7. When should an endpoint be async def and when def?

Use async def when the body awaits async I/O libraries. Use plain def when you must call blocking code; FastAPI runs it in a thread pool so the event loop stays free. Blocking code inside async def is the classic mistake. See async def vs def endpoints.

8. What happens if you call a blocking function inside async def?

The event loop thread is blocked, so every other request on that worker waits. Throughput collapses, even though CPU usage may look low. Fix: async library, plain def, or a separate process.

9. Does async make my code faster?

No. It improves concurrency for I/O-bound work: while one request waits for the database, the loop serves another. A CPU-heavy function is not sped up and will block the loop; use worker processes or a task queue.

10. How do you run work after the response is sent?

BackgroundTasks for small jobs in the same process (email, cache refresh). For work that must survive restarts, be retried or scale independently, use a task queue (Celery, ARQ, RQ). See Background tasks.

11. How do you scale a FastAPI app?

Run several worker processes (uvicorn --workers, or gunicorn with the uvicorn worker class), then several machines or containers behind a load balancer. Keep the app stateless: shared state belongs in a database or Redis, because each worker has its own memory. See Deployment.

Dependency injection

12. What is dependency injection in FastAPI?

You declare what an endpoint needs with Depends(function); FastAPI calls the function for each request, resolves its own dependencies first, and passes the result. It is used for database sessions, current user, pagination, settings and permission checks.

13. Are dependencies cached?

Within one request, yes: if two dependents use the same dependency, it runs once and the result is shared. Depends(dep, use_cache=False) disables that. Across requests, nothing is cached unless you do it yourself (for example lru_cache on settings).

Python Per-request dependency caching and dependency_overrides

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.

14. What does yield do in a dependency?

Code before yield is setup, the yielded value is injected, and code after yield runs after the response (cleanup, closing a session). Exceptions raised in the endpoint are re-raised inside the dependency at the yield, so you can roll back. See Class and yield dependencies.

15. How do you apply a dependency to a whole router or app?

APIRouter(dependencies=[Depends(...)]) or FastAPI(dependencies=[...]). These run for every route but do not inject a value; use them for guards such as authentication. See Router-level and global dependencies.

16. How do you test code that uses dependencies?

app.dependency_overrides[original] = replacement, cleared after each test. Replace databases, clocks and current users instead of patching internals. See Testing FastAPI apps.

Pydantic and models

17. What is the difference between a request model and a response model?

The request model validates what comes in; response_model (or the return annotation) validates and filters what goes out. Separate models prevent leaks such as returning password_hash, and let create, read and update shapes differ. See Response models and nested data.

18. What changed in Pydantic v2 that you must know?

model_dump/model_validate replace dict/parse_obj, field_validator and model_validator replace validator/root_validator, from_attributes replaces orm_mode, Optional[X] without a default is now required, and the core is written in Rust, which makes validation much faster. See Common FastAPI pitfalls.

19. How do you implement a partial update (PATCH)?

Use a model where every field is optional, then apply model_dump(exclude_unset=True) so only the fields the client sent change. Without exclude_unset, defaults would overwrite stored data. See PUT, PATCH and partial updates.

20. How do you add custom validation?

Constraints in Field(...) for simple rules (min_length, ge, pattern), @field_validator for one field, @model_validator for rules across fields, and Annotated types to reuse a rule. See Field constraints and validators.

Security

21. How do you store passwords?

Never in plain text, and never with a fast hash such as SHA-256 alone. Use a slow, salted, purpose-built algorithm (argon2, bcrypt, scrypt) and compare with a constant-time check. See Password hashing and user accounts.

22. Describe the OAuth2 password flow with JWT in FastAPI.

The client posts username and password to a token endpoint; the server verifies the hash and returns a signed JWT with a subject and an expiry. The client sends it in Authorization: Bearer ...; a dependency built on OAuth2PasswordBearer decodes it and returns the current user. Keep tokens short-lived and use refresh tokens for long sessions. See OAuth2 password flow and JWT.

23. 401 or 403?

401 means "I don't know who you are" (missing or invalid credentials, with a WWW-Authenticate header). 403 means "I know who you are, and you are not allowed". See Roles, scopes and permissions.

24. How do you configure CORS safely?

Add CORSMiddleware with an explicit list of origins. Avoid ["*"] together with allow_credentials=True. CORS is enforced by browsers only; it is not an authentication mechanism. See Middleware and CORS.

Databases and testing

25. How do you manage database sessions?

One session per request, created in a dependency with yield and closed afterward; commit in the endpoint or service layer. Never share a global session. For async drivers use AsyncSession and await every call. See SQLAlchemy with FastAPI.

26. How do you test a FastAPI app?

With TestClient in pytest (use it as a context manager when you have a lifespan), or an async httpx.AsyncClient with ASGITransport. Use a fresh in-memory database per test, override dependencies, and assert on status, JSON and error shapes.

Comparisons

27. FastAPI vs Flask?

Flask is minimal and synchronous by default; validation, serialization and docs come from extensions and your own code. FastAPI has typed validation, OpenAPI docs, dependency injection and async support built in, which suits API-first services. Flask remains pleasant for small apps and server-rendered pages. See the Flask tutorial.

28. FastAPI vs Django (and Django REST framework)?

Django is a batteries-included framework: ORM, migrations, admin, auth, templates, forms. DRF adds serializers and viewsets on top. FastAPI gives you routing, validation and docs, and you choose the database layer, migrations and auth yourself. Pick Django when you need the admin and a rich relational app quickly; pick FastAPI for lean, typed, high-concurrency APIs or services that sit next to ML code. They can also coexist. See the Django tutorial.

Do not trash the alternatives. A strong answer names the trade-off: "FastAPI gives me typed contracts and async out of the box, and I accept that I assemble the rest myself."

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an ASGI server hand to a FastAPI app for each request?

    ASGI apps are async callables app(scope, receive, send); the server translates network traffic into those arguments.
  2. 2. Two dependencies in one request both depend on get_connection. How many times does it run by default?

    FastAPI caches a dependency's result for the duration of a request unless you pass use_cache=False.
  3. 3. Which is the best answer to "when would you pick plain def over async def?"

    Plain def endpoints run in a worker thread, so blocking calls do not stall the event loop.
  4. 4. A signed-in user without the right role calls an admin endpoint. Which status code is right?

    The server knows the user but refuses the action: 403 Forbidden.

Summary

  • Know the stack: Starlette (ASGI toolkit) plus Pydantic (validation), with type hints driving everything.
  • Explain async honestly: it helps I/O concurrency, never CPU-bound work, and blocking calls in async def hurt.
  • Dependencies are cached per request, can use yield for cleanup, and are replaced in tests with dependency_overrides.
  • Use separate request and response models; know the Pydantic v2 renames.
  • Hash passwords slowly, use short-lived JWTs, and distinguish 401 from 403.
  • Compare FastAPI with Flask and Django by trade-offs, not by slogans.

Finish the course with the one-page FastAPI cheat sheet.