Dependencies - First Steps
Part of: FastAPI Basics
Learn FastAPI's dependency injection system to share logic and create reusable components.
What You'll Learn
Theory and Concepts
Dependencies - First Steps
🎯 What You'll Learn
- Understand FastAPI's dependency injection system
- Create dependency functions for shared logic
- Use Depends() to inject dependencies into path operations
- Share reusable components across multiple endpoints
📚 Theory
FastAPI has a very powerful but intuitive Dependency Injection system. It is designed to be very simple to use, and to make it very easy for any developer to integrate other components with FastAPI.
What is "Dependency Injection"
"Dependency Injection" means that there is a way for your code (your path operation functions) to declare things that it requires to work and use: "dependencies". FastAPI will take care of providing your code with those needed dependencies ("inject" the dependencies).
This is very useful when you need to:
- Have shared logic (the same code logic again and again)
- Share database connections
- Enforce security, authentication, role requirements, etc.
- And many other things...
All these, while minimizing code repetition.
🔧 Key Concepts
Creating a Dependency
A dependency is just a function that can take all the same parameters that a path operation function can take:
[Code Example]
It has the same shape and structure as your path operation functions, but without the decorator.
Using Dependencies
You use Depends in your path operation parameters:
[Code Example]
How it Works
When a request arrives, FastAPI will:
1. Call your dependency function with the correct parameters
2. Get the result from your function
3. Assign that result to the parameter in your path operation function
Sharing Dependencies
You can use the same dependency in multiple path operations:
[Code Example]
This way you write shared code only once, and FastAPI takes care of calling it for your path operations.
💡 Best Practices
- Keep dependencies simple: Focus on single responsibilities
- Use type annotations: They help with editor support and validation
- Share common dependencies: Reuse the same dependency across multiple endpoints
- Async compatibility: You can mix async def and def dependencies freely
🔗 Additional Resources
- FastAPI Dependencies Documentation
Helpful Hint
Dependencies are just functions that can be injected into path operations using Depends() - think of them as reusable components that handle shared logic.