FastApi & MongoDB
FastApi & MongoDB - the full guide: https://github.com/tiangolo/fastapi/issues/1515
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from bson import ObjectId from bson.errors import InvalidId from fastapi import FastAPI from pydantic import BaseConfig, BaseModel, Field app = FastAPI() class PyObjectId(str): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v):
if isinstance(v, ObjectId):
return v
try: return ObjectId(str(v)) except InvalidId: raise ValueError("Not a valid ObjectId") class MongoModel(BaseModel): id: Optional[PyObjectId] = Field(..., alias='_id') class Config(BaseConfig): json_encoders = { datetime: lambda dt: dt.isoformat(), ObjectId: lambda oid: str(oid), } class User(MongoModel): name: str = Field() @app.post('/me', response_model=User) def save_me(body: User): assert isinstance(body.id, ObjectId) return body