⚡ Instant CRUD APIs from Pydantic Models ⚡</br> Build a fully working FastAPI CRUD API in 10 seconds.
from fastapi import FastAPI
import motor.motor_asyncio
from fastapi_crudrouter_mongodb import (
ObjectIdType,
MongoModel,
CRUDRouter,
)
# Database connection using motor
client = motor.motor_asyncio.AsyncIOMotorClient("mongodb://localhost:27017/local")
# store the database in a global variable
db = client.local
# Database Model
class UserModel(MongoModel):
id: ObjectIdType | None = None
name: str
email: str
# Instantiating the CRUDRouter
users_router = CRUDRouter(
model=UserModel,
db=db,
collection_name="users",
prefix="/users",
tags=["users"],
)
# Instantiating the FastAPI app
app = FastAPI()
app.include_router(users_router)
| HTTP Verb | Path | Description |
|---|---|---|
GET |
/users | List all users |
POST |
/users | Create a new user |
GET |
/users/{id} | Get a user by id |
PUT |
/users/{id} | Update a user by id |
PATCH |
/users/{id} | Partially update a user by id |
DELETE |
/users/{id} | Delete a user by id |
!!!tip “No routing. No boilerplate. No repetition.” The CRUDRouter automatically generates all the necessary routes for your models.
Requires Python >=3.10.
pip install fastapi-crudrouter-mongodb
I will provide more examples in the future, but for now, here is a basic example of how to use the FastAPI CRUDRouter for Mongodb :seedling:.
```py linenums=”1” from fastapi import FastAPI from fastapi_crudrouter_mongodb import ( ObjectIdType, MongoModel, CRUDRouter, ) import motor.motor_asyncio
client = motor.motor_asyncio.AsyncIOMotorClient(“mongodb://localhost:27017/local”)
db = client.local
class UserModel(MongoModel): id: ObjectIdType | None = None name: str email: str password: str
users_router = CRUDRouter( model=UserModel, db=db, collection_name=”users”, prefix=”/users”, tags=[“users”], )
app = FastAPI() app.include_router(users_router) ```
FastAPI is amazing, but CRUD is repetitive.
This library removes boilerplate so you can focus on your product
👉 Full docs: Right here
By default, the CRUDRouter automatically documents all generated routes in accordance with the OpenAPI specification.

The CRUDRouter can dynamically generate comprehensive documentation based on the provided models.

Credits :
Base projet and idea : awtkns
Convert _id to id (for previous versions of Pydantic) : mclate github guide
For Pydantic v2 : Stackoverflow