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 BaseModel

class Item(BaseModel):
name: str
price: float

✔ Ensures validation
✔ Prevents bad data

2. Blocking Async Code

Problem:

import time

async def bad():
time.sleep(5) # blocks event loop!

Solution:

import asyncio

async 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 os
SECRET_KEY = os.getenv("SECRET_KEY")


5. Not Hashing Passwords

Problem:

Storing plain passwords

Solution:

from passlib.context import CryptContext

pwd_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 HTTPException

raise HTTPException(status_code=400, detail="Bad request")


9. Ignoring CORS Issues

Problem:

Frontend cannot connect

Solution:

from fastapi.middleware.cors import CORSMiddleware


10. 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 == 200

12. 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 logging

logging.info("Request received")

15. Using --reload in Production

Problem:

Performance issues

Solution:

Use Gunicorn:

gunicorn -w 4 -k uvicorn.workers.UvicornWorker app.main:app

Best Practices Summary

✔ Use Pydantic models
✔ Use dependency injection
✔ Secure your API
✔ Write tests
✔ Follow clean architecture

Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling