what is the difference between decorator @api_view and @csrf_exempt in project level django rest framework? I need the difference and which is better to develop the project.
2 Answers 2
the crsf in @crsf_exempt stands for Cross site Request Forgery, this basically means that if you put this decorator, this is basically a cookie created so that clients that don't have a CSRF token can use the POST HTTP method, this also makes the view excluded from the Middleware protection
@csrf_exempt(your_view)
While @api_view on the other hand takes a list of supported methods in your view and if an unsupported one is called it handles the response instead of throwing an error
@api_view(http_method_names=['GET', 'POST', 'WHATEVER METHOD YOU WANT']
1 Comment
@api_view() a lot, and @csrf_exempt() only in specific cases.The @api_view decorator in Django REST Framework takes a list of HTTP methods that your function based view should respond to whilst @csrf_exempt decorator marks a view as being exempt from the protection ensured by the middleware. This is done because by default, Django's CSRF protection requires a valid CSRF token to be included in any incoming POST, PUT, or DELETE requests to ensure they originate from your website and not a malicious third-party site. Applying @csrf_exempt tells Django that the view does not need this token. For example CSRF token will not be required from this :
@csrf_exempt
@api_view(['GET', 'POST'])
def hello_world(request):
if request.method == 'POST':
return Response({"message": "Got some data!", "data": request.data})
return Response({"message": "Hello, world!"})
It is generally recommended that unsafe HTTP operations, such as POST, PUT, PATCH and DELETE should require a valid CSRF token.
See api_view and csrf_exempt
Comments
Explore related questions
See similar questions with these tags.
@csrf_exemptisn't part of Django Rest Framework, it's part of Django. The two decorators are extremely different. My suggestion would be to read the DRF docs about @api_view, and read the docs about @csrf_exempt.