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)
# 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)
# 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
# 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 registrationPOST /auth/signin- User loginGET /health- Health check
Testing
- Start server:
uvicorn main:app --reload - Visit:
http://localhost:8000/docsfor interactive API docs - Test endpoints using Swagger UI or Postman