---
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.
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:
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
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"}
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)
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:
The AI will follow the best practices defined in the rule, such as using type hints, appropriate status codes, and Pydantic models.
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.
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.
For maximum benefit:
Using this rule consistently will help maintain a well-structured, type-safe FastAPI codebase that follows recommended best practices.