Pydantic color type hex only

Question:

I have the pydantic model that have color property

from pydantic import BaseModel
from pydantic.color import Color

class MyModel(BaseModel):
    color: Color

And I define FastAPI router that returns MyModel

@router.get("/", response_model=MyModel)
async def get_my_model() -> MyModel:
    item = await DbItem.get()
    return MyModel(**item.dict())

In this setup pydantic converts colors to named colors (e.g. black).

My frontend don’t recognize named colors.

How can I point pydantic to return hex colors?

Asked By: ChabErch

||

Answers:

Use Color.as_hex:

from pydantic import BaseModel
from pydantic.color import Color


class MyModel(BaseModel):
    color: Color


my_model = MyModel(color=Color("black"))
print(my_model.color.as_hex())  # '#000'

To get the hex value in your response, you can add a custom json encoder:

class MyModel(BaseModel):
    color: Color

    class Config:
        json_encoders = {Color: lambda c: c.as_hex()}
Answered By: Paweł Rubin
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.