Modify data representation and field order of response model #8823
-
First Check
Commit to Help
Example Code# TIP: This is full app. Run using `uvicorn main:app --port 5000 --reload`
from datetime import datetime
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
# Fake Data (database)
data = [
{
"id": 1,
"username": "johndoe007",
"created_at": datetime.now(),
"updated_at": datetime.now(),
}
]
# Pydantic
class DemoBase(BaseModel):
username: str
class DemoOut(DemoBase):
id: int
created_at: datetime
updated_at: datetime
# FastAPI
app = FastAPI()
@app.get("/", response_model=List[DemoOut])
def read_root():
return data DescriptionIf you visit the app you will get below response: [
{
"username": "johndoe007",
"id": 1,
"created_at": "2021-09-13T12:57:55.200998",
"updated_at": "2021-09-13T12:57:55.201006"
}
] It is working fine but the problem is when we want below: 1. order the data sent by In the above response,
2. Update the data representation In the above response, we get the date as Wanted SolutionI guess we can create another magic class that lets us define the field order and value representation but that might introduce code duplication. Sorry but I don't have any perfect solution. Wanted CodeNo idea AlternativesNone. I might have to raise the same issue to pydantic. Operating SystemLinux Operating System DetailsLinux Mint 20.2 Cinnamon FastAPI Version0.68.0 Python Version3.9.x Additional ContextNone |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
@jd-0001
|
Beta Was this translation helpful? Give feedback.
-
Hi @NoCrEaTiVe I know I can use validators but this is not what they are made for. As per their name they are for validation. |
Beta Was this translation helpful? Give feedback.
-
@jd-solanki I had this same issue and I think I've got a reasonable workaround. Make an empty subclass that inherits all of its properties from your desired superclass and a "mirror" superclass that has the additional properties that you want. Based on my testing, the properties on "actual_sub_foo" in the below example will populate in reverse order both on the FastAPI Swagger page and in any responses. See below:
In this example, if you use "actual_sub_foo" as your response_model, the API response should look like:
|
Beta Was this translation helpful? Give feedback.
pydantic/pydantic#593