How to create an endpoint with an arbitrary request format, saving logic, and response format?

106 views
Skip to first unread message

Travis Miller

unread,
Dec 29, 2022, 4:55:04 PM12/29/22
to Django REST framework
I'm new to DRF (and pretty new to Django and Python in general). I'm trying to build a simple API endpoint. But I'm having trouble figuring out the best approach.

1. The endpoint accepts a request payload similar to the following (this is contrived):

{
    "employee_id": 123,
    "favorite_flavor": "chocolate",
    "subscribe_to_updates": true,
    "cats_or_dogs": "cats"
}

Obviously, I would like to validate this payload before doing anything further with it.

2. The endpoint then creates several related records in the database. Note that the request payload is not a direct 1-to-1 representation of a Django ORM model. Instead, employee_id gets saved to one table, and favorite_flavor and subscribe_to_updates get saved to a second table. Perhaps cats_or_dogs doesn't get saved to the database at all – maybe it just triggers an email send, or writes a file to disk, or something like that.

3. Finally, I would like the endpoint to return an arbitrary JSON payload, which differs from both the request payload and the model structure:

{
    "recommended_dessert": "Black Forest Cake",
    "subscription_id": 5827,
    "cat_name": "Fluffy",
    "some_nested_object": {
        "foo": "bar"
    }
}

How can I do this? DRF provides a dizzying array of ways to do things, and I can't quite figure out which combination is best for my case.

Thanks!

Michael Angelozzi

unread,
Feb 24, 2023, 10:23:54 AM2/24/23
to Django REST framework
To override the returned representation, you can override the `to_representation` method of a serializer:

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data.pop('secret_field')
        data['some_new_field'] = 'Cow infiltrator!'
        data['nested_data'] = {'fav_toys': ['pogo_stick', 'cannon balls']}
        return data



You don't live in South Africa by any chance?

Cheers!
Reply all
Reply to author
Forward
0 new messages