All posts

Fix Missing Import in FastAPI

Resolve ImportError and ModuleNotFoundError in FastAPI projects, covering virtual environments, Pydantic v2, and circular imports.

Missing Import Errors in FastAPI

FastAPI projects often hit ImportError or ModuleNotFoundError due to virtual environment issues, Pydantic version mismatches, or circular imports.

Virtual Environment Not Activated

# The package is installed globally but not in your venv
python -m venv venv
source venv/bin/activate
pip install fastapi uvicorn sqlalchemy

Pydantic v1 vs v2

FastAPI 0.100+ uses Pydantic v2, which changed imports:

# Pydantic v1 (old)
from pydantic import validator

# Pydantic v2 (new)
from pydantic import field_validator

class UserCreate(BaseModel):
    email: str

    # v1
    @validator('email')
    def validate_email(cls, v):
        return v

    # v2
    @field_validator('email')
    @classmethod
    def validate_email(cls, v: str) -> str:
        return v

Circular Imports

Common in FastAPI projects with models importing schemas and vice versa:

# BAD — circular
# models.py
from app.schemas import UserCreate  # schemas imports models too!

# GOOD — use TYPE_CHECKING
from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from app.schemas import UserCreate

Relative vs Absolute Imports

# In app/api/routes/users.py
# BAD — fails if run from wrong directory
from models import User

# GOOD — absolute import
from app.models import User

# ALSO GOOD — relative import
from ...models import User

Bugsly captures ImportError at application startup, showing the exact import path that failed — crucial for debugging container deployments where the Python path differs from local development.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free