Search code examples
pythonrequestfastapiuuid

Return uppercase UUID in FastApi


When using FastApi with a pydantic model at the reponse model, I found that the uuid are always returned lowercase by the http response. Is there any standard way to return them upper cased?

from fastapi import FastAPI
from pydantic import BaseModel
from uuid import UUID
app = FastAPI()

class Test(BaseModel):
    ID: UUID

@app.get("/test", response_model=Test)
async def test():
    id_ = uuid.uuid4()
    return Test(ID=id_)
   

When making the request the returned uuid will be in lowercased.

from requestr
a = requests.get("http://localhost:800/test").text # you ir
# a -> '{"ID":"fffc0b5b-8e8d-4d06-b910-2ae8d616166c"}' # it is lowercased

The only somewhat hacky way I found to return them uppercased is overwriting the uuid class __str__ method or sub-classing uuid:

What I tried (and works):

# use in main.py when importing for first time
def newstr(self):
    hex = '%032x' % self.int
    return ('%s-%s-%s-%s-%s' % (hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])).upper()


uuid.UUID.__str__ = newstr

But I was wondering if there is a standard way of doing this without modifying the original class, maybe a post process in pydantic or a setting in FastApi.


Solution

  • You can define custom json_encoders:

    class Test(BaseModel):
        ID: UUID
    
        class Config:
            json_encoders = {
                UUID: lambda val: str(val).upper()
            }