0
0
DjangoHow-ToBeginner · 3 min read

How to Use api_view Decorator in DRF in Django

Use the @api_view decorator from Django REST Framework to turn a function into an API view that handles HTTP methods like GET or POST. Place @api_view(['GET', 'POST']) above your function to specify allowed methods and return Response objects for API responses.
📐

Syntax

The @api_view decorator wraps a function to make it an API view that accepts specified HTTP methods.

  • @api_view(['GET', 'POST']): List HTTP methods the view supports.
  • def my_view(request):: Define your view function with a request parameter.
  • return Response(data): Return a DRF Response object with data.
python
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def example_view(request):
    return Response({'message': 'Hello, world!'})
💻

Example

This example shows a simple API view that responds to GET requests with a greeting message.

python
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def hello_api(request):
    return Response({'greeting': 'Hello from DRF!'})
Output
{"greeting": "Hello from DRF!"}
⚠️

Common Pitfalls

Common mistakes include:

  • Not specifying allowed HTTP methods in @api_view, which defaults to no methods allowed.
  • Returning Django HttpResponse instead of DRF Response, which can cause incorrect content types.
  • Forgetting to import api_view or Response from rest_framework.
python
from rest_framework.decorators import api_view
from django.http import HttpResponse

@api_view(['GET'])
def wrong_view(request):
    return HttpResponse('This is wrong')  # Should use Response instead

# Correct way:
from rest_framework.response import Response

@api_view(['GET'])
def correct_view(request):
    return Response({'message': 'This is correct'})
📊

Quick Reference

FeatureDescription
@api_view(['GET', 'POST'])Declare which HTTP methods the function accepts
requestThe incoming HTTP request object
Response(data)Return API response with JSON or other content
Import from rest_framework.decoratorsGet api_view decorator
Import from rest_framework.responseGet Response class

Key Takeaways

Use @api_view to declare allowed HTTP methods for function-based API views.
Always return rest_framework Response objects, not Django HttpResponse.
Import api_view and Response from rest_framework modules.
Specify HTTP methods as a list of strings in the decorator.
api_view makes simple API endpoints easy without class-based views.