Skip to main content

1. Modular Backend Project Layouts

As your backend grows, keeping all routes, database models, and logic in one file becomes impossible to maintain. A standard, modular layout is necessary. Here is a typical production-grade FastAPI project layout:

2. Layered Package Groupings

FastAPI applications typically divide code into three distinct layers to promote the Separation of Concerns (SoC) principle:
  1. API Layer (app/api/): Defines path operations, requests handling, and responses. No database queries or heavy calculations should live here.
  2. Business Logic Layer (app/services/): Orchestrates actions, checks permissions, calculates data, and connects different services.
  3. Database Layer (app/models/ & app/schemas/): Represents data structure in the database (SQLAlchemy models) and data structure transferred over the network (Pydantic schemas).

3. Managing Imports

Python supports two import styles: absolute imports and relative imports. Absolute imports specify the full path to a module starting from the project’s root directory.
Why prefer absolute imports?
  • Highly readable and clear.
  • Prevents errors when running files from different working directories.
  • Refactoring files is much easier.

Relative Imports

Relative imports specify paths relative to the current module file using dots (.).
[!WARNING] Avoid relative imports in backend development. They can easily break with ImportError or ValueError: attempted relative import beyond top-level package if you execute a script directly rather than running the application from the root directory.