Spaces:
Sleeping
Sleeping
|
Download FASTAPI_GUIDE.md from Divyaraj1617/testnexus-backend: direct link, hf CLI and curl.
- Browser
- Download file 2.34 kB
-
https://huggingface.co/spaces/Divyaraj1617/testnexus-backend/resolve/main/FASTAPI_GUIDE.md
- Command line
-
hf download hf://spaces/Divyaraj1617/testnexus-backend/FASTAPI_GUIDE.md
-
curl -L -o FASTAPI_GUIDE.md https://huggingface.co/spaces/Divyaraj1617/testnexus-backend/resolve/main/FASTAPI_GUIDE.md
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 | |