Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send nested JSON data with image/file from postman: Django REST framework

I want to POST the following data:

{
    "user": {
        "name": "user name",
        "email": "user@example.com",
        "phone_number": "01XXXXXXXXX",
        "user_type": "MGR"
    },
    "img": "image_data",
    "manager_brands": [
        2,
        1
    ]
}

How can I pass this JSON data through postman? Challenges I am facing:

  1. This is a nested JSON data
  2. I am passing an image with it.

Note: I wrote the nested serializers to GET/PUT/PATCH/DELETE requests. Everything works fine when I don’t send an image (image is optional here).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Convert your Image to base64Image and send it through the JSON data.

All you need to do is:

  1. go to https://www.base64-image.de/ and convert the image to base64 format. Copy the encoded result.
  2. Install django-extra-fields package in your project from here
  3. In your serializer_class, change the image field like the following code:

serializers.py

...
from drf_extra_fields.fields import Base64ImageField
...
 
...
class ProfileSerializer(serializer.ModelSerializer):
    user = UserSerializer()
    img = Base64ImageField(required=False)

    class Meta:
        model = Profile
        fields = ('user', 'img', 'manager_brands')
...
  1. Now, go to your postman and send the JSON data like the following. Remember to send that encoded image in your img field in JSON.
{
    "user": {
        "name": "user name",
        "email": "user@example.com",
        "phone_number": "01XXXXXXXXX",
        "user_type": "MGR"
    },
    "img": "<base64 encoded image>",
    "manager_brands": [
        2,
        1
    ]
}

Hope this helps 😀

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading