← Back to Django Course | Chapter 14: REST API with DRF | Lesson 4 of 6

Function-Based API के Views

@api_view decorator एक normal Django function को ऐसे function में बदलता है जो JSON in और JSON out बोलता है।
Syntax
markup
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET', 'POST'])
def view_name(request):
    if request.method == 'POST':
        serializer = ModelNameSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
    return Response(data)

एक GET Endpoint लिखना

@api_view([GET]) इस function को एक DRF view मार्क करता है। View एक queryset बनाता है, इसे serialize करता है, और result को एक DRF Response में wrap करके return करता है।

उदाहरण: Writing a GET Endpoint

@api_view([GET]) marks this function as a DRF view. The view builds a queryset, serializes it, and returns the result wrapped in a DRF Response.

markup
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer

@api_view(['GET'])
def book_list(request):
    books = Book.objects.all()
    serializer = BookSerializer(books, many=True)
    return Response(serializer.data)
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

POST Requests Handle करना

@api_view में POST allow करना इसी function को नया data accept करने देता है। DRF views में request.data (request.POST नहीं) parsed JSON body रखता है।

उदाहरण: Handling POST Requests

Allowing POST in @api_view lets this same function accept new data. request.data (not request.POST) holds the parsed JSON body in DRF views.

markup
@api_view(['GET', 'POST'])
def book_list(request):
    if request.method == 'POST':
        serializer = BookSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
    books = Book.objects.all()
    return Response(BookSerializer(books, many=True).data)
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

URL Wire Up करना

एक function-based API view urls.py में exactly एक regular Django view जैसे ही connect होता है।

उदाहरण: Wiring Up the URL

A function-based API view is connected in urls.py exactly like a regular Django view.

markup
from django.urls import path
from . import views

urlpatterns = [
    path('api/books/', views.book_list, name='book-list'),
]
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. @api_view([GET, POST]) decorator भूल जाना, जो view को JSON request bodies parse करने या DRF के Response objects सही से render करने में असमर्थ छोड़ देता है।
  2. DRF के Response के बजाय एक plain Django HttpResponse return करना, automatic content negotiation और browsable API खोते हुए।
  3. कई HTTP methods handle करने वाले एक view के अंदर request.method न जांचना, जिससे GET logic एक POST request पर भी run हो जाता है।
चैप्टर सारांश
  • @api_view([GET, POST]) एक function को एक DRF API view मार्क करता है और restrict करता है कि यह कौन से HTTP methods accept करता है।
  • DRF की Response class HttpResponse replace करती है और automatically JSON (या browser में browsable API) render करती है।
  • Function-based API views request.method पर branch करते हैं exactly regular Django views की तरह।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.