Create Backend GraphQL API

In the first part of the article, we created the Django project with an item app that includes our movie model.

In this part, we will create a simple API with GraphQL that will respond to queries that requested from our client-side app.

Step-1: Create an API App

Let’s create our second app that will be responsible for GraphQL API.

Step-2: Configure the URL Endpoints and Necessary Settings

Add URL endpoint that all the API requests will be done through.

Note: (graphiql=True) option is responsible for interactive GraphQL API browser. We will use it for manually querying the database.

You might also like:
Consuming REST APIs With React.js

Define the schema location for Graphene in the file of your Django project. SCHEMA location points to our schema that we will create in a moment.

Create a file in the gql directory.

Step-3: Define API Model and Query

Now, we should clearly define the API requests and its relevant type of data.

First, we will create an API model type and its resolvers that will be the interface of our previously defined movie model.

You can also define custom types with graphene.ObjectType that is not connected to any pre-defined Django-model.


When we create API-model, we first define API-model-fields with respect to our original movie model. There is no obligation to define all the field, but we will do. Also, you can write custom fields that are not defined before.

Let’s look at how our movie model fields and API-model fields are paired.

Movie model fields compared to API model fields


After the fields, we will define resolvers, which are responsible for the logic part. The second argument of resolvers is info argument which holds useful information like authentication or HTTP information.


Now we are going to write our queries. The client-side app will make their requests according to these queries. For the sake of simplicity, only two queries will be defined.

The movie_list query returns all the movies in the database.

The movie query returns only specific movie if slug of the URL matches any slug field of a movie.

The final code of file is here:

Writing API for backend is finished. Now, we can check it in the GraphQL interactive browser.

Step-3: Interactive GraphQL Playground

Please run the server and open in the browser and write this. You will see the response to this query.

Our second query has arguments. We can make the request like this:

then the response will be

We checked that our API is ready. This part of the tutorial is finished. You can stop the server.

Next, we will create a single page application with React. Then we make requests to our backend.

Further Reading

Integrating Spring Boot and React With Spring Security: Basic and JWT Authentication

Python Django Tutorial for Beginners

Source link

Write A Comment