Skip to content
tezvyn:
Menu

How do you use a Python class as a FastAPI dependency?

Source: fastapi.tiangolo.comMediumHow cards are made

How do you use a Python class as a FastAPI dependency?

It tests whether you understand FastAPI DI beyond functions and when stateful encapsulation wins. Explain that Depends takes callable classes, centralizing setup and shared state in __init__. Red flag: claiming classes are pure syntactic sugar.

What's really being asked

This question probes whether you view FastAPI dependencies as a real architectural layer or merely as a bag of helper functions. The interviewer wants to see that you understand the dependency injection system can host callable classes, not just bare functions, and that you know when object-oriented encapsulation improves maintainability over a purely procedural approach. They are also checking if you grasp how FastAPI resolves dependencies by calling the provided callable and how that design naturally extends to classes with initialization logic.

The full answer

First, explain that Depends will invoke any callable, so a class exposing a call method works exactly like a function dependency while adding the power of object initialization. Second, describe how init becomes the natural place for sub-dependencies and configuration, turning the class into a reusable service boundary that accepts parameters at the router or endpoint level. Third, highlight concrete benefits: centralized setup logic that avoids repetition, shared mutable or immutable state across multiple path operations, cleaner unit testing through standard instantiation without mocking frameworks, and seamless integration with OpenAPI because FastAPI continues to inspect type annotations on call. Fourth, contrast this with function-based dependencies, which are inherently stateless and can scatter setup boilerplate when the same preamble is needed in many endpoints, forcing developers to rely on closures or repeated parameter lists.

The mistakes people make

A major red flag is claiming classes are only syntactic sugar and provide zero runtime or organizational benefit. Another is forgetting that FastAPI manages dependency resolution automatically, so developers should not manually instantiate the class themselves instead of letting the framework inject it through Depends. Some candidates also confuse class instantiation with dependency scope, incorrectly arguing that class-based dependencies leak state between requests unless manually managed.

What usually comes next

The interviewer may ask how you would share a database connection pool via a class dependency, how to override a class dependency during unit or integration testing using dependency overrides, or whether you should prefer a class over a factory function when the setup logic grows complex. They might also ask how sub-dependencies interact with class initialization or how type hints on call affect automatic documentation.

A concrete example

Imagine a PermissionChecker class that accepts a list of required roles in init, receives the current user from a sub-dependency, and returns a boolean or raises an HTTPException in call. Using a class keeps the role configuration declarative at the router level while encapsulating the authorization logic in one testable unit, something a single function cannot do as cleanly without awkward closures or repeated parameters across every protected endpoint.

Interview question

You need a FastAPI dependency that accepts roles in its constructor and validates the current user each request. Why use a callable class rather than a plain function?

  • a.The instance becomes a request-scoped singleton that stores the role list globally after the first call
  • b.The class __init__ receives configuration and sub-dependencies declaratively while __call__ handles per-request logic and OpenAPI integrationCorrect
  • c.Callable classes bypass automatic dependency resolution so you can instantiate them manually inside the endpoint
  • d.FastAPI only inspects type annotations on class __call__ methods, not on multi-parameter functions
Why?

A callable class lets FastAPI resolve constructor sub-dependencies and configuration via __init__ while __call__ handles per-request execution and remains visible to OpenAPI. The tempting distractor wrongly claims you must manually instantiate the class inside the endpoint, which defeats automatic injection and is explicitly flagged as a red flag.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.

See open roles