-3

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
  • 2
    @csrf_exempt isn'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. Commented Nov 17 at 16:34
  • have you read them in the doucmentation ? Commented Nov 18 at 7:18

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Answer's good; could be improved by links to the relevant decorators in the official docs: docs.djangoproject.com/en/5.2/ref/csrf/… and django-rest-framework.org/api-guide/views/#api_view Also, to answer the "which should I use" part of the question, you'll probably use @api_view() a lot, and @csrf_exempt() only in specific cases.
1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.