Common FastAPI Mistakes & How to Avoid Them
Introduction
FastAPI is simple and powerful but many developers (especially beginners) make mistakes that can lead to:
- Bugs
- Poor performance
- Security issues
In this blog, we’ll cover the most common FastAPI mistakes and how to avoid them like a pro.
1. Not Using Pydantic Models
Problem:
Using plain dictionaries instead of validation.
@app.post("/items/")def create_item(item: dict):return item
Solution:
from pydantic import BaseModelclass Item(BaseModel):name: strprice: float
✔ Ensures validation
✔ Prevents bad data
2. Blocking Async Code
Problem:
import timeasync def bad():time.sleep(5) # blocks event loop!
Solution:
import asyncioasync def good():await asyncio.sleep(5)
3. Not Using Dependency Injection
Problem:
Repeating code everywhere.
Solution:
def get_db():yield db@app.get("/items")def get_items(db=Depends(get_db)):return db
4. Hardcoding Secrets
Problem:
SECRET_KEY = "123456"
Solution:
import osSECRET_KEY = os.getenv("SECRET_KEY")5. Not Hashing Passwords
Problem:
Storing plain passwords
Solution:
from passlib.context import CryptContextpwd_context = CryptContext(schemes=["bcrypt"])hashed = pwd_context.hash("password")6. Returning Raw Database Models
Problem:
Exposing internal data.
Solution:
Use response models:
@app.get("/items/", response_model=ItemResponse)7. Poor Project Structure
Problem:
Everything in one file.
Solution:
Use a modular structure:
- routes/
- models/
- schemas/
- services/
8. Not Handling Errors Properly
Problem:
return {"error": "Something went wrong"}Solution:
from fastapi import HTTPExceptionraise HTTPException(status_code=400, detail="Bad request")9. Ignoring CORS Issues
Problem:
Frontend cannot connect
Solution:
from fastapi.middleware.cors import CORSMiddleware10. Overusing Async Everywhere
Problem:
Unnecessary complexity
Solution:
Use async only for:
- I/O operations
- External calls
11. No Testing
Problem:
Bugs in production
Solution:
Use
pytest:def test_home():assert client.get("/").status_code == 20012. Not Using Proper Status Codes
Problem:
return {"message": "Created"}Solution:
@app.post("/items/", status_code=201)13. No Input Validation
Problem:
Invalid data enters system
Solution:
Always use schemas
14. Not Using Logging
Problem:
Hard to debug issues
Solution:
import logginglogging.info("Request received")15. Using
--reloadin ProductionProblem:
Performance issues
Solution:
Use Gunicorn:
gunicorn -w 4 -k uvicorn.workers.UvicornWorker app.main:appBest Practices Summary
✔ Use Pydantic models✔ Use dependency injection✔ Secure your API✔ Write tests✔ Follow clean architecture
Comments
Post a Comment