Releases: PierroD/fastapi-crudrouter-mongodb
0.1.3 - CRUDRouterService (December 17, 2024)
v.0.1.3 - Create your own CRUD service and call an existing one
You can now :
- request the service of an existing CRUDRouter router
- create your own CRUDRouterService to save time
from fastapi_crudrouter_mongodb import CRUDRouterService
"""
The rest of your code should be here
This is an example on how to use the service added to the lib
👇
"""
@app.get("/get_one/{id}")
async def get_one(id: str):
# Assuming you already have a users_router CRUDRouter instance
return await users_router.service.get_one(id)
# Create your own CRUDRouterService with all the CRUD methods provided
class TestModel(MongoModel):
id: Annotated[ObjectId, MongoObjectId] | None = None
name: str
service = CRUDRouterService(TestModel, db, "test")
@app.get("/test")
async def test():
return await service.get_all()
0.1.2 - Breaking Change (August 21, 2024)
v.0.1.2 - Change input and output
⚠️ Breaking Change :
- MongoModel will now use camelCase as input and output by
DEFAULT
You do not have to change anything it will natively convert snake_case to camelCase as input and output to your FastAPI project
Description | Impacted |
---|---|
Input in snake_case | |
Input in camelCase | |
Output in snake_case | ✅ |
Output in camelCase |
All your outputs data will be in camelCase now
Examples :
Old output
{
"user_id": "...."
}
New output
{
"userId": ""
}
0.1.1 - fix convert_to (April 13, 2024)
Fix :
- convert_to function is now able to replace every objectId in a dict and in a list
0.1.0 - Migrate to Pydantic v2 (March 31, 2024)
v0.1.0 - Migrate to Pydantic v2 & Refacto
2024-03-31
⚠️ Breaking changes
- A lot of the typing has changed due to Pydantic v2
- The Embed needs to be written explicitly
Feat
- Migrate to Pydantic v2
- Add output schema to the CRUDLookup
- New CRUDEmbed router
Fix
- DELETE Routes will returned the same Schema
- Remove lookups fields from the parent Schema automatically
Doc
- New documentation pages
- Migration guides available here Migration Guide
0.0.8 - (September 13, 2023)
Feat
- Add
model_out
to the CRUDRouter, gives you the opportunity not to reveal sensitive data - Add black to format the code
- Add ruff to lint the code
Fix
- fix the
convert_to
method so it will convert theid
to str to prevent issue while converting MongoObjectId to str
Example
class UserModel(MongoModel):
id: Optional[MongoObjectId] = Field()
name: str
email: str
password: str
addresses: Optional[List[AddressModel]]
messages: Optional[Union[List[MessageModel], MessageModel]] = None
class UserModelOut(MongoModel):
id: str
name: str
email: str
users_controller = CRUDRouter(
model=UserModel,
model_out=UserModelOut,
db=db,
collection_name="users",
lookups=[messages_lookup],
prefix="/users",
tags=["users"],
)
Result
0.0.7 - (August 13, 2023)
Fix Pydantic crashes and add methods
- Fix : force pydantic v 1.X dependency to prevent the lib from crashes
- Refactor : refacto
mongo
and rename it toto_mongo
- Feat : add a new method called
convert_to
(it helps you to convert a model to another)
Example
Using the convert_to option
@app.get("/{id}", response_model=UserModelDAO)
async def root(id: str):
response = await db['users'].find_one({'_id': MongoObjectId(id)})
userDAO = UserModelDAO.from_mongo(response)
userDTO = userDAO.convert_to(UserModelDTO)
return userDTO
0.0.5 - (May 10, 2023)
Remove route and add dependencies to a specific route 🚀
- Feat : allowed to disable any route of the CRUDRouter
- Feat : allowed to add custom dependencies to a specific route
Example
user = CRUDRouter(
model=UserModel,
db=db,
collection_name="users",
prefix="/users",
tags=["users"],
disable_get_all=True,
dependencies_get_one=[Depends(verify_admin)],
)
New CRUDRouter params
Param Name | Default Value | Type | Description | Default Behavior |
---|---|---|---|---|
disable_get_all | False | bool | Disable get all route | Get all route is enable / visible |
disable_get_one | False | bool | Disable get by id route | Get by id route is enable / visible |
disable_create_one | False | bool | Disable create by id route | Create by id route is enable / visible |
disable_replace_one | False | bool | Disable replace by id route | Replace by id route is enable / visible |
disable_update_one | False | bool | Disable update by id route | Update by id route is enable / visible |
disable_delete_one | False | bool | Disable delete by id route | Delete by id route is enable / visible |
dependencies_get_all | None | Sequence[Depends] | Add custom dependencies | Default router dependencies |
dependencies_get_one | None | Sequence[Depends] | Add custom dependencies | Default router dependencies |
dependencies_create_one | None | Sequence[Depends] | Add custom dependencies | Default router dependencies |
dependencies_replace_one | None | Sequence[Depends] | Add custom dependencies | Default router dependencies |
dependencies_update_one | None | Sequence[Depends] | Add custom dependencies | Default router dependencies |
dependencies_delete_one | None | Sequence[Depends] | Add custom dependencies | Default router dependencies |
Initial Release - (April 10, 2023)
🥳 Initial Release 🥳
Tired of rewriting the same generic CRUD routes? Need to rapidly prototype a feature for a presentation or a hackathon? Thankfully, fastapi-crudrouter-mongodb has your back. As an extension to the APIRouter included with FastAPI, the FastAPI CRUDRouter will automatically generate and document your CRUD routes for you.
Documentation: https://pierrod.github.io/fastapi-crudrouter-mongodb-doc/
Source Code: https://github.com/pierrod/fastapi-crudrouter-mongodb
Credits :
-
Base projet and idea : awtkns
-
Convert _id to id : mclate github guide
Installation
pip install fastapi-crudrouter-mongodb
Basic Usage
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.
from datetime import datetime
from typing import List, Optional, Union
from fastapi import FastAPI
from pydantic import Field
from fastapi_crudrouter_mongodb import CRUDRouter, MongoModel, MongoObjectId, CRUDLookup
import motor.motor_asyncio
# Database connection using motor
client = motor.motor_asyncio.AsyncIOMotorClient(
"mongodb://localhost:27017/local")
db = client.local
# Models
class MessageModel(MongoModel):
id: Optional[MongoObjectId] = Field()
message: str
user_id: MongoObjectId
created_at: Optional[str] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
updated_at: Optional[str] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
class AddressModel(MongoModel):
id: Optional[MongoObjectId] = Field()
street: str
city: str
state: str
zip: str
class UserModel(MongoModel):
id: Optional[MongoObjectId] = Field()
name: str
email: str
addresses: Optional[List[AddressModel]]
messages: Optional[Union[List[MessageModel], MessageModel]] = None
# Instantiating the CRUDRouter, and a lookup for the messages
# a User is a model that contains a list of embedded addresses and related to multiple messages
messages_lookup = CRUDLookup(
model=MessageModel,
collection_name="messages",
prefix="messages",
local_field="_id",
foreign_field="user_id"
)
users_controller = CRUDRouter(
model=UserModel,
db=db,
collection_name="users",
lookups=[messages_lookup],
prefix="/users",
tags=["users"],
)
# Instantiating the FastAPI app
app = FastAPI()
app.include_router(users_controller)
OpenAPI Support
By default, all routes generated by the CRUDRouter will be documented according to OpenAPI spec.
Below are the default routes created by the CRUDRouter shown in the generated OpenAPI documentation.