Creating a Django API using Django Rest Framework APIView

The answer is no.

A user should be able to update articles.

For this, we will update our articles endpoint to allow users to update an article by sending a PUT request to the article.

First, add a new path in the articles urlpatterns from which the update will be sent to.

path('articles/<int:pk>', ArticleView.

as_view())Next, let's add an update method to our serializer that will do the update for us.

Your code now should look like the followingserializer.

pyWhat is happening in the update method is that we are passing in the instance of the article we want to update and if the user has provided a value to update with, we reassign that value otherwise we maintain the old value of the attribute.

Now let’s work on getting the update request from the user and updating the article.

First, we have to define the put method in our ArticleView , this method should accept a pk URL parameter which we will use to query the Article we want to update.

Here is how the put method should look like.

We are passing partial=True to the serializer since we want to be able to update some fields but not necessarily all at once.

 Using Postman or any other tool, you can now be able to update an article by sending a put request to the URL http://127.

0.

0.

1:8000/articles/<article id> with the data you want to update.

Great progress so far.

Now, suppose you decide you don’t want this article anymore?? In the last part of this blog, we are going to add a delete functionality to our API.

For this, we will create a delete method in the APIView that takes the id of the article we want to delete as an argument.

For the delete method, all we are doing is getting the article if it exists and then deleting it and returning a response to the user.

With this, we have a functioning API where we can perform all the basic requirements of an API i.

e CreateReadUpdateDelete (CRUD) operations using the Django Rest Framework.

In part two of this blog, we will go over how to use Django Rest Framework GenericAPIView which will make the process even easier.

Happy coding.

Link to Part 2Creating a DjangoRest API using DjangoRestFramework part 2.

This is the second part of a series.

The first part can be found here.

In this part, we will recreate the Blog API that…medium.

com.

. More details

Leave a Reply