testnexus-backend / FASTAPI_GUIDE.md
Divyaraj1617's picture
Added server files
4db2610
|
Raw History Blame Contribute Delete
2.34 kB
# 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