Cursor Rules for
FastAPI

This rule explains FastAPI conventions and best practices for high-performance Python APIs.
Back to rules
Type
Backend
Language(s)
Python
Stats
844 views
97 copies
46 downloads
fastapi.mdc
---
description: This rule explains FastAPI conventions and best practices for high-performance Python APIs.
globs: **/*.py
alwaysApply: false
---

# FastAPI rules

- Use type hints for all function parameters and return values
- Use Pydantic models for request and response validation
- Use appropriate HTTP methods with path operation decorators (@app.get, @app.post, etc.)
- Use dependency injection for shared logic like database connections and authentication
- Use background tasks for non-blocking operations
- Use proper status codes for responses (201 for creation, 404 for not found, etc.)
- Use APIRouter for organizing routes by feature or resource
- Use path parameters, query parameters, and request bodies appropriately

The FastAPI rule helps you follow best practices when developing Python APIs with FastAPI, ensuring your code is type-safe, properly structured, and follows HTTP conventions. This rule guides Cursor's AI to provide suggestions aligned with FastAPI's recommended patterns.

What this rule does

The FastAPI rule provides guidance for developing high-performance Python APIs using the FastAPI framework. It encapsulates key best practices and conventions that make your API code more maintainable, type-safe, and properly structured.

The rule focuses on several important aspects of FastAPI development:

  • Type annotations for API functions
  • Request/response validation using Pydantic
  • Proper HTTP method usage
  • Dependency injection patterns
  • Background task implementation
  • HTTP status code usage
  • Route organization
  • Parameter handling

FastAPI best practices explained

Type hints and validation

The rule emphasizes using Python type hints for all function parameters and return values. This practice enables FastAPI's automatic documentation generation and request validation. Paired with Pydantic models, it creates a robust validation system for your API data:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = False

@app.post("/items/", response_model=Item)
def create_item(item: Item):
    return item

HTTP methods and status codes

The rule recommends using appropriate HTTP methods via FastAPI's path operation decorators (@app.get, @app.post, etc.) and returning proper status codes:

@app.post("/items/", status_code=201)
def create_item(item: Item):
    # Create the item
    return {"id": item_id, "name": item.name}

@app.get("/items/{item_id}", status_code=200)
def read_item(item_id: int):
    if item_not_found:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"id": item_id, "name": "Example item"}

Route organization and dependency injection

The rule encourages organizing routes by feature using APIRouter and implementing dependency injection for shared logic:

from fastapi import Depends, APIRouter

router = APIRouter(prefix="/users", tags=["users"])

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

@router.get("/{user_id}")
def read_user(user_id: int, db = Depends(get_db)):
    return db.query(User).filter(User.id == user_id).first()

app.include_router(router)

Using FastAPI in Cursor

The FastAPI rule (stored as fastapi.mdc in your project's .cursor/rules directory) is designed to be automatically applied when working with Python files. Since it has a glob pattern of **/*.py, Cursor will automatically invoke this rule whenever you're editing any Python file in your project.

When active, this rule provides context to Cursor's AI features, helping it understand FastAPI conventions. This means when you:

  1. Use Cmd-K to request code completion or modifications
  2. Chat with the AI about your FastAPI code
  3. Generate new FastAPI endpoints or functionality

The AI will follow the best practices defined in the rule, such as using type hints, appropriate status codes, and Pydantic models.

Usage tips

When to manually invoke the rule

While this rule automatically applies to Python files, you can also manually invoke it by typing @fastapi in the Cmd-K prompt or chat if you want to specifically focus on FastAPI guidance.

Combining with other rules

This rule works well with other Python-related rules, such as those for code style, testing, or documentation. The FastAPI rule will specifically handle the API structure and conventions while other rules can handle complementary aspects of your codebase.

Getting the most from this rule

For maximum benefit:

  • Ensure your project has the FastAPI dependencies installed
  • Use the rule when designing new endpoints or refactoring existing ones
  • Reference the rule when asking the AI to generate API validation logic or route organization

Using this rule consistently will help maintain a well-structured, type-safe FastAPI codebase that follows recommended best practices.

Want to 10x your AI skills?

Get a free account and learn to code + market your apps using AI (with or without vibes!).

Nah, maybe later