Home > Net >  How to convert POST PascalCase json to snake_case in Django Rest Framework?
How to convert POST PascalCase json to snake_case in Django Rest Framework?

Time:01-28

I have a DRF API endpoint that accepts python snake_case payloads:

{
    "sample_id": "",
    "notes": "",
    "patient_id": "",
    "dob": "",
    "scan_model": {
        "current_time_left": "",
        "scan_state": null,
        "timer_configuration": {
            "timer_interval": null,
            "timer_length": "",
            "warning_span": "",
            "window_of_opportunity": ""
        }
}

How to get the endpoint to accept a json with keys in PascalCase like this:

{
 "SampleId": null,
  "Notes": null,
  "PateintId": "testid",
  "DateOfBirth": "05/11/1995",
  "ScanModel": {
    "Id": 1,
    "CurrentTimeLeft": "00:00:00",
    "ScanState": 6,
    "TimerConfiguration": {
      "TimerInterval": 200,
      "TimerLength": "00:15:00",
      "WarningSpan": "00:02:00",
      "WindowOfOpportunity": "00:05:00"
    }
}

I am using Django 4.1, DRF 3.14 and python 3.11 Thanks!

CodePudding user response:

So you can achieve this by using the JSONParser class and a custom JSONRenderer class.

You can create a custom JSONRenderer class that overrides the default render method to convert PascalCase keys to snake_case before rendering the data.

So this will be your renderer:

import json

class SnakeCaseJSONRenderer(JSONRenderer):
    def render(self, data, media_type=None, renderer_context=None):
        # convert data keys to snake_case
        data = json.loads(json.dumps(data, separators=(',', ':')))
        return super().render(data, media_type=media_type, renderer_context=renderer_context)

Then in your views you can use this custom renderer by setting the renderer_class attribute as your custom renderer class. Like this:

from rest_framework import viewsets

class MyViewSet(viewsets.ModelViewSet):
    renderer_classes = [SnakeCaseJSONRenderer]

Or you can add it to the settings too:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}

You can also use this package

  • Related