pythonfastapiimporterrorcircular-dependency

Circular Import Issue with FastAPI and Pydantic Models


I'm developing an application using FastAPI and Pydantic, and I'm encountering a circular import issue when trying to define my data models.

Here are the relevant files:

src/schemas/user.py

from typing import List
from pydantic import BaseModel
from src.schemas.blog import ShowBlog  # Import causing circular dependency

class ShowUser(BaseModel):
    username: str
    email: str
    blogs: List[ShowBlog]

    class Config:
        from_attributes = True

class User(BaseModel):
    username: str
    email: str
    password: str

src/schemas/blog.py

from pydantic import BaseModel
from src.schemas.user import ShowUser  # Import causing circular dependency

class Blog(BaseModel):
    title: str
    description: str
    user_id: int

class ShowBlog(BaseModel):
    id: int
    title: str
    description: str
    written_by: ShowUser

    class Config:
        from_attributes = True

When I run the application, I receive the following error:

ImportError: cannot import name 'ShowBlog' from partially initialized module 'src.schemas.blog' (most likely due to a circular import)

How can I resolve this circular import issue while keeping my FastAPI application structured? Are there best practices for organizing Pydantic models to avoid such problems?


Solution

  • I had a similiar problem using SQLModel with fastapi. This is what worked for me: Replace the dependency in one of the schema files with the name in quotations and don't import it there:

    from typing import List
    from pydantic import BaseModel
    
    class ShowUser(BaseModel):
       username: str
       email: str
       blogs: List["ShowBlog"]
    
       class Config:
           from_attributes = True
    
    
    class User(BaseModel):
       username: str
       email: str
       password: str
    

    This seems to work also in your example!