Django DRF - How to interact with a POST endpoint using CURL?

I'm new to Django DRF or API development in general, please be patient with me ;) Beside some pure get API views I now wanted to setup my very first endpoint where I can send data to, so I decided to go with a user password change. Here is what I did so far:

views.py

@api_view(['GET', 'POST'])
@authentication_classes([JSONWebTokenAuthentication])
@permission_classes([IsAuthenticated])
def update_user(request):
    if request.method == 'GET':
        serializer = UserSerializer(request.user)
        return Response(serializer.data, status=status.HTTP_200_OK)

    elif request.method == 'POST':
        serializer = UserSerializer(request.user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

serializers.py

class UserSerializer(serializers.ModelSerializer):
    id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    password = serializers.CharField(
        max_length=128,
        min_length=8,
        write_only=True
    )

    class Meta:
        model = User
        fields = ('id', 'user', 'password', 'pin', 'avatar')
        read_only_fields = ('id', 'user')

    def update(self, instance, validated_data):
        password = validated_data.pop('password', None)
        for (key, value) in validated_data.items():
            setattr(instance, key, value)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

Now the question is how can I update the referenced fields like "pin" or especially "password" using curl.

The first thing I always do is to get myself a new token like this:

curl -X POST -d "user=admin&password=admin" http://localhost/api/v1/token/obtain
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWYzN2RiODUtYjU5Yy00YjRmLWFhNjYtMDExNGFmYWQ4ZDdiIiwidXNlcm5hbWUiOiJhZG1pbiIsImV4cCI6MTYzNDE3Mjg3MiwidXNlciI6ImFkbWluIiwib3JpZ19pYXQiOjE2MzQxMjk2NzJ9.zz9Zyai3Y7MhR_chGkzA6jXY_BdjN5Eu2muRvyWIppw"}

With this token in place I can now reach the update_user endpoint but I don't understand how to interact with it using curl or some fancy browser extension. Can somebody give me a hint?

I suggest to use postman for testing your APIs. It is very easy, you just need to provide necessary headers and body and submit.

You can also view commands/code for curl, python, nodejs etc for making the api call with the headers and the body you added in postman.

Back to Top