Hello
I’m consuming an API that returns a JSON object with capitalized field names like this.
{
"CODE": 1,
"PERSONNAME": "Marco",
"PERSONSURNAME": "Richetta"
}
I created a serializer to receive and validate this data
class PersonSerializer(serializers.Serializer):
CODE = serializers.IntegerField()
PERSONNAME = serializers.CharField()
PERSONSURNAME = serializers.CharField()
Problem
I need to change the field names to camelCase
but I’m not sure where is the best place to do it.
At the moment I overwrote the to_representation
method of the serializer like this:
def to_representation(self, instance):
# This map is used to transform the field names
fields_map = {
"CODE": "code",
"PERSONNAME": "personName",
"PERSONSURNAME": "personSurname",
}
for key, value in fields_map.items():
# Field name is changed. Ej: PERSONNAME => personName
instance[value] = instance.pop(key)
return instance
It does the job but I’m not sure it’s safe to do it there.
There’s a library called djangorestframework-camel-case, that converts underscore <=> camelCase
with some helper functions to determine how to make the conversion. In my case I can’t see a pattern so I need to define the fields_map
based on the fields the API gives me.
Swagger problem
I have another problem with Swagger showing the example Response with the field names also capitalized.
It seems it inspects information of the serializer fields from another method, but I’m still looking for that.
The library I’m using for Swagger generation is [drf-yasg]
Thanks in advance.