Building GraphQL Article API with Django | Python 3
The article guides you to build full-fledged Article GraphQL API with Django framework. After building this you can consume the API with whatever frontend you like → react, flutter, vue, etc.
Background Knowledge Required -
- You should know basics of Django. How django works, how to build models, how url-patterns works …. these knowledge is essential to know before following this article.
- You are not required to know GraphQL. But if you want to know just the basics of GraphQL and how to build very simple GraphQL API with Django you can read this article →click. But don’t worry I will discuss the concepts in this article also.
1️⃣ Setting Up The Project
Go to your terminal and follow these commands →
These are all the basic commands when you create a new django project. I have used pipenv
to setup my virtual environment. But you can use anything you like to setup your virtual environment. At this point you can go to http://127.0.0.1:8000/ and you will see the default page that Django gives us.
2️⃣ Coding The Models
During set up we have created a new app article
. Register our new app in core/settings.py
.
After this registration, let’s go to article/models.py
and code the models we need.
I have added two models. One is the main Article
and another one is CommentOnArticle
. One article can have many comments. Also notice in the Article
model I have a field to count total number of views article has got. Also I have field to record which users has clapped on the article.
Because I have a ImageField
in my model I need to install package : pillow
. Just go your terminal and type →
Another small step we need to is to define media root paths in core/settings.py
file add this at the bottom →
We need to also edit core/urls.py
→
Now let’s register the models in django admin panel. To do so, go to article/admin.py
and write this →
Now I could have just register the models in admin with simple admin.site.register(ClassName)
statement. But I like to it with model classes. Just personal preference. You can do whatever way you like.
If you have made so far, you can go to http://127.0.0.1:8000/admin/ and login with the super user account you created during setup. After login you will view a page like this.
Go ahead and add some users. Also add some demo Articles and some demo comments for articles.
3️⃣ Building The GraphQL API
To build GraphQL APIs, graphene-django
package needs to be installed. If you want official docs for this package: click here. To install the package, in the terminal type →
Now go to core/settings.py
and add this →
⚠️ IMPORTANT: An important thing to know about GraphQL is that, unlike REST APIs where you need different URL endpoints to query for different data, GraphQL does it a simpler way. You only need one URL endpoint and you will query for whatever data you need.
Now lets add the only URL path we need in core/urls.py
file.
Explanation: At the top we have imported csrf_exempt
decorator that will allow us to make modify data from tools like Postman, Insomnia, etc. That we have imported the GraphQLView
view which is provided to us by the graphene package. Inside urlpatterns
we have just added a new path where endpoint is graphql/
. You can edit the endpoint and name it whatever you like. next we have added the view class wrapped around by the csrf_exempt
decorator. graphiql=True
means that we will get a very helpful panel when we visit the URL from where we will query the data. At this moment if you visit http://127.0.0.1:8000/graphql/ you will get error saying that a schema is required.
What is schema ? → If you want the technical data that you will not understand in the first reading visit this page. Now I also don’t know how to put this in simple language 🤦🏻♂️. Just follow the flow and you will understand how to create and play with schema.
In article
directory add a new file and name it schema.py
. In this new file add this →
Explanation : Inside article/schema.py
file at the top I have imported the necessary modules from graphene package. Then imported the models that we have coded in models.py
. Next is the confusing part. If you have ever write forms you will find the code very similar. These are called “Types”. I have two type classes one for the article and another for the comments. In ArticleType
class I have not added “fields”, that simply means that I want all the fields from Article
model. But in the next type class I have mentioned fields. Now you will ask why I have replies
in fields. I don’t have any field in CommentOnArticle
model named as replies
. Don’t worry I am referring to the related name. I don’t want to refer to related comment as parent_comment
but I want to refer to them as replies
just as a normal frontend develper will try to do. Then I have Query
class. Here I mention the queries that frontend developer can do. I have added two queries one for all the articles and another for specific article. Then we have added the resolve_...
function to resolve the queries. By default you have to name the resolve functions like this.
Just as in regular django project, we add different urls.py
file in different apps and all of them go to the core urls.py
file, We will have different schema.py
file in different apps and all of them will be called by a single core schema.py
file. Add a new file inside core directory and name itschema.py
. Add this inside the new file →
Fantastic 🥳. We have successfully created a schema. But we still don’t want what is schema. LOL! I am so bad writer. But don’t worry now. Go ahead and this at the bottom of core/settings.py
file.
Here we are just saying that our main schema is core.schema.schema
. At this moment you can go to http://127.0.0.1:8000/graphql/ and you will get a nice page divided in two panel one for the input and another to view the output. Lets test our schema →
The whole output is not fitted inside my screenshot. But you get the idea. You only mention what you need. If I needed the the created_on_timestamp I will just add createdOnTimestamp
(all the fields are camel cased by default). Lets query for only one article. Inside the article/schema.py
file, we have mentioned that to get specific articles the frontend needs to send ID. Lets see how that is done →
Now I only get one article and all the data related to that article that we mention.
If you’ve noticed, I cannot get data about the author from article. That’s because every article’s author is a User. And to get data about User we need to add a type class for it. That is pretty simple. Inside article/schema.py
add this →
Now I can query for the data related to author or a comment’s commenter.
That’s it for now. At the moment, we can query for data. If you want to modify the remaining data check these helpful articles →
If you find articles like this valuable and want to support this type of content, consider signing up to Medium, You will get unlimited access to all articles from thousands of authors. I appreciate your support. Made with ❤️ by Sk Soyeb Akhter.