理解 FastAPI 中的依赖
探索依赖注入的概念,以及它如何简化 FastAPI 中的代码组织和复用。
理解 FastAPI 中的依赖 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is Dependency Injection?
Ever wished your functions could magically get the tools they need? That's what Dependency Injection (DI) helps with!
In FastAPI, DI is a powerful design pattern where components (like your API endpoints) don't create their dependencies. Instead, they declare what they need, and FastAPI "injects" them.
Benefits of FastAPI DI
FastAPI uses DI extensively because it makes your code:
- Reusable: Write logic once, use everywhere.
- Testable: Easily swap real services with mock versions for tests.
- Clean: Keeps path operation functions focused on their main task.
- Maintainable: Changes to dependencies don't ripple through your entire app.
Crafting a Basic Dependency
A dependency in FastAPI is usually just a regular Python function.
This function can perform any setup, validation, or resource acquisition needed before your main API logic runs. It can even return a value.
FastAPI will automatically call this function and pass its result to your endpoint.
Injecting into an Endpoint
To use a dependency, you declare it as a parameter in your path operation function, using FastAPI's special Depends function.
When a request comes in, FastAPI checks your endpoint's parameters, resolves any dependencies, and then calls your endpoint with the results.
Simple Dependency in Action
Let's see a basic dependency that returns a simple string. Notice how get_message is called by FastAPI before read_root.
from fastapi import FastAPI, Depends
app = FastAPI()
def get_message():
return "Hello from dependency!"
@app.get("/")
async def read_root(message: str = Depends(get_message)):
return {"message": message}
# To run this:
# 1. Save as main.py
# 2. pip install fastapi uvicorn
# 3. uvicorn main:app --reload
# Then visit http://127.0.0.1:8000/Dependencies Can Have Params
Dependencies aren't limited to simple functions. They can also take their own parameters, which FastAPI will also resolve.
This means a dependency can itself depend on other dependencies, forming a chain! It's super powerful for building complex logic.
Dependency Taking Input
Here, greet_user is a dependency that takes a name. If name is not provided in the query, it defaults to 'Guest'.
from fastapi import FastAPI, Depends
app = FastAPI()
def greet_user(name: str = "Guest"):
return f"Hello, {name}!"
@app.get("/greet/")
async def say_hello(greeting: str = Depends(greet_user)):
return {"greeting": greeting}
# To run this:
# uvicorn main:app --reload
# Visit http://127.0.0.1:8000/greet/
# And http://127.0.0.1:8000/greet/?name=CoddyUnderstanding `Depends()`
The magical piece connecting your endpoint to a dependency is the Depends() function.
- It tells FastAPI: "Hey, before running this function, please resolve this dependency."
- You pass your dependency function (or callable) directly to
Depends(), not its result. - FastAPI handles calling your dependency function for you.
Use Cases for Dependencies
Dependencies are perfect for:
- Database connections: Get a session for each request.
- Authentication: Verify user credentials.
- Authorization: Check user roles/permissions.
- Shared logic: Any code that multiple endpoints need.
They keep your API clean and focused.
Dependency Concept Check
Consider the following FastAPI code snippet:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_db_session():
# Imagine this connects to a database
return "Database Session Object"
@app.get("/items/")
async def read_items(session: str = Depends(get_db_session)):
return {"message": f"Using {session}"}What will be the value of session inside the read_items function when a request is made to /items/?
Recap: Dependencies Unveiled
You've taken a crucial step in mastering FastAPI by understanding Dependency Injection!
- Dependencies are functions FastAPI runs before your endpoint.
- They keep your code modular, reusable, and testable.
- You declare them using
param: Type = Depends(your_dependency_func).
Next, we'll dive into more common and advanced dependency patterns!
常见问题解答
「理解 FastAPI 中的依赖」课时是免费的吗?
是的 — 「理解 FastAPI 中的依赖」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
「理解 FastAPI 中的依赖」这节课中我会学到什么?
探索依赖注入的概念,以及它如何简化 FastAPI 中的代码组织和复用。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 FastAPI Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「理解 FastAPI 中的依赖」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 理解 FastAPI 中的依赖
- 注入常用依赖
- 基于类的依赖与 Yield 依赖
- 全局依赖与子依赖