
Adding GraphQL to DjangoCMS allows exposing data through an api in a structured way. This can be used to build a cms frontend in other technologies or integrate a cms with more applications.
Install package ‘graphene-django’ from pip. This will also install:
Package graphene enables main functionality of graphql and graphene-django allows using django models as nodes in graphql.
In the settings.py add ‘graphene_django’ to INSTALLED_APPS and add configuration for graphene:
Inside urls.py add
Next step is to define a schema. Create a file schema.py and import DjangoObjectType.
The schema variable is the one that is pointed to in the settings file.
Next step is to create an object that can be returned by query. For django models you have to inherit from DjangoObjectType. Class names in graphql usually end with Type on Node. Inside Meta class configure what django model will use. If a model uses parler for translation of fields then for every translated field you have to manually define a type and source for graphene fields.
Next step is to add a function that can populate return types with data. For that you have to add a resolve_* function inside a Query class. Because the person class defines a Node interface, therefore all object ids will be encoded with base64 in the form model:ID. To get id back use from_global_id function.
Go to localhost/graphql interactive console and run:
To query for specific person use:
To add “searching” and “pagination” to people query add two new input parameters for query:
to get the first 5 email addresses.
To add a mutation that can modify an object create a new class:
Create a new mutations class:
Graphene is a great library that can help expose endpoints with a relatively little configuration. Adding new endpoints is simple when you get a grasp of graphene code conventions. This allows rapid development of APIs that expose data in logical and easy to follow ways.
Building something similar or facing technical challenges? We've been there.
Let's talk — no sales pitch, just honest engineering advice.
Did You Know? 10 MusicTech Facts That Will Surprise You
A collection of fascinating facts about music technology, standards, and innovations that shape how we create, share, and experience music. Part 2 of an ongoing series.
Does Zappa make it super easy?
The article provides step-by-step instructions for the easy implementation of the application in Zappa framework based on Python.