# FastAPI Guide for Express Developers ## Quick Comparison ### Express vs FastAPI | Express | FastAPI | |---------|---------| | `app.get('/route', handler)` | `@app.get("/route")` | | `router.post('/signup', handler)` | `@router.post("/signup")` | | `req.body` | `request: ModelName` (Pydantic model) | | `res.json({...})` | `return ModelName(...)` | | `res.status(400).json(...)` | `raise HTTPException(status_code=400, detail="...")` | | `app.use('/auth', authRouter)` | `app.include_router(auth.router)` | | `bcrypt.hash()` | `hash_password()` | | `bcrypt.compare()` | `verify_password()` | | `jwt.sign()` | `create_access_token()` | | `jwt.verify()` | `verify_token()` | ## Key Concepts ### 1. **Routers** (like Express routes) ```python # server/routers/auth.py router = APIRouter(prefix="/auth", tags=["Authentication"]) @router.post("/signup") async def signup(request: SignUpRequest): # Handler logic ``` ### 2. **Pydantic Models** (like request validation) ```python # Request validation (like express-validator) class SignUpRequest(BaseModel): name: str email: EmailStr password: str ``` ### 3. **Async/Await** FastAPI is async by default. Use `async def` for route handlers. ### 4. **Error Handling** ```python # Instead of res.status(400).json({error: "..."}) raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Error message" ) ``` ## Project Structure ``` server/ ├── main.py # Main app (like app.js in Express) ├── routers/ # Route handlers (like routes/ in Express) │ ├── __init__.py │ └── auth.py # Auth routes ├── models/ # Pydantic models (like schemas/ in Express) │ ├── __init__.py │ └── auth.py # Request/Response models ├── utils/ # Utility functions (like utils/ in Express) │ ├── __init__.py │ └── auth.py # JWT, password hashing └── requirements.txt # Dependencies (like package.json) ``` ## API Endpoints - `POST /auth/signup` - User registration - `POST /auth/signin` - User login - `GET /health` - Health check ## Testing 1. Start server: `uvicorn main:app --reload` 2. Visit: `http://localhost:8000/docs` for interactive API docs 3. Test endpoints using Swagger UI or Postman