

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
1# AGENTS.md — fastapi23## Project Overview45FastAPI is a modern, high-performance Python web framework for building APIs, based on standard Python type hints. It is built on top of Starlette for web functionality and Pydantic for data validation and serialization. The project's core philosophy is to provide developers with a world-class experience through robust tools, predictable behavior, and frictionless workflows, enabling the creation of clear, performant, and automatically documented APIs.67## Tech Stack89* **Primary Language**: Python10* **Core Frameworks**: Starlette (ASGI foundation), Pydantic (data validation/serialization)11* **Typing**: `typing-extensions`, `typing-inspection`12* **Ecosystem**: Uvicorn (ASGI server), HTTPX (async HTTP client for testing)13* **Build System**: `pdm-backend`14* **Testing**: `pytest`, `anyio` (for async tests), `coverage`15* **Code Quality**: `ruff` (linter and formatter), `black` (formatter), `mypy` (static type checker)16* **Documentation**: `mkdocs-material`, `mkdocstrings`1718## Architecture1920The project is organized with a clear separation of concerns, primarily distinguishing between the core framework logic, tests, and documentation.2122* `fastapi/`: The core source code of the framework.23 * `applications.py`: Contains the main `FastAPI` application class.24 * `routing.py`: Defines the `APIRouter` and handles all routing logic.25 * `dependencies/`: Implements the dependency injection system.26 * `openapi/`: Manages the OpenAPI schema generation.27 * `security/`: Provides built-in security utilities like OAuth2 and API Keys.28* `tests/`: Contains all unit, integration, and end-to-end tests. The directory structure mirrors the `fastapi/` source directory.29* `docs_src/`: The raw Markdown source files for the official documentation.30* `scripts/`: Holds utility scripts for development, maintenance, and CI/CD.31* `pyproject.toml`: The central configuration file for project metadata, dependencies, and all development tooling.3233## Code Style3435The project enforces a strict, automated code style to ensure consistency and readability.3637* **Formatting**: All code is formatted using `black` and `ruff format`. Manual formatting adjustments are not permitted. The command `ruff format .` should be run before committing.38* **Linting**: `ruff check` is used for linting. All code must be free of its errors and warnings, which includes rules for ordered imports, no unused variables, and other best practices.39* **Static Typing**: This is a non-negotiable cornerstone of the codebase.40 * All function signatures, method signatures, variables, and class attributes **must** have explicit type hints.41 * The entire codebase must pass `mypy .` static analysis without any errors. This is critical for preventing bugs and ensuring a great developer experience via IDE autocompletion.4243An example of a correctly styled and typed function signature:4445```python46from typing import Any, Dict4748def create_item(item_id: int, data: Dict[str, Any]) -> Dict[str, Any]:49 # function implementation50 return {"item_id": item_id, **data}51```5253## Anti-Patterns & Restrictions5455To maintain performance, concurrency safety, and maintainability, the following patterns are strictly forbidden.56571. **NEVER perform blocking I/O in `async` routes.** A synchronous call like `requests.get()` or `time.sleep()` in an `async` function will freeze the entire server's event loop. Always use `async`-compatible libraries (e.g., `httpx`, `asyncpg`). For CPU-bound work, use `asyncio.to_thread()`.582. **NEVER use global mutable variables for request state.** This leads to race conditions, data leaks between requests, and makes testing impossible. All per-request state must be managed via the Dependency Injection system (`Depends`).593. **NEVER manually validate request data.** This bypasses Pydantic's validation, error reporting, and automatic OpenAPI schema generation. Always define a Pydantic `BaseModel` and use it as a type hint in your endpoint function to let FastAPI handle validation automatically.604. **NEVER create monolithic routers.** A single file with hundreds of routes is unmaintainable. Group related endpoints into separate `APIRouter` instances in different modules and include them in the main application using `app.include_router()`.6162## Database & State Management6364State and data management conventions are designed to ensure concurrency safety, testability, and clear data contracts.6566* **Golden Rule of State**: **Never use global mutable state.** Global variables modified during requests are a source of race conditions and are forbidden. For application-wide, read-only configuration, use `pydantic-settings` to load settings at startup.67* **Per-Request State**: The **Dependency Injection (`Depends`)** system is the **only** approved way to manage request-scoped state and resources, such as database sessions.68* **Resource Management**: For resources that need setup and teardown (like database connections), use a `yield` statement within a dependency function. This pattern ensures resources are properly cleaned up, even in case of errors.6970```python71# Correct pattern for managing a database session72def get_db() -> Generator[Session, None, None]:73 db = SessionLocal()74 try:75 yield db # Provide the session to the endpoint76 finally:77 db.close() # Guarantee the session is closed78```7980* **Data Contracts**: Use Pydantic `BaseModel` classes for all data entering or leaving the API. Define separate models for request bodies and use the `response_model` parameter in decorators to control response bodies, preventing accidental data leakage.8182## Error Handling & Logging8384The framework uses a structured approach to error handling and logging.8586* **Client Errors**: For all expected client-side errors (e.g., resource not found, permission denied), you **must** raise `fastapi.HTTPException` with the appropriate status code.87* **Validation Errors**: `RequestValidationError` is raised automatically by the framework when incoming request data fails Pydantic validation. The default handler returns a `422 Unprocessable Entity` response with detailed error information.88* **Unhandled Exceptions**: Custom exception handlers can be added to the application to catch unhandled server errors and return a consistent, formatted error response instead of a generic 500 error.89* **Logging**: **Do not use `print()` statements.** All logging within the framework must be done using the central logger obtained via `logging.getLogger("fastapi")`.9091## Testing Commands9293Before submitting code, run the full local quality suite using these commands from the project root.9495* **Run all tests**:96```bash97 pytest98```99* **Format code**:100```bash101 ruff format .102```103* **Lint and auto-fix code**:104```bash105 ruff check . --fix106```107* **Run static type checking**:108```bash109 mypy .110```111112## Testing Guidelines113114A multi-layered testing strategy ensures the framework's stability and correctness.115116* **Framework**: All tests are written using `pytest`.117* **Test Client**: Integration tests for API endpoints must use `fastapi.testclient.TestClient`, which wraps `httpx` to send requests to the application.118* **File Placement**: Test files are located in the `tests/` directory. The structure of `tests/` mirrors the `fastapi/` source directory.119* **Asynchronous Tests**: Tests for `async` code must be marked appropriately and are executed using the `anyio` pytest backend.120* **Static Analysis as a Test**: Passing `mypy` checks is a mandatory part of the testing suite. Code that fails type checking is considered broken.121* **Mocking**: Use standard mocking libraries compatible with `pytest` (e.g., `unittest.mock` or `pytest-mock`) to test components in isolation.122* **Coverage**: New code should have high test coverage. Use `coverage` to identify and cover untested code paths.123124## Security & Compliance125126* **Vulnerability Reporting**: Security vulnerabilities **must not** be reported via public GitHub issues. Report them privately to `security@tiangolo.com`.127* **Authentication & Authorization**: When implementing security features, leverage the framework's built-in security schemes from `fastapi.security` (e.g., `OAuth2PasswordBearer`, `APIKeyHeader`).128* **Dependency Updates**: Keep all project dependencies up-to-date, especially FastAPI itself, to ensure you have the latest security patches.129130## Dependencies & Environment131132* **Dependency Manager**: The project uses `pdm` for dependency and environment management. The single source of truth for dependencies is `pyproject.toml`.133* **Dependency Groups**:134 * `[project.dependencies]`: Core runtime dependencies required for the framework to function.135 * `[project.optional-dependencies]`: Optional features users can install (e.g., `[all]`, `[standard]`).136 * `[tool.pdm.dev-dependencies]`: Development-only dependencies, organized into groups like `tests` and `docs`.137* **Adding Dependencies**:138 * To add a runtime dependency: `pdm add <package>`139 * To add a development dependency to a group: `pdm add -dG <group> <package>` (e.g., `pdm add -dG tests pytest-mock`)140141## PR & Git Rules142143* **Branching Convention**: Create feature branches from an up-to-date `main` branch. Name branches with a prefix indicating the work type, e.g., `feature/my-new-feature` or `fix/bug-in-routing`.144* **Commit Messages**: Follow conventional commit message standards for clarity.145* **Pull Request Process**:146 1. Open PRs against the `main` branch.147 2. The PR description must clearly explain the "what" and "why" of the change and link to any relevant GitHub issues.148 3. All CI checks (testing, linting, type checking) must pass before a PR can be merged.149 4. Engage with reviewer feedback and push updates to your branch to update the PR.150* **Contributing Guide**: Before starting any work, you must read the detailed guidelines at [Development - Contributing](https://fastapi.tiangolo.com/contributing/).151152## Documentation Standards153154* **Public Documentation**: The public-facing documentation is built with `MkDocs` and the `Material for MkDocs` theme from source files in `docs_src/`.155* **Docstrings**: All public functions, classes, and methods **must** have clear, comprehensive docstrings. API reference documentation is generated automatically from these docstrings using `mkdocstrings`.156* **Type Hints in Docs**: Type hints are a fundamental part of the documentation and are rendered automatically. Ensure they are correct and explicit.157* **Examples**: All new features or significant changes must be accompanied by documentation updates, including clear, complete, and runnable examples.158159## Common Patterns160161These are recurring design patterns and strict rules that must be followed throughout the codebase.162163* **Declarative Routing with Decorators**: ALWAYS define API endpoints using decorators on path operation functions. This keeps routing logic clean and co-located with the implementation.164```python165 from fastapi import FastAPI166167 app = FastAPI()168169 @app.get("/items/{item_id}")170 async def read_item(item_id: int):171 return {"item_id": item_id}172```173* **Dependency Injection for Resources**: ALWAYS use the `Depends` system for managing per-request resources like database sessions. NEVER create global, shared resources for requests.174```python175 # The correct pattern for managing a database session176 def get_db() -> Generator[Session, None, None]:177 db = SessionLocal()178 try:179 yield db # The session is provided to the endpoint180 finally:181 db.close() # The session is guaranteed to be closed182183 @app.get("/items/")184 async def read_items(db: Session = Depends(get_db)):185 return db.query(Item).all()186```187* **Pydantic for Data Contracts**: ALWAYS define `pydantic.BaseModel` classes for all request and response data structures. This provides automatic validation, serialization, and documentation.188* **Async for I/O**: ALWAYS use `async def` for path operation functions and use `await` with `async`-compatible libraries for any I/O-bound operations (e.g., database calls, external API requests) to avoid blocking the event loop.189190## Agent Workflow / SOP191192To contribute a new feature or fix, follow this standard operating procedure:1931941. **Sync `main`**: Ensure your local `main` branch is up-to-date with the upstream repository.1952. **Create Branch**: Create a new feature branch from `main` (e.g., `git checkout -b feature/my-new-feature`).1963. **Implement Changes**: Write the code for the new feature or fix, strictly adhering to the project's code style, typing, and architectural conventions.1974. **Write Tests**: Add comprehensive `pytest` tests covering the new code. Include tests for success cases, edge cases, and error conditions.1985. **Write Documentation**: Update the documentation in the `docs_src/` directory. Add a new page or update an existing one to explain the feature, providing clear, runnable examples.1996. **Local Verification**: Before pushing, run the entire local quality suite to ensure everything passes:200 * `pytest`201 * `ruff format .`202 * `ruff check . --fix`203 * `mypy .`2047. **Push and Open PR**: Push your branch to the remote and open a Pull Request against the `main` branch. Provide a detailed description of your changes.2058. **Review and Iterate**: Respond to any feedback from code reviewers. Push subsequent commits to your branch to update the PR.206207## Few-Shot Examples208209This example demonstrates the critical rule of using non-blocking I/O in `async` functions.210211### Bad: Blocking I/O in an `async` route212213This code uses the synchronous `requests` library, which will block the entire server's event loop, preventing it from handling any other requests until this one is complete. This is a severe performance anti-pattern.214215```python216# ANTI-PATTERN: This will block the entire application!217@app.get("/bad")218async def bad_request():219 import requests220 response = requests.get("http://example.com") # BLOCKING!221 return response.json()222```223224### Good: Non-blocking I/O in an `async` route225226This code uses the `httpx` library, which is `async`-compatible. The `await` keyword correctly pauses the function, allowing the event loop to handle other tasks while waiting for the network response, thus maintaining high concurrency.227228```python229# CORRECT PATTERN: Non-blocking I/O230@app.get("/good")231async def good_request():232 import httpx233 async with httpx.AsyncClient() as client:234 response = await client.get("http://example.com") # NON-BLOCKING!235 return response.json()236237```
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| originalankur/GenerateAgents.mdAGENTS.md · 254 | AGENTS.md | setupteststylearch+8 | 93/100 | 14 days ago | |
| originalankur/GenerateAgents.mdprojects/flagsmith/AGENTS.md · 254 | AGENTS.md | setuptestlint-formatstyle+9 | 88/100 | 14 days ago | |
| originalankur/GenerateAgents.mdprojects/flask/AGENTS.md · 254 | AGENTS.md | lint-formatstylesecuritydo-not | 89/100 | 14 days ago | |
| originalankur/GenerateAgents.mdprojects/dspy/AGENTS.md · 254 | AGENTS.md | setupbuildtestlint-format+11 | 96/100 | 14 days ago |
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| unoplat/unoplat-code-confluenceunoplat-code-confluence-frontend/AGENTS.md · 95 | AGENTS.md | setupbuildtestlint-format+6 | 100/100 | 13 days ago | |
| n8n-io/n8npackages/@n8n/agents/AGENTS.md · 201k | AGENTS.md | buildteststylearch+3 | 100/100 | 14 days ago | |
| deepseek-ai/deepseek-harnessnative/landlock-run/AGENTS.md · 104k | AGENTS.md | setupteststylearch+3 | 100/100 | today | |
| vllm-project/vllmAGENTS.md · 89k | AGENTS.md | setuptestlint-formatstyle+5 | 100/100 | 14 days ago | |
| SkeneTechnologies/skene-cookbookAGENTS.md · 52 | AGENTS.md | setupbuildtestlint-format+7 | 100/100 | 13 days ago | |
| OnlyTerp/prompt-cache-skillsAGENTS.md · 113 | AGENTS.md | setupbuildtestlint-format+5 | 100/100 | 14 days ago | |
| netdata/netdatasrc/go/plugin/ibm.d/AGENTS.md · 80k | AGENTS.md | buildtestlint-formatarch+3 | 99/100 | today | |
| unoplat/unoplat-code-confluenceunoplat-code-confluence-query-engine/AGENTS.md · 95 | AGENTS.md | setupbuildtestlint-format+5 | 98/100 | 13 days ago |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/originalankur-generateagents-md-projects-fastapi-agents)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.