@@ -730,6 +730,49 @@ This will enable full tracebacks errors in the response, print request and respo
730730 return app.resolve(event, context)
731731 ```
732732
733+ ### Custom serializer
734+
735+ You can instruct API Gateway handler to use a custom serializer to best suit your needs, for example take into account Enums when serializing.
736+
737+ === "custom_serializer.py"
738+ ```python hl_lines="19-20 24"
739+ import json
740+ from enum import Enum
741+ from json import JSONEncoder
742+ from typing import Dict
743+
744+ class CustomEncoder(JSONEncoder):
745+ """Your customer json encoder"""
746+ def default(self, obj):
747+ if isinstance(obj, Enum):
748+ return obj.value
749+ try:
750+ iterable = iter(obj)
751+ except TypeError:
752+ pass
753+ else:
754+ return sorted(iterable)
755+ return JSONEncoder.default(self, obj)
756+
757+ def custom_serializer(obj) -> str:
758+ """Your custom serializer function ApiGatewayResolver will use"""
759+ return json.dumps(obj, cls=CustomEncoder)
760+
761+ # Assigning your custom serializer
762+ app = ApiGatewayResolver(serializer=custom_serializer)
763+
764+ class Color(Enum):
765+ RED = 1
766+ BLUE = 2
767+
768+ @app.get("/colors")
769+ def get_color() -> Dict:
770+ return {
771+ # Color.RED will be serialized to 1 as expected now
772+ "color": Color.RED,
773+ "variations": {"light", "dark"},
774+ }
775+ ```
733776
734777## Testing your code
735778
0 commit comments