Welcome to the first lesson of our course on implementing an API for a TODO App using Django. In this lesson, we will dive into CRUD operations, which are fundamental building blocks for any web application.
CRUD stands for Create, Read, Update, and Delete. These operations represent the basic actions you can perform on any dataset:
- Create: Adding new entries to the dataset.
- Read: Fetching entries from the dataset.
- Update: Modifying existing entries in the dataset.
- Delete: Removing entries from the dataset.
CRUD operations are vital because they mirror how users interact with applications. Whether you are creating a new blog post, updating your profile, or deleting an email, you are performing CRUD operations.
In this lesson, we'll focus on the first two operations — Create and Read — within the context of a TODO App project.
Before we delve into CRUD operations, let's briefly recap the initial setup of our Django project and app. This will ensure we are all on the same page.
We have a Django project and within it, an app called myapp
. We also have a model named Todo
. Here’s a quick code snippet to remind you of the model setup:
Python1# project/myapp/models.py 2from django.db import models 3 4class Todo(models.Model): 5 task = models.CharField(max_length=200) 6 completed = models.BooleanField(default=False)
This model has two fields:
task
: A character field to store the task description.completed
: A boolean field to mark whether the task is completed.
We also have a serializer to convert our model instances to JSON. Here’s a quick code snippet to remind you of the serializer setup:
Python1# project/myapp/serializers.py 2from rest_framework import serializers 3from .models import Todo 4 5class TodoSerializer(serializers.ModelSerializer): 6 class Meta: 7 model = Todo 8 fields = ['id', 'task', 'completed']
In the TodoSerializer
, we can use fields = '__all__'
to include all model fields in the serialized output instead of specifying the list of fields.
You can do it like this:
Python1class TodoSerializer(serializers.ModelSerializer): 2 class Meta: 3 model = Todo 4 fields = '__all__'
By setting fields
to __all__
, we instruct the serializer to include all fields from the Todo
model in the serialized output. This is a convenient shortcut when you want to expose all fields of a model in the API response. However, for more control, you can specify individual field names in the fields
list, e.g., fields = ['task', 'completed']
. In the tasks, we will use both approaches, so you can get comfortable with both.
Now, let's create the views to handle our CRUD operations. We'll start with the views to list all TODO items and to add new TODO items.
We'll use Django Rest Framework's ListCreateAPIView
for this purpose. This class-based view provides both GET
and POST
methods to handle listing and creating resources, respectively.
Here’s the code for our views.py
:
Python1# project/myapp/views.py 2from rest_framework import generics 3from .models import Todo 4from .serializers import TodoSerializer 5 6class TodoListCreate(generics.ListCreateAPIView): 7 queryset = Todo.objects.all() 8 serializer_class = TodoSerializer
Explanation:
- We import
generics
fromrest_framework
, which provides a variety of pre-built class-based views. - We import the
Todo
model andTodoSerializer
. - The
TodoListCreate
class inherits fromListCreateAPIView
, which provides theGET
andPOST
methods. - The
queryset
specifies the data to be handled by the view, in this case, allTodo
objects. - The
serializer_class
specifies which serializer to use to convert the data to/from JSON.
Next, let's define the URL patterns to route requests to our newly created view. We'll map the URL path todos/
to TodoListCreate
view.
Here’s how to configure the urls.py
:
Python1# project/myapp/urls.py 2from django.urls import path 3from .views import TodoListCreate 4 5urlpatterns = [ 6 path('todos/', TodoListCreate.as_view(), name='todo_list_create'), 7]
Explanation:
- We import the
path
function fromdjango.urls
. - We import the
TodoListCreate
view. - We define a URL pattern that routes
GET
andPOST
requests to thetodos/
endpoint, handled by theTodoListCreate
view.
Finally, let's test our implementation using Python's requests
library. We'll use a script to:
- Create a new TODO item via a
POST
request. - Fetch all TODO items via a
GET
request.
Here’s the testing script:
Python1# send_request.py 2import requests 3 4URL = 'http://127.0.0.1:8000/api/todos/' 5 6# Create a new To-Do item 7new_todo = {'task': 'First task'} 8post_response = requests.post(URL, json=new_todo) 9print(post_response.json()) # Expect to see the newly created TODO item 10 11# Fetch all To-Do items 12get_response = requests.get(URL) 13print(get_response.json())
Explanation:
- We define the URL for our TODO API.
- We create a new TODO item by sending a
POST
request with a JSON payload containing the task description.post_response
should return the JSON representation of the newly created TODO item.
- We fetch all TODO items by sending a
GET
request.get_response
should return a JSON list of all TODO items.
Expected Output:
When you run send_request.py
, you should see the following output:
JSON1# Output of the POST request - Example Response 2{ 3 "id": 1, 4 "task": "First task", 5 "completed": false 6} 7 8# Output of the GET request - Example Response 9[ 10 { 11 "id": 1, 12 "task": "First task", 13 "completed": false 14 } 15]
This confirms that we can successfully create and read TODO items.
In this lesson, you learned about CRUD operations and their importance in web development. You also:
- Recapped the initial setup of our Django project and app.
- Implemented views to list and add TODO items using Django Rest Framework's
ListCreateAPIView
. - Configured URL routing for the TODO operations.
- Tested the Create and Read operations using Python's
requests
library.
CRUD operations are crucial for any web application, and mastering them is a foundational step in becoming a proficient web developer.
Up next, you'll get to practice what we've covered in hands-on exercises. You'll implement these CRUD operations yourself, fine-tuning your understanding and skill set.
Great job on completing the first lesson! Let's move on to the practice exercises.