Mashumaro instead of Pydantic
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
from dataclasses import dataclass
from typing import Optional
from fastapi import FastAPI
from mashumaro import DataClassJSONMixin
app = FastAPI()
@dataclass
class Item(DataClassJSONMixin):
name: str
price: float
is_offer: Optional[bool] = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
Description
pydantic can be a bit on the slower side and the default functionality is not geared towards strict typing. "1"
can become 1
in an int()
field. I don’t think this is good behavior for APIs. Also, mypy only catches pydantic issues with a plugin. Which does work well, but it is a bit unusual in my mind.
https://github.com/Fatal1ty/mashumaro looks like it provides the needed functionality, but with speed benefits and strictness.
I know it’d be a huge change, or maybe mashumaro could be supported in addition. In the past I’ve liked dacite, but it looks like mashumaro might be even better.
Just to note that as it is, dataclasses in FastAPI are very limited and buggy.
Wanted Solution
Being able to use mashumaro classes in FastAPI.
Wanted Code
from dataclasses import dataclass
from typing import Optional
from fastapi import FastAPI
from mashumaro import DataClassJSONMixin
app = FastAPI()
@dataclass
class Item(DataClassJSONMixin):
name: str
price: float
is_offer: Optional[bool] = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
Alternatives
dacite
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.68.1
Python Version
3.8.10
Additional Context
Thank you!
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
apischema actually looks very good!
Just chiming in to add that apischema supports this.