-
Notifications
You must be signed in to change notification settings - Fork 811
Description
Problem
Currently, the API in this project appears to follow a monolithic pattern, placing all logic and endpoints in a single file or tightly-coupled structure. This approach becomes unsustainable as the codebase grows, making it harder to maintain, extend, and test.
Proposal
Adopt FastAPI's recommended modular structure for organizing API endpoints and dependencies. FastAPI provides an easy and scalable way to split your application into multiple modules using APIRouter and Python packages. This helps keep code organized by logical domain, encourages re-use, and makes it easier for contributors to navigate the codebase.
Recommended Structure Example
Reference: FastAPI - Bigger Applications
.
├── app
│ ├── __init__.py
│ ├── main.py
│ ├── dependencies.py
│ └── routers
│ │ ├── __init__.py
│ │ ├── items.py
│ │ └── users.py
│ └── internal
│ ├── __init__.py
│ └── admin.py
main.py
creates the FastAPI app and includes routers.routers/
contains modules for each logical endpoint group (e.g.,items.py
,users.py
).dependencies.py
holds shared dependencies.internal/
can hold submodules for internal/admin APIs.
Example Code Snippets
Routers (e.g., app/routers/items.py):
from fastapi import APIRouter, Depends, HTTPException
from ..dependencies import get_token_header
router = APIRouter(
prefix="/items",
tags=["items"],
dependencies=[Depends(get_token_header)],
responses={404: {"description": "Not found"}},
)
@router.get("/")
async def read_items():
...
Main app (app/main.py):
from fastapi import FastAPI, Depends
from .dependencies import get_query_token
from .routers import items, users
app = FastAPI(dependencies=[Depends(get_query_token)])
app.include_router(users.router)
app.include_router(items.router)
Rationale
- Maintainability: Logical separation makes it easier to find and update code.
- Scalability: New features can be added as new routers/modules without cluttering the main app.
- Testing: Easier to write targeted tests for specific routers or dependencies.
- Community Best Practice: Aligns with FastAPI and modern Python best practices.
References
Suggested Next Steps
- Refactor the existing API codebase into a modular structure using routers and dependencies as described above.
- Update the README or developer documentation to reflect the new structure.
- Ensure future endpoints are added following this modular pattern.
This issue proposes a structural refactor to align with FastAPI and Python best practices for maintainability and scalability.