Is there a way to transfer images between Django Rest Framework and Flutter app?

Viewed 520

I want to take a picture on an app in flutter using the phone's camera or gallery and send it (POST request) to a Django REST API along with some other information. When the Django REST API receives the image along with the other information, it should resize the image and then save it in a model like:

class Animals(models.Model):
    animal_image = models.ImageField(blank = True, upload_to=getFileName)
    animal_name = models.CharField(max_length = 30)
    species = models.CharField(max_length = 30)

And later, the flutter app should be able to do a GET request to the API in order to get the image along with other details in the model and display the image on a widget (in another screen of the app).

Therefore, I want to know how to do the Django REST API (views code to handle the GET and POST request) and Flutter implementation (code for making the GET and POST requests with images to the Django server).

Either code snippets, links to blog posts or documentation would be good.

If this way is not possible, what are the alternate ways through which images can be exchanged between Django and Flutter?

Please Help

Cheers!!!

1 Answers

A good starting point could be using Django REST Framework ModelViewSet and ModelSerializer :

# serializers.py
class AnimalSerializer(serializers.ModelSerializer):
    class Meta:
        model = Animals
        fields = '__all__'

# views.py
class AnimalViewSet(ModelViewSet):
    queryset = Animals.objects.all()
    serializer = AnimalSerializer

# urls
router = DefaultRouter()
router.register(r'animals', AnimalViewSet, base_name='animal')

urlpatterns = [router.urls]

Around that, you could add validation logic in your serializer, permission_classes in your viewset, ...etc.

Related