Building REST APIs with Django
# CHAPTER 15
Building REST APIs with Django
1. Introduction
Modern web development is increasingly decentralized. Often, your backend must serve data not just to web browsers via HTML templates, but to iOS apps, Android apps, and separate React/Vue frontend applications. These clients do not understand HTML; they require raw data formatted as JSON. To achieve this, we build REST APIs. While you can build APIs using vanilla Django, the industry standard is to use the Django REST Framework (DRF). In this chapter, we will install DRF, create Data Serializers, and build API endpoints.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand the purpose of a REST API in a decoupled architecture.
- Install and configure Django REST Framework (DRF).
-
Create a
ModelSerializerto convert Python objects to JSON.
- Build class-based API Views.
- Test endpoints using the DRF Browsable API interface.
3. Beginner-Friendly Explanation
Imagine you are an author (The Database). You only write books in French (Python Objects). A reader from Japan (An iOS App) wants to read your book. They do not understand French. If you hand them the French book (HTML/Python), they cannot process it. You need a Translator (The Serializer). The Translator takes your French book, translates it into the universal language of English (JSON format), and hands it to the reader. Now, regardless of whether the reader is from Japan (iOS), Brazil (Android), or Canada (React), they can all understand the universal English format. Django REST Framework is the translation agency that automates this entire process.4. Step 1: Installing Django REST Framework
Open your terminal and install the package:Register the framework in your core/settings.py file:
5. Step 2: Creating a Serializer
The Serializer acts exactly like aModelForm, but instead of converting a Database Model into HTML <input> tags, it converts the Database Model into a JSON string.
Create a new file: blog/serializers.py
6. Step 3: Building the API View
Instead of usingrender() to return an HTML file, we will use DRF's special classes to return the serialized JSON data.
Update blog/views.py:
7. Step 4: Routing the API
Finally, we connect our new API View to a URL. It is standard practice to prefix API routes with/api/.
Update blog/urls.py:
8. Testing the API
Start your development server. Navigate your browser tohttp://127.0.0.1:8000/blog/api/posts/.
You will be greeted by the DRF Browsable API. Instead of a raw, ugly wall of JSON text, DRF provides a beautiful, interactive webpage where you can view the JSON payload and even test POST requests directly from the browser without needing tools like Postman!
*The raw output looks like this:*
9. Backend Workflow: Full CRUD with Generic Views
Writing views manually for Create, Read, Update, and Delete takes dozens of lines of code. DRF provides Generic Views that do all the work for you. You can replace the entire view from Step 3 with just three lines of code:*This is the true power of Django REST Framework. Massive functionality with minimal code.*
10. Best Practices
-
API Versioning: Just like in Node.js, always version your APIs. In the master
urls.py, route traffic like this:path('api/v1/', include('blog.urls')). This ensures that if you completely redesign the API next year (v2), the legacy mobile apps relying onv1won't crash.
11. Common Mistakes
-
Forgetting
many=True: When querying a list of objects (Post.objects.all()), if you forget to pass themany=Trueargument to the Serializer, DRF will crash because it expects a single object but received a list.
12. Exercises
-
1.
Explain the conceptual relationship between a Django
ModelForm(used for HTML pages) and a DRFModelSerializer(used for APIs). How are their primary tasks similar?
13. Coding Challenges
-
Challenge: Using the
@apiview(['GET'])decorator, write a detail endpointapipost_detail(request, pk)that fetches a single post by its Primary Key (pk). Pass the single object to the Serializer (do *not* usemany=True), and return the Response.
14. MCQs with Answers
What is the primary purpose of a Serializer in the Django REST Framework?
When returning data from an API endpoint using Django REST Framework, which object should you use to send the response instead of the standard Django HttpResponse?
15. Interview Questions
-
Q: Explain why Django developers rely on the Django REST Framework (DRF) package instead of simply using Python's built-in
jsonmodule to serialize data manually.
- Q: Describe how a decoupled architecture works (e.g., a React frontend communicating with a Django DRF backend). What are the advantages of this approach over traditional server-side rendering (SSR) using Django templates?
16. FAQs
Q: Can I use Django Templates and DRF in the exact same project? A: Yes! This is a hybrid approach. You might render your public blog pages using standard Django HTML Templates for good SEO, while building a separate/api/ section in the same project to feed data to your company's iOS mobile app.