Build high-performance Python APIs with FastAPI, async/await, and proper dependency injection.
# Python FastAPI Best Practices
Master API development with FastAPI using Google Antigravity IDE. This comprehensive guide covers routing, validation, authentication, and performance optimization.
## Why FastAPI?
FastAPI provides high-performance async APIs with automatic documentation. Google Antigravity IDE's Gemini 3 engine suggests optimal patterns and security configurations.
## Application Structure
```python
# app/main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api import router
from app.core.config import settings
from app.db.session import engine, Base
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
# Shutdown
await engine.dispose()
app = FastAPI(
title=settings.PROJECT_NAME,
version="1.0.0",
lifespan=lifespan,
docs_url="/api/docs",
redoc_url="/api/redoc",
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(router, prefix="/api/v1")
```
## Pydantic Models
```python
# app/schemas/user.py
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, EmailStr, Field, field_validator
import re
class UserBase(BaseModel):
email: EmailStr
name: str = Field(..., min_length=2, max_length=100)
class UserCreate(UserBase):
password: str = Field(..., min_length=8, max_length=100)
@field_validator("password")
@classmethod
def validate_password(cls, v: str) -> str:
if not re.search(r"[A-Z]", v):
raise ValueError("Password must contain uppercase letter")
if not re.search(r"[0-9]", v):
raise ValueError("Password must contain number")
return v
class UserUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=2, max_length=100)
bio: Optional[str] = Field(None, max_length=500)
class UserResponse(UserBase):
id: str
created_at: datetime
updated_at: datetime
model_config = {"from_attributes": True}
class UserListResponse(BaseModel):
data: list[UserResponse]
total: int
page: int
limit: int
```
## Route Handlers
```python
# app/api/endpoints/users.py
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_db, get_current_user
from app.schemas.user import UserCreate, UserUpdate, UserResponse, UserListResponse
from app.services import user_service
from app.models.user import User
router = APIRouter(prefix="/users", tags=["users"])
@router.get("", response_model=UserListResponse)
async def list_users(
db: Annotated[AsyncSession, Depends(get_db)],
page: Annotated[int, Query(ge=1)] = 1,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
search: str | None = None,
):
"""List users with pagination."""
users, total = await user_service.get_users(
db, page=page, limit=limit, search=search
)
return UserListResponse(
data=users,
total=total,
page=page,
limit=limit,
)
@router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
db: Annotated[AsyncSession, Depends(get_db)],
user_in: UserCreate,
):
"""Create a new user."""
existing = await user_service.get_by_email(db, user_in.email)
if existing:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Email already registered",
)
return await user_service.create(db, user_in)
@router.get("/me", response_model=UserResponse)
async def get_current_user_profile(
current_user: Annotated[User, Depends(get_current_user)],
):
"""Get current user profile."""
return current_user
@router.patch("/me", response_model=UserResponse)
async def update_current_user(
db: Annotated[AsyncSession, Depends(get_db)],
current_user: Annotated[User, Depends(get_current_user)],
user_in: UserUpdate,
):
"""Update current user profile."""
return await user_service.update(db, current_user, user_in)
```
## Dependency Injection
```python
# app/core/deps.py
from typing import Annotated, AsyncGenerator
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession
from jose import JWTError, jwt
from app.db.session import async_session
from app.core.config import settings
from app.models.user import User
from app.services import user_service
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with async_session() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
async def get_current_user(
db: Annotated[AsyncSession, Depends(get_db)],
token: Annotated[str, Depends(oauth2_scheme)],
) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
user_id: str = payload.get("sub")
if user_id is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = await user_service.get_by_id(db, user_id)
if user is None:
raise credentials_exception
return user
def require_role(required_role: str):
async def role_checker(
current_user: Annotated[User, Depends(get_current_user)]
) -> User:
if current_user.role != required_role:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient permissions",
)
return current_user
return role_checker
```
## Best Practices
- Use Pydantic for request/response validation
- Apply dependency injection for shared logic
- Implement proper error handling
- Use async database sessions
- Add rate limiting for protection
- Generate OpenAPI documentation
Google Antigravity IDE provides FastAPI patterns and automatically suggests security improvements for your Python APIs.This Python prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their python implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Python projects, consider mentioning your framework version, coding style, and any specific libraries you're using.