Usage
Basic usage examples for fastapi-mongo-base.
2. Define Schemas and Models
schemas.py
from fastapi_mongo_base.schemas import BaseEntitySchema
class BookSchema(BaseEntitySchema):
title: str
author: str
publish_year: int
isbn: str | None = None
models.py
from fastapi_mongo_base.models import BaseEntity
from .schemas import BookSchema
class Book(BookSchema, BaseEntity):
"""Book model that inherits from both BookSchema and BaseEntity"""
pass
3. Create and Register Routers
routes.py
from fastapi_mongo_base.routes import AbstractBaseRouter
from . import models, schemas
class BookRouter(AbstractBaseRouter):
model = models.Book
schema = schemas.BookSchema
router = BookRouter().router
server/server.py
from fastapi import FastAPI
from apps.books.routes import router as book_router
from .config import Settings
app = FastAPI()
app.include_router(book_router, prefix=f"{Settings().base_path}/books")
4. MongoDB Configuration
Set your MongoDB URI in .env
or as an environment variable:
- For Docker, use
mongo
as the hostname:
5. Running the Application
-
Locally:
-
With Docker Compose:
See Quick Start for a full example.
6. Custom Endpoints
You can add custom endpoints for advanced queries or background tasks.
See Endpoints & Customization for details.