Spaces:
Sleeping
Sleeping
File size: 2,337 Bytes
4db2610 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | # 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
|