FastAPI MongoDB Base
A powerful package that provides base classes and utilities for building FastAPI applications with MongoDB. Built on top of FastAPI and Beanie ODM, it offers pre-built CRUD operations, authentication, caching, and more.
✨ Features
- 🚀 Ready-to-use CRUD Operations: Pre-built abstract routers with full CRUD functionality
- 📦 MongoDB Integration: Seamless integration using Beanie ODM
- 🔒 Authentication: Built-in JWT authentication support
- 📝 Type Safety: Pydantic models for request/response validation
- 🔄 Caching: Built-in caching mechanism for improved performance
- 🛠 Background Tasks: Easy background task handling
- 📸 Image Processing: Optional image processing support (requires Pillow)
📦 Installation
pip install fastapi-mongo-base
📄 Documentation
The complete documentation is available at: https://mahdikiani.github.io/fastapi-mongo-base/
You can also ask questions about the project using DeepWiki:
🚀 Quick Start
- Create your schema:
from fastapi_mongo_base.schemas import BaseEntitySchema
class UserSchema(BaseEntitySchema):
email: str
name: str
age: int | None = None
- Create your model:
from fastapi_mongo_base.models import BaseEntity
from .schemas import UserSchema
class User(UserSchema, BaseEntity):
"""User model that inherits from both UserSchema and BaseEntity"""
pass
- Set up your router:
from fastapi_mongo_base.routes import AbstractBaseRouter
from . import models, schemas
class UserRouter(AbstractBaseRouter):
def __init__(self):
super().__init__(model=models.User, schema=schemas.UserSchema)
router = UserRouter().router
- Include in your FastAPI app:
from fastapi import FastAPI
from fastapi_mongo_base.core import app_factory
app = app_factory.create_app()
app.include_router(router, prefix="/api/v1/users")
📚 Available Endpoints
Each router automatically provides these endpoints:
GET /api/v1/users- List all usersPOST /api/v1/users- Create a new userGET /api/v1/users/{id}- Get a specific userPATCH /api/v1/users/{id}- Update a userDELETE /api/v1/users/{id}- Delete a user
🔧 Configuration
Configure your application using environment variables or a settings class:
import dataclasses
import logging
import logging.config
import os
import dotenv
from singleton import Singleton
dotenv.load_dotenv()
@dataclasses.dataclass
class Settings(metaclass=Singleton):
root_url: str = os.getenv("DOMAIN", default="http://localhost:8000")
project_name: str = os.getenv("PROJECT_NAME", default="PROJECT")
base_path: str = "/api/v1"
worker_update_time: int = int(os.getenv("WORKER_UPDATE_TIME", default=180))
testing: bool = os.getenv("DEBUG", default=False)
page_max_limit: int = 100
mongo_uri: str = os.getenv(
"MONGO_URI", default="mongodb://localhost:27017/"
)
redis_uri: str = os.getenv("REDIS_URI", default="redis://localhost:6379/0")
app_id: str = os.getenv("APP_ID")
app_secret: str = os.getenv("APP_SECRET")
JWT_CONFIG: str = os.getenv(
"USSO_JWT_CONFIG",
default='{"jwk_url": "https://sso.usso.io/website/jwks.json","type": "RS256","header": {"type": "Cookie", "name": "usso-access-token"} }',
)
@classmethod
def get_coverage_dir(cls):
return cls.base_dir / "htmlcov"
@classmethod
def get_log_config(
cls, console_level: str = "INFO", file_level: str = "INFO", **kwargs
):
log_config = {
"formatters": {
"standard": {
"format": "[{levelname} : {filename}:{lineno} : {asctime} -> {funcName:10}] {message}",
"style": "{",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": console_level,
"formatter": "standard",
},
"file": {
"class": "logging.FileHandler",
"level": file_level,
"filename": cls.base_dir / "logs" / "app.log",
"formatter": "standard",
},
},
"loggers": {
"": {
"handlers": ["console", "file"],
"level": "INFO",
"propagate": True,
},
"httpx": {
"handlers": ["console", "file"],
"level": "WARNING",
"propagate": False,
},
},
"version": 1,
}
return log_config
@classmethod
def config_logger(cls):
log_config = cls.get_log_config()
if log_config["handlers"].get("file"):
(cls.base_dir / "logs").mkdir(parents=True, exist_ok=True)
logging.config.dictConfig(cls.get_log_config())
🛠️ Advanced Usage
Custom Business Logic
Extend the base router to add custom endpoints:
from fastapi_mongo_base.routes import AbstractBaseRouter
class UserRouter(AbstractBaseRouter):
def __init__(self):
super().__init__(model=models.User, schema=schemas.UserSchema)
@router.get("/me")
async def get_current_user(self):
# Your custom logic here
pass
Background Tasks
Handle background tasks easily:
import asyncio
import logging
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from fastapi_mongo_base.utils.scheduler import run_apscheduler
from server.config import Settings
logging.getLogger("apscheduler").setLevel(logging.WARNING)
async def log_something():
logging.info("something")
async def worker(stop: asyncio.Event):
scheduler = AsyncIOScheduler()
scheduler.add_job(
log_something, "interval", seconds=Settings.worker_update_time
)
# Runs until shutdown; jobs that are running then are allowed to finish.
await run_apscheduler(scheduler, stop)
Pass it as create_app(..., worker=worker) and start the app with fastapi_mongo_base.core.lifecycle.serve() for graceful shutdown (requires the scheduler extra: pip install "fastapi-mongo-base[scheduler]"). See the usage docs for details.
📋 Requirements
- Python >= 3.9
- FastAPI >= 0.65.0
- Pydantic >= 2.0.0
- MongoDB
- Beanie ODM
🔍 Project Structure
fastapi_mongo_base/
├── core/ # Core functionality and configurations
├── models.py # Base models and database schemas
├── routes.py # Abstract routers and endpoints
├── schemas.py # Pydantic models for request/response
├── tasks.py # Background task handling
└── utils/ # Utility functions and helpers
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
📝 License
Distributed under the MIT License. See LICENSE for more information.
👤 Author
- Mahdi Kiani - GitHub
🙏 Acknowledgments
- FastAPI team for the amazing framework
- MongoDB team for the powerful database
- Beanie team for the excellent ODM
- All contributors who have helped shape this project
Metadata
Release files for fastapi-mongo-base 1.9.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_mongo_base-1.9.1.tar.gz | 144.5 kB | Without provenance | Details for fastapi_mongo_base-1.9.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_mongo_base-1.9.1-py3-none-any.whl | Python 3 | none | any | Details for fastapi_mongo_base-1.9.1-py3-none-any.whl |
Total release size: 241.0 kB
Release files / fastapi_mongo_base-1.9.1.tar.gz
| Download URL | fastapi_mongo_base-1.9.1.tar.gz |
|---|---|
| Size | 144.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d58c2fe8b935aa87ad88b28cf3c2d7080d2c502d31cf01070016038d32e25562
|
|
BLAKE2b-256 checksum How to use checksums |
de8b920c1a435b95f93a415bc6e96f9bea6e4ea414516bab34e067a6010dc595
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / fastapi_mongo_base-1.9.1-py3-none-any.whl
| Download URL | fastapi_mongo_base-1.9.1-py3-none-any.whl |
|---|---|
| Size | 96.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a4ee16f26220594645e7b6a508a2d07afc97ab8f529e2ccd5bd19c8a9071673a
|
|
BLAKE2b-256 checksum How to use checksums |
9d9baaf29e65a217cbc71426bb220e02c5367be1fc5792722442d64ef24bc972
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for fastapi-mongo-base 1.9.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.