Overview - Class-based dependencies
What is it?
Class-based dependencies in FastAPI let you use a class to provide shared logic or data to your API endpoints. Instead of writing a function for dependency injection, you create a class with methods that FastAPI calls automatically. This helps organize code better and manage state or resources cleanly. It works by FastAPI creating an instance of your class and calling its __call__ method when needed.
Why it matters
Without class-based dependencies, you might write many separate functions that can get messy and hard to maintain, especially when sharing state or resources like database connections. Using classes groups related logic and data together, making your code cleaner and easier to understand. This also helps avoid repeating setup code and makes testing simpler. Without this, your API code can become tangled and error-prone.
Where it fits
Before learning class-based dependencies, you should understand basic FastAPI dependency injection using functions. After mastering this, you can explore advanced dependency features like dependency overrides, async dependencies, and integrating with external libraries or databases.