Creating Python APIs - The Django REST framework. Building a Reddit clone - Adding Posts to DB.[4/n]

Welcome back to my API series, where I create and integrate an API to our app. This is part 4 of the series, I highly recommend to read the 1st three posts to be able to follow through with this post.

Part 1 : Creating Python APIs - The Django REST framework : Basics[1/n]

Part 2 : Creating Python APIs - The Django REST framework. Building a Reddit clone - Models.[2/n]

Part 3 : Creating Python APIs - The Django REST framework. Building a Reddit clone - Serializers.[3/n]

Now that we've made our 1st ever API call, we need to add some data in the database to display through the API.

The simplest method is creating a superuser and adding posts via the admin panel.

Before creating a superuser make sure we migrate every changes we've made to the model using the command python manage.py migrate

image.png

Now we can create a superuser using the command python manage.py createsuperuser

image.png

Now that you've created a superuser as well, before accessing the admin panel you need to register our class. We do that in the admin.py file. If we don't register our classes and start the server to access the admin panel we'd see the below:

image.png

You need to add the following to register the classes we've created:

image.png

After you've successfully registered the classes run the server using the command python manage.py runserver then type the url http://localhost:8000/admin/ as we need to add posts using the admin panel.

You should see the panel as below:

image.png

Notice you have both the posts and votes in the panel.

Since our API displays the posts, let's create a new post:

image.png

image.png

Now refresh the page with url http://localhost:8000/api/posts and you should see the following:

image.png

The first post that you created!

When you display the data on the browser it displays it very neatly in a nice webpage. You can also view the json data on your terminal using the curl command.

You can do this by running the server on one terminal window and running the command curl http://localhost:8000/api/posts in another terminal window.

You should see the following:

image.png

This is the same data as we viewed on the webpage when we run the url localhost:8000/api/posts in the browser, but in json format.

Bonus:

If you want to change the name in the admin panel from "Post Object 1" to displaying the title name, add the following code in the Post class in models.py.

def __str__(self):
    return self.title

image.png

Then refresh the page and you should see the following:

image.png

No Comments Yet