Essential cursor rules for building Python-based API servers with clean architecture, focusing on FastAPI, SQLAlchemy, and structured perfection. Includes comprehensive testing, security practices, and repository organization.
A comprehensive guide to building structured, secure Python API servers with FastAPI, focusing on clean architecture, testing, and collaborative development practices.
Follow these guidelines to maintain **structured perfection** in your Python-based API server, extensions, and tooling:
Organize your project with clear separation between server, extension, and shared code:
```
server/
├── src/
│ ├── api/ # RESTful API endpoints (FastAPI)
│ ├── models/ # ORM models (SQLAlchemy, Pydantic)
│ ├── schemas/ # Input/output validation schemas (Pydantic)
│ ├── services/ # Business logic and service layer
│ ├── utils/ # Reusable helper functions
│ ├── middleware/ # Custom FastAPI middleware
│ ├── tests/ # Unit and integration tests
│ └── __init__.py # Make folders Python modules
extension/
├── src/
│ ├── background/
│ ├── content/
│ ├── popup/
│ ├── options/
│ ├── components/
│ ├── hooks/
│ ├── utils/
│ ├── lib/
│ ├── types/
│ └── storage/
shared/
├── src/
│ ├── types/ # Shared TypeScript types
│ └── utils/ # Shared utilities
```
Version your APIs and organize endpoints logically:
```
server/src/api/
├── v1/ # Versioned API structure
│ ├── users.py # User endpoints
│ ├── auth.py # Auth endpoints
│ ├── health.py # Health checks
│ └── __init__.py
├── dependencies.py # Dependency injection helpers
├── errors.py # Custom API exception handling
├── __init__.py
```
Create an isolated development environment:
1. **Create virtual environment**: `python -m venv .venv`
2. **Activate environment**:
- Mac/Linux: `source .venv/bin/activate`
- Windows: `.venv\Scripts\activate`
3. **Upgrade pip**: `pip install --upgrade pip`
4. **Install dependencies**: `pip install -r requirements.txt`
Add to your `.gitignore`:
```gitignore
.venv/
*.pyc
__pycache__/
*.pyo
*.pyd
.Python
*.so
*.egg
*.egg-info/
dist/
build/
```
```python
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
router = APIRouter()
class User(BaseModel):
username: str
email: str
@router.post("/users", summary="Create a new user")
async def create_user(user: User):
if not user.email.endswith("@example.com"):
raise HTTPException(status_code=400, detail="Invalid email domain")
# Business logic here
return {"status": "success", "data": user.dict()}
```
Create `scripts/manage.sh` for common development tasks:
```bash
#!/bin/bash
ACTION=${1:-help}
case "$ACTION" in
"start")
echo "🚀 Starting the Python server..."
uvicorn src.api.main:app --reload
;;
"stop")
echo "🛑 Stopping the Python server..."
pkill -f uvicorn
;;
"test")
echo "🧪 Running tests..."
pytest --cov=src
;;
"setup")
echo "🔧 Setting up the environment..."
python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
;;
"help"|"")
echo "🎛️ Usage: scripts/manage.sh {start|stop|test|setup}"
;;
*)
echo "❌ Unknown action: $ACTION"
exit 1
;;
esac
```
Make executable: `chmod +x scripts/manage.sh`
Install testing dependencies:
```bash
pip install pytest pytest-cov pytest-asyncio
```
```python
from fastapi.testclient import TestClient
from src.api.main import app
client = TestClient(app)
def test_health_check():
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
def test_create_user_invalid_email():
response = client.post("/users", json={
"username": "testuser",
"email": "[email protected]"
})
assert response.status_code == 400
```
```bash
pytest
pytest --cov=src
pytest tests/test_api.py
pytest -v
```
Implement robust security measures:
1. **Input Validation**: Validate and sanitize all inputs using Pydantic
2. **Authentication**: Follow OAuth2 or token-based authentication patterns
3. **CORS Policies**: Restrict origins appropriately
4. **Rate Limiting**: Prevent abuse with rate limiting middleware
5. **SQL Injection Prevention**: Use ORM parameterized queries
6. **Sensitive Data**: Never log passwords or tokens
7. **HTTPS**: Enforce HTTPS in production
8. **Environment Variables**: Store secrets in environment variables, never in code
Keep business logic separate from API routes:
```python
class UserService:
def __init__(self, db_session):
self.db = db_session
async def create_user(self, user_data):
# Business logic here
pass
@router.post("/users")
async def create_user(user: UserCreate, db: Session = Depends(get_db)):
service = UserService(db)
return await service.create_user(user)
```
Use FastAPI's dependency injection system:
```python
from fastapi import Depends, HTTPException
from sqlalchemy.orm import Session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_current_user(token: str = Depends(oauth2_scheme)):
# Auth logic
pass
```
FastAPI automatically generates OpenAPI documentation:
Enhance documentation with:
1. **Setup**: Create virtual environment and install dependencies
2. **Structure**: Organize code following the repository structure
3. **Develop**: Write endpoints with Pydantic validation and FastAPI patterns
4. **Test**: Write unit and integration tests with pytest
5. **Secure**: Implement security checklist items
6. **Document**: Leverage automatic OpenAPI documentation
7. **Deploy**: Use uvicorn/gunicorn with proper environment configuration
```bash
./scripts/manage.sh start # Start development server
./scripts/manage.sh test # Run tests
./scripts/manage.sh setup # Initial setup
pytest --cov=src # Run tests with coverage
pytest -v tests/ # Verbose test output
gunicorn -w 4 -k uvicorn.workers.UvicornWorker src.api.main:app
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/mcp-to-atc-python-bridge-development/raw