PyGrunn: unifying django APIs through GraphQL - Jeroen Stoker

Tags: pygrunn, python

(One of my summaries of the 2024 Dutch PyGrunn python&friends conference in Groningen, NL).

He works on a big monolythical django application. It started with one regular django app. Then a second app was added. And a third one. The UI was templates with a bit of javascript/jquery. Then a REST api was added with djangorestframework and a single page app in backbone or react. Then another rest api was added. With another rest api library.

In the end, it becomes quite messy. Lots of different APIs. Perhaps one has a certain attribute and another version doesn’t have it. And the documentation is probably spread all over the place.

REST APIs have problems of their own. Overfetching and underfetching are the most common. Underfetching is when you have to do multiple requests to get the info you need. Overfetching is when you get a big blob of data and only need a little part of it.

Then…. a new frontend app had to be build. He wanted to spend less time on defining endpoionts/serializers. And to re-use existing functionality as much as possible.

At a previous pygrunn, was suggested. What is graphql?

  • Query language for APIs.

  • Defined with a strongly typed schema.

  • You query for only the data you need. This also means you get predictable results: exactly what you want, based on the schema. You can query for items and subitems, reducing the underfetching problem of REST APIs.

There were a few options to start with graphql. Hasura (haskell), postgraphile (typescriot), apollo, graphene. Graphene uses python, so he chose that.

Graphene provides Fields to map python types to GraphQL types. graphene_django helps you provide those mappings for django models, in this way it looks a bit like djangorestframework’s serializers. He puts the mappings in a next to the in the existing apps.

He then demoed graphql. There are apps to browse a graphql API and to interactively construct queries and look at the results.

Some feedback they got after the initial implementation:

  • You might have accidentally worked around security that was present in the old REST API views. The solution is to put the security into the database layer. Perhaps row level security.

  • Speed might be a problem. Graphene out-of-the-box experience can be really slow for certain kinds of queries. A graphene component called “data loaders” was the solution for them.

TIP: look at , it has a steep learning curve, but it is worth the effort.

I have two other summaries you might want to look at: logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):