Creating Python APIs - The Django REST framework. Listing Completed Todos.[11/n]
Welcome back to my series on creating Python APIs using Django REST framework.
Today we will list out the completed Todos in our API view.
Add the below to the urls.py file that you created in the api folder.
The final address would be 127.0.0.1:8000/api/todos/completed
Notice that we have added permission_class in the TodoCompletedList class as well. That is to make sure that only the authenticated users can view the completed todos.
We have defined the get_queryset to make sure we get only the data that we want returned. Make sure you use the exact function get_queryset because it is Django REST framework specific.
Also notice that we're returning the same todo objects as we did in out todo.views.
Notice in the TodoSerializer class, we have created and datecompleted as read-only field because we don't want users to be able to change those fields.
We have a meta class, where we add the models to retrieve the fields from. We have taken the fields from the todo.models. We do not need to retrieve user field because only authorized users can access the list so no sense displaying that again.
So, now if you go to 127.0.0.1:8000/api/todos/completed, the following is what you should get. (Make sure the server is running before accessing the API using the command
python manage.py runserver)
Congratulations! You've successfully listed the completed todos using API. It must feel awesome to have achieved that. In the next article, we will add the basic CRUD (Create, Read, Update, Delete) functionality in the API.
- 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.