GraphQL and MongoDB in Python 🐍

Published by Abhay Rastogi on

GraphQL is a Query language for dealing with your API. The best part is that it can fetch multiple API at ones with a single hit!

In Python, graphene library is used to work with GraphQL in Python for more details visit(https://graphene-python.org). so in this coding blog, we will see how we can connect with the MongoDB database and get the result of multiple queries with a single hit to sever.

Before writing any code we need to install python server for that I will use aiohttp framework. for more detail on aiohttp visit(https://aiohttp.readthedocs.io/en/stable/)

Its time to check aiohttp is running properly!

create a new python file with .py ..i.e filename.py

aiohttp(codeserachonline.com)

Run file python filename.py in terminal

open link in postman (http://localhost:8080/apitest)

As the server is setup properly now its time to create user collection in MongoDB.

user collection

Pip the following dependencies.

  • pip install graphene_mongo
  • pip install graphene

Models are required in GraphQL for binding data so create model.py

After creating models its time to create a schema name this file as api.py

Fetch all users

Fetch user by there type

http://localhost:8080/mongo?query=query { usertype( types : “admin”){ firstName lastName type } }
http://localhost:8080/mongo?query=query { usertype( types : “editor”){ firstName lastName type } }

Fetch all users and type admin at sametime

query { usertype( types : “admin”){ firstName lastName type } users{ firstName lastName } }


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *