fastapi

A set of coding guidelines for FastAPI, a Python framework for building web APIs. It covers project organization, data models, database access, routes, and tests.

In plain words
What is it for?
Use it when creating or reviewing FastAPI applications, including API routes, request and response data, database code, project structure, and tests.
Why use it?
It gives an agent consistent patterns for structuring FastAPI projects instead of making design decisions from scratch each time.

Cursor rule for Cursor

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.

agentmods
npx agentmods add rules/kok-o/koko-contextos-agents/fastapi
Clone the repo
git clone --depth 1 https://github.com/kok-o/koko-contextos-agents

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 898 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
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 $0.00000 $0.00898
Opus 5 $0.00000 $0.00449
Sonnet 5 $0.00000 $0.00180
Haiku 4.5 $0.00000 $0.00090

Measured 2d ago against content hash 78b78ef666a8, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

fastapi 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 2d 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.

.cursor/rules/fastapi.mdc · 152 lines

How it starts

The opening of the file, as written. The whole thing — 152 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Skill: FastAPI

FastAPI

Overview

A brief summary of what the skill does and its core philosophy.

When to Use

Context for when this skill is applicable.

Rules & Patterns

FastAPI — Best Practices

Project Structure

app/
├── main.py              # App entry, CORS, middleware
├── config.py            # Settings with Pydantic BaseSettings
├── database.py          # Database session, engine
├── models/              # SQLAlchemy models
│   ├── __init__.py
│   └── user.py
├── schemas/             # Pydantic schemas (request/response)
│   ├── __init__.py
│   └── user.py
├── api/                 # Route handlers
│   ├── __init__.py
│   ├── deps.py          # Dependency injection
│   └── v1/
│       ├── __init__.py
│       └── users.py
├── services/            # Business logic
│   └── user_service.py
├── repositories/        # Database access
│   └── user_repo.py
└── tests/
    └── test_users.py

Pydantic Models

from pydantic import BaseModel, EmailStr, Field

class UserCreate(BaseModel):
    email: EmailStr
    name: str = Field(..., min_length=1, max_length=100)
    
class UserResponse(BaseModel):
    id: int
    email: str
    name: str
    
    model_config = ConfigDict(from_attributes=True)

Dependency Injection

from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with async_session() as session:
        yield session

async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: AsyncSession = Depends(get_db)
) -> User:
    # Verify token, return user
    ...

Async

  • Use async for all I/O operations (database, HTTP calls, file I/O)
  • Never block the event loop — no sync I/O in async endpoints
  • Use asyncio.gather for parallel async operations
  • Background tasksBackgroundTasks for non-critical work

Error Handling

from fastapi import HTTPException

class AppException(HTTPException):
    def __init__(self, status_code: int, detail: str, code: str):
        super().__init__(status_code=status_code, detail=detail)
        self.code = code

Read the full file on GitHub · 152 lines

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. 2d ago First seen · 152 lines · 0 tokens per session scan A 78b78ef666a8

Subscribe to this mod's changes

fastapi is a cursor rule published in the GitHub repository kok-o/koko-contextos-agents (2 stars, last pushed 3d ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 898 tokens. 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-08-31.