Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

915
Views
override default encoders for jsonable_encoder in FastAPI

I have code that looks something like this using Fast API:

class EnumTestT(Enum):
    test_t_value = 0

object = { 
    test: test_t_value
}

enum_mapping = {
    test_t_value: "Test"
}

def enum_encoder(val: EnumTestT) -> str:
    return enum_mapping[val]

custom_encoder = {
    EnumTestT: enum_encoder
}

@app.get("/test")
async def test_get():
    return jsonable_encoder(object, custom_encoder=custom_encoder)

The issue is that jsonable_encoder applies custom encoders after the defaults. Is there any way to apply them before the default encoders. Because for an Enum and any derived classes the value of the enum is reported instead of the mapped value.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

FastAPI use ENCODERS_BY_TYPE (from pydantic.json) to encode some basic data type.

ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
    bytes: lambda o: o.decode(),
    Color: str,
    datetime.date: isoformat,
    datetime.datetime: isoformat,
    datetime.time: isoformat,
    datetime.timedelta: lambda td: td.total_seconds(),
    Decimal: decimal_encoder,
    Enum: lambda o: o.value,

so for me to override the default datetime encode, just like

 ENCODERS_BY_TYPE[datetime] = lambda date_obj: date_obj.strftime("%Y-%m-%d %H:%M:%S")

over 4 years ago · Santiago Trujillo Report

0

Right now I am using custom encoder within json.dumps like this:

class TestEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, EnumTestT):
            return TestEncoder.process_enum_test_t(obj)

and response within the FastAPI app would be:

json_str = json.dumps(json_list, cls=TestEncoder).encode('utf-8')
return Response(media_type="application/json", content=json_str)

The problem with FastAPI using custom encoders is that custom encoder is invoked after all the standard encoders have been invoked and there is no way to override that order.

over 4 years ago · Santiago Trujillo Report

0

inspired by coder vx

import datetime
from fastapi.responses import JSONResponse 
...
content = something to serialize 
JSONResponse(jsonable_encoder(content,
    custom_encoder={datetime.datetime: lambda date_obj: 
    date_obj.strftime("%Y-%m-%d %H:%M:%S")})))
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!