Creating Python APIs - The Django REST framework. Building a Reddit clone - Creating Posts via API.[5/n]

In the last article, we created the posts using the admin panel. In this article we will add the posts using the API itself. Keep reading to find out more.

All you have to do is change the instance method from ListAPIView to ListCreateAPIView in views.py as we want to not only want to view the posts but also create them.

image.png

Now if you refresh the browser window, then you should see the following:

image.png

You can now add posts through the form generated on the page.

image.png

Now if you refresh the page, you would be able to see both the posts that you've added.

image.png

Now, you might think that's all we had to do to create posts via the API but that's not true. There's more.

When you try to create a Post using the json data and do not put the poster name, it shows that it cannot be null. Ideally the user should not get an option to select the poster. It should be the logged in user.

image.png

That's what we're going to change next by making the poster field read-only in the serializer file.

image.png

Notice that we also added the poster_id to the fields in class Meta.

Now if we refresh our browser window then we'll notice that there is no poster field in both the HTML form and the json field.

image.png

image.png

But when we try to fill the data and try to create the post we get the following error saying someone has to be the poster.

image.png

So what we can do to solve this error is to override a function just before the API is trying to save the data in the database.

We need to make the following changes in views.py

image.png

Now if you refresh and enter the details for the new post, notice it now has a poster and a poster_id field that we just created. image.png

We are able to perform these functions because we are logged in as the user. If we copy the url http://localhost:8000/api/posts and post it in another browser and try to create a post it would give the following error:

image.png

Which basically means that we don't have permission to call the API because we are not authenticated. We need to set that in the views.py file.

image.png

Notice that we had to import permissions from rest framework and the instance of the permissions class is 'IsAuthenticatedOrReadonly` which basically means that if you're logged in you can create new post else you can only view the posts, just like reddit.

So, in a browser where you're not logged in you can still view the posts but not create new ones.

image.png

But in a browser where you're logged in you can do both.

image.png

In the next article, we will write code on how to upvote a particular post. Stay tuned!

No Comments Yet