Hire the author: Bijita K

Highly committed and reliable software developer with experience in Django.

Introduction

In this article, we’ll be discussing how to structure a GraphQL multipart form query on Postman. For this purpose, we’ll be creating the GraphQL API in a Django project. Tools/libraries used for structuring a GraphQL multipart form query:

  • Postman – It is an API platform for testing our multipart form query request.
  • graphene – It is a Python library for building GraphQL schemas/types fast and easily.
  • graphene-Django – It is a Django integration of graphene.
  • graphene-file-upload – It enables multi-part file uploading in our API.

Here is the link to code.

Glossary

Multipart/form-data: It is used in form elements with a file upload. Additionally, it means form data divides into multiple parts and sends it to the server.

API: The messenger that allows two applications to talk to each other and send data to each other.

Implementation

Step 1: Setting up the GraphQL API in the Django project for structuring a multipart form query

In the Django app we will set up a GraphQL API by following the steps given below:

Create a new model in models.py

from django.db import models
class Post(models.Model):
title = models.CharField(max_length=250)
photo = models.FileField()
caption = models.TextField()
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
def __str__(self) -> str:
return self.title
view raw models.py hosted with ❤ by GitHub

Additionally, install the libraries required for the project.

pip install graphene
pip install graphene-django
pip install graphene-file-upload

Also, we need to insert ‘graphene_django’ under INSTALLED_APPS inside settings.py.

Create a new file types.py inside the Django app

from graphene_django import DjangoObjectType
from .models import Post
class PostType(DjangoObjectType):
class Meta:
model = Post
fields = "__all__"
view raw types.py hosted with ❤ by GitHub

DjangoObjectType is used to change our Django object into a format that is known and can be used by GraphQL. We use this process for our model named ‘Post’ so that the data will be able to be used by GraphQL.

Create a new file query.py inside the Django app

import graphene
from graphene_django import DjangoListField
from .models import Post
from .types import PostType
class Query(graphene.ObjectType):
all_posts = DjangoListField(PostType)
def resolve_all_posts(root, info):
return Post.objects.all()
view raw query.py hosted with ❤ by GitHub

We are creating a query that can be used for reading the data from the database. However, we cannot edit data using a query only thus we need a mutation for the multipart form query.

Create a new file mutations.py inside the Django app

import graphene
from graphene_file_upload.scalars import Upload
from .models import Post
from .types import PostType
class CreatePostMutation(graphene.Mutation):
post = graphene.Field(PostType)
class Arguments:
title = graphene.String(required=True)
photo = Upload(required=True)
caption = graphene.String(required=True)
@classmethod
def mutate(cls, root, info, title, photo, caption):
post_ins = Post.objects.create(title=title, photo=photo, caption=caption)
return CreatePostMutation(post=post_ins)
class Mutation(graphene.ObjectType):
create_post = CreatePostMutation.Field()
view raw mutations.py hosted with ❤ by GitHub

We have created a mutation that will help us create a post with fields title, photo, and caption. Moreover, we have used the graphene_file_upload library to be able to upload the photo.

Create a new file schema.py inside your Django app

import graphene
from .query import Query
from .mutations import Mutation
schema = graphene.Schema(query=Query, mutation=Mutation)
view raw schema.py hosted with ❤ by GitHub

This file will define our GraphQL schema.

Edit the app’s urls.py file to be like the one given below.

from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from graphene_file_upload.django import FileUploadGraphQLView
from .schema import schema
urlpatterns = [
path('graphql/', csrf_exempt(FileUploadGraphQLView.as_view(graphiql=True, schema=schema)))
]
view raw urls.py hosted with ❤ by GitHub

Note: csrf_exempt shouldn’t be used for production and is currently used only for development purposes.

Step 2: Structuring the multipart form query on Postman

We will be structuring the multipart form in the following format.

Postman screenshot

As we can see above there are three main parameters. They are operations, map, and 0.

Operations: To explain, the value of query consists of the query mutation and we use the variable’s key-value pair to assign values except for the photo field.

{
"query": "mutation($title: String!, $photo: Upload!, $caption: String!){createPost(title: $title, photo: $photo, caption: $caption){post {id}}}",
"variables": {
"title": "New Post",
"photo": null,
"caption": "This is a new post"
}
}
view raw operations hosted with ❤ by GitHub

Map: Its value contains a mapping to the photo variable that was mentioned in operations.

{"0": ["variables.photo"]}

0: Its value contains the photo that needs to be uploaded.

Finally, the request is now ready to be sent. Consequently, its response should show that the post was created and its id will be returned. This completes the whole process of sending the data. We can also carry out this structure in other API platforms like Insomnia in a similar way as shown above. You can check out the whole project here.

Learning Tools

We can use the following links as learning tools for this project.

  1. https://docs.graphene-python.org/projects/django/en/latest/
  2. https://github.com/lmcgartland/graphene-file-upload

Learning Strategies

The graphene-Django documentation is good for understanding a lot of the concepts. Similarly, it also includes tutorials that will help to learn about this topic in more detail.

Furthermore, we can learn by observing the large-scale GraphQL Django implementation in the saelor project. This project is maintained well and therefore can be used as a good reference.

Reflective Analysis

The process of working on this project provided me with more clarity in terms of understanding the whole process of GraphQL implementation in Django. Furthermore, it helped me to learn more about multipart-form query structure and how we can send it using Postman.

Conclusions and Future Directions

In conclusion, photos can be uploaded to our application by using the method shown above since GraphQL in Django doesn’t have a built-in way to do that yet. We can extend this project to accept other file types as well. We can further add more endpoints so that this can be turned into a proper application. This project can also be extended further by creating a frontend. You can find the GitHub repository of this project here for a more detailed view.

You can try out creating the frontend for this using React. In fact, you can learn from the blogs How to create a Quiz app using React, Material UI & Heroku, and How to create a cryptocurrency app using React. Here is the code

Citations

Highly committed and reliable software developer with good experience in Django.

Hire the author: Bijita K