Django REST Framework (DRF) Basics
Introduction to DRF, why we need it, and how it upgrades Django for modern APIs.
🧑🏫 Sabse pehle — simple mein samjho#
Pure Django ka main kaam tha HTML generate karke browser ko bhejna. Par aajkal zamana React, React Native, aur Next.js ka hai. In modern frontends ko HTML nahi chahiye, inko sirf JSON data chahiye. Pure Django ko JSON data bhejne ke liye modna kaafi mushkil hota hai. Yahi par Django REST Framework (DRF) aata hai. Ye ek toolkit hai jo Django ke upar lagti hai, aur usko ek super-powerful, secure API backend mein badal deti hai jo directly JSON mein baat karta hai.
Why use DRF instead of standard Django?#
- Serialization: Automatically converts complex Django Database Models into JSON, and parses incoming JSON back into Database Models.
- Authentication Policies: Provides built-in support for Token-based auth, OAuth2, and JWTs.
- Browsable API: DRF generates a beautiful, interactive web interface for your API endpoints. You can test your GET and POST requests directly in the browser!
- Throttling & Permissions: Easily restrict who can access what, and how often they can access it.
Installation and Setup#
-
Install via pip:
pip install djangorestframework -
Add it to your
INSTALLED_APPSinsettings.py. Order doesn't strictly matter, but it's usually placed near the top.INSTALLED_APPS = [ ... 'rest_framework', 'blog', ] -
(Optional but Recommended) Add global configuration settings for DRF at the bottom of
settings.py.# Configure global behaviors for all your API views REST_FRAMEWORK = { # Force pagination so APIs don't crash if they return 100k items 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, # Determine who can access APIs globally (e.g., must be logged in) 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', # Change to IsAuthenticated for private APIs ] }
The Architecture of a DRF Request#
Building an API with DRF involves three layers (which heavily mirror standard Django):
- The Database Model (
models.py): Exactly the same as standard Django. - The Serializer (
serializers.py): The translator. It acts similarly to a Django Form, but instead of validating HTML form data, it validates and transforms JSON. - The API View (
views.py): The logic layer. It receives the request, asks the serializer to handle the data, and returns an HTTPResponseobject containing the JSON. - The Router (
urls.py): Maps the endpoint URL to the specific API View.
In the next sections, we will explore Serializers and Views in detail.