Creating Python APIs - The Django REST framework. Completing todos using API [13/n]
Welcome back to my series on creating Python APIs using Django REST framework.
Today we will add the ability to be able to complete the todos using the API.
So first we start by creating an url for the completed todos page.
so the final url should look like 127.0.0.1:8000/api/todos/5/complete
Now lets add its respective view as well:
Notice that we create a new serializer TodoCompleteSerializer for this, which we will create after we are done with the views:
Also notice that we have created a new function called perform_update, what it does is puts the datecompleted as the time now, so you have to import timezone from django utils using the command
from django.utils import timezone
Note that we already have datecompleted in our database so we just use its instance.
Now that we are done with our views, lets create that serializer we were talking about earlier; TodoCompleteSerializer
Why do we need a new serializer?
It's because we want all of the fields to be read-only fields except the id which we will still include in the fields.
And since we want clean code its better to create two separate functions for two separate functions.
Don't forget to import this serializer using the command from .serializers import TodoCompleteSerializer
in your views.py file.
Once all of this is done, we can go to the link:
127.0.0.1:8000/api/todos/5/complete
Notice the ids, although there are 2 todos left, there ids would not necessarily be 1 and 2, so make sure you check the id before entering it in the url.
You should see the following page.
The great thing about Django REST Framework is that it tells you exactly what needs to be done.
In this specific case, it says "detail": "Method \"GET\" not allowed." and only PUT, PATCH, OPTIONS is allowed. This means that GET is not allowed and we would have to use PUT. So just click on the PUT button at bottom right.
You should see the below which means it went through.
You can check that by going to the API main page (127.0.0.1:8000/api/todos) where it lists all current todos.
and the #### completed todos:
This is what you would see if you go through the app:
Current Todos
Completed Todos
Congratulations! You just added a function to complete the todos using the APIs. Great Job!
Next we will see how to add basic authentication in our app.
- You can view the entire code on my github profile.
Hope you enjoyed this post! If you happen to like it, feel free to share. You can also follow me on Twitter on my coding journey.