Skip to content Skip to sidebar Skip to footer

Run Django Api From Postman: Csrf Verification Failed

I'm trying to run an api using postman. My application is developed in django 1.11.6 using python 3.5. My app is installed on an ubuntu server. I have no login mechanism to create

Solution 1:

Try this.

from django.views.decorators.csrf import csrf_exempt
classApiUserRegister(APIView):
permission_classes = ()
serializer_class = RegisterUserSerializer

    @csrf_exemptdefpost(self, request):
        serializer = RegisterUserSerializer(data=request.data)

Solution 2:

To make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.

1st option

enter image description here

2nd option enter image description here

Solution 3:

update your class to be like this

from braces.views import CsrfExemptMixin
classyour_class(CsrfExemptMixin, ......yours_here)
   defpost(...):
       [....]

this will tell django to allow requests without csrf

Solution 4:

Django sets csrftoken cookie on login. After logging in, we can see the csrf token from cookies in the Postman. (see image) CSRFtoken from cookies

We can grab this token and set it in headers manually. But this token has to be manually changed when it expires. This process becomes tedious to do it on an expiration basis.

Instead, we can use Postman scripting feature to extract the token from the cookie and set it to an environment variable. In Test section of the postman, add these lines.

var xsrfCookie = postman.getResponseCookie("csrftoken"); postman.setEnvironmentVariable('csrftoken', xsrfCookie.value);

This extracts csrf token and sets it to an environment variable called csrftoken in the current environment. Now in our requests, we can use this variable to set the header.(see image) Set {{csrftoken}} in your header

When the token expires, we just need to log in again and csrf token gets updated automatically.

Thanks to @chillaranand from hackernoon.com to original post

Solution 5:

simple just make sure to put as_view()

urlpatterns = [
    path('sign_up', views.SignUp.as_view()),
]

Post a Comment for "Run Django Api From Postman: Csrf Verification Failed"