Well Organized FastAPI applications
Creating a well-organized FastAPI application involves structuring your project in a way that makes it scalable, maintainable, and understandable. Below is a simplified example of how to structure a FastAPI project and write an API within it.
Project Structure:
A recommended project structure for a FastAPI application might look like this:
my_fastapi_project/
│
├── app/ # Application module
│ ├── __init__.py # Initializes Python package
│ ├── main.py # FastAPI app creation and configuration
│ ├── dependencies.py # Dependency injection (DB connections, etc.)
│ ├── models.py # Pydantic models for request/response schemas
│ ├── schemas.py # Pydantic schemas for request/response validation
│ ├── crud.py # CRUD operations (interact with the database)
│ └── routers/ # Router modules for different endpoints
│ ├── __init__.py
│ ├── items.py
│ └── users.py
│
├── tests/ # Test modules
│ ├── __init__.py
│ ├── test_main.py
│ └── test_routers/
│ ├── __init__.py
│ ├── test_items.py
│ └── test_users.py
│
├── .env # Environment variables
├── requirements.txt # Project dependencies
└── README.md # Project READMECode Example
'app/models.py'(Pydantic models for your entities)
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
description: str = None
'app/routers/items.py'(Router for item-related endpoints)
from fastapi import APIRouter, HTTPException
from typing import List
from ..models import Item
router = APIRouter()
# Dummy database
items_db = [
Item(id=1, name="Item One", description="This is item one"),
Item(id=2, name="Item Two", description="This is item two"),
]
@router.get("/items/", response_model=List[Item])
async def read_items():
return items_db
@router.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
item = next((item for item in items_db if item.id == item_id), None)
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
'app/main.py’(Main application file)
from fastapi import FastAPI
from .routers import items
app = FastAPI()
app.include_router(items.router)
@app.get("/")
async def root():
return {"message": "Hello World"}Run your FastAPI application
uvicorn app.main:app --reloadTest your API
This example showcases a minimal structure and implementation. Real-world applications might involve more complex data interactions, additional routers and models, middleware, background tasks, and more, depending on your requirements.
Comments
Post a Comment