Function-Based Views & Class-Based Views
Function-Based Views & Class-Based Views
In Django REST Framework, you can build API endpoints using either Function-Based Views with the @api_view decorator or Class-Based Views inheriting from APIView. Choosing between them depends on whether your endpoint represents simple procedural logic or an object-oriented controller with reusable behaviors.
1. Function-Based Views with @api_view
The @api_view decorator wraps standard Python functions, giving them DRF superpowers:
- Parses incoming request bodies into
request.data. - Enforces permitted HTTP methods.
- Enables content negotiation (JSON vs Browsable API).
2. Class-Based Views with APIView
APIView organizes HTTP methods into dedicated class methods (get(), post(), put(), delete()), eliminating messy if request.method == "..." branches:
3. Comparison Matrix
| Feature | @api_view (Functional) | APIView (Class-Based) |
|---|---|---|
| Code Organization | if/elif on request.method | Distinct def get(), def post() methods |
| Inheritance & Mixins | Not supported | Supported (OOP inheritance) |
| URL Registration | path("url/", views.my_view) | path("url/", views.MyView.as_view()) |
| Best Used For | One-off calculations, simple webhooks | Resource endpoints, CRUD logic, OOP reuse |
4. Understanding request.data
Unlike standard Django's request.POST (which only parses form-encoded data), DRF's request.data:
- Handles incoming JSON payloads (
application/json). - Handles standard form submissions (
multipart/form-data,application/x-www-form-urlencoded). - Handles file uploads transparently without inspecting
request.FILESseparately!
Practice Quiz
Create, Retrieve, Update, Delete APIs
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Serializers Overview | Create, Retrieve, Update, Delete APIs |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.