0Pricing
FastAPI Backend Development Bootcamp · 课时

注入常用依赖

为数据库会话、用户身份验证或各端点共享的配置实现常用依赖。

注入常用依赖 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to Common Dependencies

In FastAPI, dependencies are powerful. They help you share logic, manage resources, and keep your code clean.

Common dependencies are functions or classes that you reuse across many API endpoints. This prevents repetitive code and makes your application easier to maintain and test.

Think of them as reusable building blocks for your API.

Injecting Shared Configuration

Many applications need global settings, like API keys or database URLs. By injecting configuration, you can easily access these settings in any endpoint without resorting to global variables.

This keeps your configuration flexible and easy to update.

Demo: Simple Config Dependency

Let's create a dependency that returns a simple settings dictionary. In a real application, this might load from environment variables using Pydantic's BaseSettings.

from fastapi import FastAPI, Depends

app = FastAPI()

# This function acts as our dependency
def get_settings():
    return {"app_name": "CoddyKit API", "version": "1.0.0"}

@app.get("/info")
def read_info(settings: dict = Depends(get_settings)):
    return {"message": f"Welcome to {settings['app_name']} v{settings['version']}"}

# To run this:
# 1. Save as main.py
# 2. Run 'uvicorn main:app --reload'
# 3. Go to http://127.0.0.1:8000/info

Database Session Management

A common task for backend APIs is interacting with a database. Each request typically needs its own unique database "session" or connection.

Managing these sessions manually in every endpoint is tedious and error-prone. A dependency can handle creating and closing them automatically for you.

Demo: Database Session Dependency

Here's a simplified example of a get_db dependency. In a real application, this would connect to a database using an ORM like SQLAlchemy.

The yield keyword is key here!

from fastapi import FastAPI, Depends
from typing import Generator

app = FastAPI()

# This simulates a database session.
# In a real app, this would be a SQLAlchemy session.
class MockDBSession:
    def __init__(self):
        print("Opening DB session...")
    def close(self):
        print("Closing DB session...")
    def query(self, item_id: int):
        return {"id": item_id, "name": f"Item {item_id}"}

def get_db() -> Generator:
    db = MockDBSession()
    try:
        yield db  # This is where the endpoint gets the 'db' object
    finally:
        db.close() # This runs after the request is finished

@app.get("/items/{item_id}")
def read_item(item_id: int, db: MockDBSession = Depends(get_db)):
    # The 'db' object is provided by the dependency
    return db.query(item_id)

# To run this:
# 1. Save as main.py
# 2. Run 'uvicorn main:app --reload'
# 3. Go to http://127.0.0.1:8000/items/1

The Magic of `yield`

The yield keyword in our get_db function is very important.

  • Code before yield runs before the endpoint function. This is for setup (e.g., opening a database connection).
  • Code after yield runs after the endpoint function and its response. This is for teardown (e.g., closing the connection).

This pattern is called a "dependency with yield" or a "context manager dependency".

Injecting User Authentication

Most APIs need to know who is making a request. Authentication dependencies extract user information from request headers (like an API key or JWT token) and make it available to your endpoints.

This keeps your authentication logic separate and reusable across many routes.

Demo: Current User Dependency

Here's a basic dependency that simulates getting the current user. In a real application, this would involve validating a token from the request headers.

If the user isn't authenticated, it can raise an HTTPException to stop the request early.

from fastapi import FastAPI, Depends, HTTPException, status
from typing import Optional

app = FastAPI()

class User:
    def __init__(self, username: str, email: Optional[str] = None):
        self.username = username
        self.email = email

# This dependency simulates fetching the current user
def get_current_user(token: str = "some_valid_token") -> User:
    # In a real app, 'token' would come from request headers
    # and be validated against a database or auth service.
    if token != "some_valid_token":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return User(username="jane_doe", email="jane@example.com")

@app.get("/me")
def read_current_user(current_user: User = Depends(get_current_user)):
    return {"username": current_user.username, "email": current_user.email}

# To run this:
# 1. Save as main.py
# 2. Run 'uvicorn main:app --reload'
# 3. Go to http://127.0.0.1:8000/me

Chaining & Reusing Dependencies

Dependencies can also depend on other dependencies! This allows for complex logic to be broken down into smaller, manageable pieces.

For example, a "current admin user" dependency might first depend on "current user", then check if that user has admin privileges.

This modularity is a core strength of FastAPI's dependency injection.

Check Your Understanding

Consider the following FastAPI dependency:

from fastapi import HTTPException, status

def check_api_key(api_key: str = "SECRET_KEY"):
    if api_key != "VALID_API_KEY":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid API Key"
        )
    return True

If an endpoint uses Depends(check_api_key) and a request comes in without the correct API_KEY, what will happen?

Common Dependencies: Key Takeaways

We've explored how to inject common dependencies in FastAPI:

  • Configuration: Share application settings easily across endpoints.
  • Database Sessions: Manage database connections per request using yield for proper setup and teardown.
  • User Authentication: Centralize logic for identifying and validating users.

Dependencies promote clean, reusable, and testable code by keeping cross-cutting concerns separate from your main endpoint logic.

常见问题解答

「注入常用依赖」课时是免费的吗?

是的 — 「注入常用依赖」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「注入常用依赖」这节课中我会学到什么?

为数据库会话、用户身份验证或各端点共享的配置实现常用依赖。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「注入常用依赖」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 理解 FastAPI 中的依赖
  2. 注入常用依赖
  3. 基于类的依赖与 Yield 依赖
  4. 全局依赖与子依赖
← 返回 FastAPI Backend Development Bootcamp