fastapi-dependency-injection

fastapi-dependency-injection is a cursor rule for Cursor from holtwood/awesome-cursorrules-zh. It costs 7 tokens per session (806 once invoked), scanned A, original, MIT.

Guidelines for using dependency injection in FastAPI. Dependency injection lets a function receive services such as database sessions, settings, or the current user instead of creating them itself.

In plain words
What is it for?
Use it to provide authentication, API keys, database sessions, configuration, and other request-level resources to API routes.
Why use it?
It keeps components easier to test, reuse, and maintain, while also supporting shared setup and cleanup.

Cursor rule for Cursor

Written for Cursor: a Cursor rule (.mdc).

Good fit Use it to provide authentication, API keys, database sessions, configuration, and other request-level resources to API routes.

Compare 6 cursor rules from other repositories ↓
Install with agentmods
npx agentmods add rules/holtwood/awesome-cursorrules-zh/fastapi-dependency-injection
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Clone the repo
git clone --depth 1 https://github.com/holtwood/awesome-cursorrules-zh

Made for: Cursor.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for fastapi-dependency-injection

README.md
[![agentmods](https://agentmods.dev/badge/rules/holtwood/awesome-cursorrules-zh/fastapi-dependency-injection/github.svg)](https://agentmods.dev/rules/holtwood/awesome-cursorrules-zh/fastapi-dependency-injection)
Your own site
<a href="https://agentmods.dev/rules/holtwood/awesome-cursorrules-zh/fastapi-dependency-injection"><img src="https://agentmods.dev/badge/rules/holtwood/awesome-cursorrules-zh/fastapi-dependency-injection/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for fastapi-dependency-injection

Your own site · 80×15
<a href="https://agentmods.dev/rules/holtwood/awesome-cursorrules-zh/fastapi-dependency-injection"><img src="https://agentmods.dev/badge/rules/holtwood/awesome-cursorrules-zh/fastapi-dependency-injection.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 7 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 806 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00007 $0.00806
Opus 5 $0.00003 $0.00403
Sonnet 5 $0.00001 $0.00161
Haiku 4.5 $0.00001 $0.00081

Measured 6d ago against content hash 2a87415f3178, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-09, from the pricing page.

Security

Grade A, and why

fastapi-dependency-injection scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 6d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

docs/rules/backend/python/fastapi-api-example/fastapi-dependency-injection.mdc · 93 lines

What it actually says

FastAPI 依赖注入

本规则集定义了在 FastAPI 应用程序中如何有效地使用依赖注入(Dependency Injection, DI),以提高代码的可测试性、可维护性和模块化。

1. 什么是依赖注入?

依赖注入是一种设计模式,它允许您将组件所需的依赖项(如数据库会话、配置设置、认证用户等)“注入”到组件中,而不是让组件自己创建或查找这些依赖项。这使得组件更加独立和可重用。

2. FastAPI 中的依赖注入

FastAPI 内置了一个强大且易于使用的依赖注入系统。您可以通过在路径操作函数中声明参数来定义依赖项。

2.1 简单的依赖

  • 函数作为依赖: 最简单的依赖是一个函数,它返回一个值。FastAPI 会在调用路径操作函数之前执行这个依赖函数,并将其返回值作为参数传递给路径操作函数。
from fastapi import FastAPI, Depends

app = FastAPI()

def get_current_user():
    # 假设这里是从请求头或数据库获取当前用户
    return {"username": "john_doe"}

@app.get("/users/me/")
async def read_current_user(current_user: dict = Depends(get_current_user)):
    return current_user

2.2 带参数的依赖

  • 依赖也可以有自己的依赖: 依赖函数本身也可以声明依赖项,形成依赖链。
from fastapi import FastAPI, Depends, HTTPException, status

app = FastAPI()

def get_api_key():
    # 假设这里从请求头获取 API Key
    api_key = "some_api_key"
    if api_key != "valid_key":
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API Key")
    return api_key

@app.get("/protected-data/")
async def get_protected_data(api_key: str = Depends(get_api_key)):
    return {"data": "This is protected data", "api_key_used": api_key}

2.3 yield 依赖 (带清理代码)

  • 资源管理: 对于需要在使用后进行清理的资源(如数据库会话、文件句柄),可以使用 yield 依赖。yield 之前的代码会在请求处理前运行,yield 之后的代码会在请求处理后运行。
from fastapi import FastAPI, Depends

app = FastAPI()

class DatabaseSession:
    def __init__(self):
        print("Opening database session")

    def close(self):
        print("Closing database session")

def get_db():
    db = DatabaseSession()
    try:
        yield db
    finally:
        db.close()

@app.get("/items/")
async def read_items(db: DatabaseSession = Depends(get_db)):
    # 使用数据库会话
    return {"message": "Items read using DB session"}

3. 依赖注入的优势

  • 代码重用: 依赖项可以被多个路径操作函数重用。
  • 可测试性: 易于为路径操作函数编写单元测试,因为可以轻松地模拟或替换依赖项。
  • 解耦: 路径操作函数不需要关心如何获取其依赖项,从而实现更好的解耦。
  • 声明式: 通过函数参数声明依赖项,代码更加清晰和声明式。
Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 6d ago First seen · 93 lines · 7 tokens per session scan A 2a87415f3178

Subscribe to this mod's changes

fastapi-dependency-injection is a cursor rule published in the GitHub repository holtwood/awesome-cursorrules-zh (233 stars, last pushed 1mo ago), licensed MIT. It adds 7 tokens to every session and 806 once invoked, about $0.0000 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.