3
votes

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.

1
@lsabi Not sure I understand the question. - Karlson
I mean if you need something as shown in the link. You can return a response that you prepare on your own and that does not go through the jsonable_encoder - lsabi
@lsabi I have a dict which I have represented simplistically in the code. The object is more complex and need to be encoded. So either I write a completely custom encoder by myself, which I would like to avoid or use jsonable_encoder but one thing that I can't seem to do is to provide a mnemonic instead of a numerical value for an enum. - Karlson
Yes, but if you try to serialize your object with json.dumps(my_object) does it return the desired result? In case you can return that result directly, instead of passing through the jsonable_encoder of fastapi - lsabi

1 Answers

1
votes

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.