Junior — Middle
How do you implement architectural decisions when working with FastAPI?
sobes.tech AI
Answer from AI
When working with FastAPI, I adhere to a modular architecture, dividing the project into layers: routing, business logic, data access, and models.
- Routes (routers) are organized by functional areas, using APIRouter for convenience and scalability.
- Services contain business logic to separate it from controllers.
- Pydantic models are used for data validation and serialization.
- For database interaction, I use an ORM (e.g., SQLAlchemy) with an asynchronous engine to avoid blocking request processing.
- Configuration and dependencies are placed in separate modules, applying Dependency Injection through FastAPI.
An example of a simple route with a dependency:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_db():
db = ... # create session
try:
yield db
finally:
db.close()
@app.get("/items/{item_id}")
async def read_item(item_id: int, db=Depends(get_db)):
item = db.query(Item).get(item_id)
return item
This approach facilitates testing, maintenance, and extension of the application.