Introduction
Welcome back to our Django REST Framework (DRF) adventure! In Part 1, we laid the groundwork by setting up a Django project, installing DRF, and crafting a Task
model. Now, in Part 2, we’re diving into the fun stuff—building API endpoints to Create, Read, Update, and Delete (CRUD) tasks. By the end of this guide, your Task Manager API will be fully functional, and ready to test with tools like Postman or DRF’s browsable API.
Let’s make your API come alive, step by step!
Table of Contents
- Step 1: Create a Serializer
- Step 2: Build API Views
- Step 3: Define URL Routes
- Step 4: Test the API
- Conclusion
- What’s Next?
Step 1: Create a Serializer
Serializers are the bridge between your Django models
and JSON data—perfect
for REST APIs. Let’s create one for our Task
model.
In your tasks
app, create a new file called serializers.py
and add:
from rest_framework import serializersfrom .models import Taskclass TaskSerializer(serializers.ModelSerializer):class Meta:model = Taskfields = '__all__'from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__'from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__'
Enter fullscreen mode Exit fullscreen mode
What’s happening here?
The TaskSerializer
automatically converts Task model
instances into JSON
(and back again) using DRF’s ModelSerializer
. The fields = '__all__'
line includes all model fields—title, description, completed, and created_at—in the API responses.
Step 2: Build API Views
Time to define the views that power our CRUD operations! DRF’s generic views make this a breeze.
Open tasks/views.py and update it with:
from rest_framework import genericsfrom .models import Taskfrom .serializers import TaskSerializerclass TaskListCreateView(generics.ListCreateAPIView):queryset = Task.objects.all()serializer_class = TaskSerializerclass TaskDetailView(generics.RetrieveUpdateDestroyAPIView):queryset = Task.objects.all()serializer_class = TaskSerializerfrom rest_framework import generics from .models import Task from .serializers import TaskSerializer class TaskListCreateView(generics.ListCreateAPIView): queryset = Task.objects.all() serializer_class = TaskSerializer class TaskDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Task.objects.all() serializer_class = TaskSerializerfrom rest_framework import generics from .models import Task from .serializers import TaskSerializer class TaskListCreateView(generics.ListCreateAPIView): queryset = Task.objects.all() serializer_class = TaskSerializer class TaskDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Task.objects.all() serializer_class = TaskSerializer
Enter fullscreen mode Exit fullscreen mode
Breaking it down:
- TaskListCreateView: Handles GET (list all tasks) and POST (create a new task).
- TaskDetailView: Manages GET (retrieve a task), PUT (update a task), and DELETE (delete a task) for a specific task ID.
- DRF’s generic class-based views (CBVs) save us from writing boilerplate code—efficiency at its finest!
Step 3: Define URL Routes
Let’s wire up our views with URL routes so users can hit those endpoints.
Create or edit tasks/urls.py with:
from django.urls import pathfrom .views import TaskListCreateView, TaskDetailViewurlpatterns = [path('tasks/', TaskListCreateView.as_view(), name='task-list-create'),path('tasks/<int:pk>/', TaskDetailView.as_view(), name='task-detail'),]from django.urls import path from .views import TaskListCreateView, TaskDetailView urlpatterns = [ path('tasks/', TaskListCreateView.as_view(), name='task-list-create'), path('tasks/<int:pk>/', TaskDetailView.as_view(), name='task-detail'), ]from django.urls import path from .views import TaskListCreateView, TaskDetailView urlpatterns = [ path('tasks/', TaskListCreateView.as_view(), name='task-list-create'), path('tasks/<int:pk>/', TaskDetailView.as_view(), name='task-detail'), ]
Enter fullscreen mode Exit fullscreen mode
Then, connect it to your project’s main taskmanager/urls.py:
from django.urls import path, includeurlpatterns = [path('api/', include('tasks.urls')),]from django.urls import path, include urlpatterns = [ path('api/', include('tasks.urls')), ]from django.urls import path, include urlpatterns = [ path('api/', include('tasks.urls')), ]
Enter fullscreen mode Exit fullscreen mode
Your API endpoints are now live:
- GET /api/tasks/ – Fetch all tasks
- POST /api/tasks/ – Add a new task
- GET /api/tasks/{id}/ – View a specific task
- PUT /api/tasks/{id}/ – Update a task
- DELETE /api/tasks/{id}/ – Remove a task
Step 4: Test the API
Start the Django development server:
python manage.py runserverpython manage.py runserverpython manage.py runserver
Enter fullscreen mode Exit fullscreen mode
Now, let’s test your shiny new API with these methods:
Django’s Browsable API
Visit http://127.0.0.1:8000/api/tasks/
in your browser. DRF’s built-in interface lets you:
- View all tasks
- Create a new task with a simple form
- Update or delete tasks by navigating to http://127.0.0.1:8000/api/tasks/{id}/
Browsable API
Postman
Use Postman to send requests:
- GET http://127.0.0.1:8000/api/tasks/ – List tasks
- POST http://127.0.0.1:8000/api/tasks/ – Add a task (include JSON like {“title”: “Test Task”, “description”: “Testing API”})
- PUT or DELETE on http://127.0.0.1:8000/api/tasks/{id}/
New to Postman? Check out this quick guide.
cURL
For command-line fans:
- List tasks:
curl -X GET http://127.0.0.1:8000/api/tasks/curl -X GET http://127.0.0.1:8000/api/tasks/curl -X GET http://127.0.0.1:8000/api/tasks/
Enter fullscreen mode Exit fullscreen mode
- Create a new task:
curl -X POST -H "Content-Type: application/json" \-d '{"title": "Second Series", "description": "Write Part 2 of Task Manager API", "completed": false}' \http://127.0.0.1:8000/api/tasks/curl -X POST -H "Content-Type: application/json" \ -d '{"title": "Second Series", "description": "Write Part 2 of Task Manager API", "completed": false}' \ http://127.0.0.1:8000/api/tasks/curl -X POST -H "Content-Type: application/json" \ -d '{"title": "Second Series", "description": "Write Part 2 of Task Manager API", "completed": false}' \ http://127.0.0.1:8000/api/tasks/
Enter fullscreen mode Exit fullscreen mode
Conclusion
Boom! You’ve just built a fully functional CRUD API with Django REST Framework. Your Task Manager API can now handle creating, reading, updating, and deleting tasks.
Summary Checklist
- Created a serializer for the Task model
- Built API views for CRUD operations
- Defined URL routes for your endpoints
- Tested the API with DRF’s browsable API, Postman, and cURL
What’s Next?
In Part 3, we’ll lock down our API with authentication to keep those tasks secure. Stay tuned for more
Found this guide helpful? Let me know in the comments
原文链接:How to Build a Task Manager API with Django REST Framework: Part 2- CRUD
暂无评论内容