Best practices for FastAPI API Design
.cursorrules in your project root# FastAPI API Design Rules
=====================================
## Core Principles
------------------
1. **API-First Development**: Design the API first, then implement it.
2. **RESTful Architecture**: Follow RESTful principles for API endpoints.
3. **Consistency**: Maintain consistency in API endpoint naming, request and response formats, and error handling.
4. **Security**: Implement proper authentication, authorization, and data validation.
5. **Documentation**: Provide clear and concise API documentation using OpenAPI (Swagger) or similar tools.
## Code Style Guidelines
------------------------
### Naming Conventions
1. **Endpoint Names**: Use plural nouns for endpoint names (e.g., `/users`, `/products`).
2. **Variable Names**: Use descriptive and concise variable names (e.g., `user_id`, `product_name`).
3. **Function Names**: Use descriptive and concise function names (e.g., `get_user`, `create_product`).
### Typing
1. **Type Hints**: Use type hints for function parameters and return types.
2. **Model Definitions**: Define models using Pydantic or similar libraries.
### Code Organization
1. **Modularize**: Organize code into logical modules (e.g., `users`, `products`, `auth`).
2. **Keep it Simple**: Avoid complex, deeply nested code structures.
## Best Practices
------------------
1. **Use Async/Await**: Use async/await for asynchronous operations.
2. **Error Handling**: Implement proper error handling using try-except blocks and error responses.
3. **Validation**: Validate user input using Pydantic or similar libraries.
4. **Logging**: Implement logging using a logging library (e.g., Loguru).
5. **Testing**: Write unit tests and integration tests for API endpoints.
## Common Pitfalls to Avoid
---------------------------
1. **Tight Coupling**: Avoid tight coupling between modules and functions.
2. **Over-Engineering**: Avoid over-engineering API endpoints or models.
3. **Inconsistent API**: Avoid inconsistent API endpoint naming, request and response formats.
4. **Lack of Validation**: Avoid lack of validation for user input.
5. **Inadequate Error Handling**: Avoid inadequate error handling and logging.
## Example Use Cases
--------------------
### User Endpoint
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
email: str
@app.get("/users/{user_id}")
async def get_user(user_id: int):
try:
user = await get_user_from_db(user_id)
return user
except Exception as e:
raise HTTPException(status_code=404, detail="User not found")
def get_user_from_db(user_id: int):
# Simulate a database query
users = [
User(id=1, name="John Doe", email="john@example.com"),
User(id=2, name="Jane Doe", email="jane@example.com"),
]
for user in users:
if user.id == user_id:
return user
raise Exception("User not found")
```
### Product Endpoint
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Product(BaseModel):
id: int
name: str
price: float
@app.post("/products")
async def create_product(product: Product):
try:
# Simulate a database query
product.id = 1
return product
except Exception as e:
raise HTTPException(status_code=500, detail="Failed to create product")
```Comprehensive Cursor rules for Next.js 14+ with App Router, including routing, layouts, and API patterns.
Cursor rules for TypeScript with strict type checking, advanced patterns, and best practices.
Cursor rules for Tailwind CSS development with responsive design, custom components, and dark mode.
Cursor
coding
AI coding rules customize how Cursor generates and refactors code for your project. Follow these steps to install FastAPI API Design.
.cursor/rules, for Windsurf use .windsurfrulesComprehensive Cursor rules for Next.js 14+ with App Router, including routing, layouts, and API patterns.
Cursor rules for TypeScript with strict type checking, advanced patterns, and best practices.
Cursor rules for Tailwind CSS development with responsive design, custom components, and dark mode.