Introduction to Django and GraphQL by Patrick Arminio
Transcript
By Patrick Arminio, Speaker 2, Speaker 3. From DjangoCon US 2018. Published November 8, 2018.
Watch the video Markdown version 3,956 words · auto-generated · en
Summary
GraphQL lets clients request exactly the data they need through a single typed endpoint, avoiding REST’s common overfetching, underfetching, and proliferation of custom endpoints. Patrick Arminio shows how to build GraphQL APIs with Django and Graphene, including object types from Django models, queries, mutations, introspection, and an early integration with Django Channels for subscriptions. He also covers authentication, field-level permissions, query-depth and cost limits, timeouts, static queries, and caching concerns, arguing that GraphQL can improve both developer workflow and client performance while noting that Python’s Graphene ecosystem still needs work.
Transcript
Automatically transcribed, so expect mistakes in names and technical terms. Filler words are removed.
0:16 Introduction and Web Evolution
Patrick Arminio
So hi everyone. My name is Patrick. I'm currently HR person at Python Italy and I currently live in London and I'm interested in both back-end and front end. I've been using Django for about 10 years now and doing frontend for about more or less the same time. And you can find me at Spartan9 online if you want to tweet me or if you have any question. Today I'm gonna talk about a technology that I've been using. over the past two years I think more or less. And one of the reasons why I try to experiment with technologies because I really want to improve my workflow. I want to try to find new technology that can speed up my developer experience and also improve the user experience for the user of my the apps I build or the website I do So before digging into
what GraphQL is, I'm gonna do like a small digression on the how the web used to be what the web is now. So it used to be like something like A simple collection of documents where you had a single server and you had like a list of documents where the user could navigate between them using links. And usually these documents were just HTML, CSS, and maybe some JavaScript for like some animation. But over time the web has changed as we all know and the other requirements have changed as well. So for example, we could have something like different data sources and one single backend that would handle this data and then send the data to all these clients that we can have like smartwatches, phones, desktop devices and you will free just
1:50 REST API Limitations
Patrick Arminio
in night. these days. So one of the ways we used to communicate between a client and a backend we used to use APIs and more specifically using RAS APIs. If you're not familiar with REST API, it basically says that your API is a collection of resources and each resource has its own endpoint and you would do use HCP verbs to do operation on those resources like get, post, delete, and patch. The problem is that REST is not perfect. It's actually it's not a standard as well, so everyone is doing it a little bit differently. One of the issues that I usually had is that you have to do too many API calls if you don't fetch data. So let's suppose that we have this simple API that's returning a user
data So let's say the returns a user with their name, a list of friends, an avatar. This is nice. We are using links so we can fetch data for all the other users. The problem is if I'm building an application where I need to show all this data in one single screen. I need to do an additional two requests in this case. So one request for each user. And this is a waste of bandwidth for the user and also it's not easy to implement in the front end. So one solution would be to create another endpoint where you can do user with friends and then you get something like this where you have the friends expanded The problem is that you might need also the images of those users in another application, so you might end up doing more and more endpoints for
all your different use cases. especially if you wanna do for example light version of your application. And this over time it gets really, really big. And for example Coursera at some point had like a thousand different REST endpoints that they had to maintain a doc document. And I think I think we can if we can oops no. If we can reduce this number of endpoints that we have to document this better. Another issue is that we have too much data when we send information to the client. So for example, instead of building the API with different endpoints, we could send just one single API where you return all the data. That's possible to have.
The problem with this one is that if I'm building a screen that only needs, for example, the username, we're basically wasting bandwidth and CPU resources because we're sending data that's not needed to the client. So can we can we do better? We could extend REST. The problem, as I said, is not a standard. So everyone is doing things differently, which means that we need to document. or the NAC extension that we built, for example, we could do I don't know get parameter to expand some fields. We can use headers to say oh this is a client, a mobile client, so send images that are smaller and so on So for some of this reason GraphCal was created. GraphCal solves some of some of those issues quite qua in a
4:55 GraphQL Fundamentals
Patrick Arminio
pretty nice way. GraphQL was created by Facebook in about 2012 and it's been open source in 2015. So it's it's been used in production for a bit and also it's been used by loads of companies they say like Twitter, GitHub, Coursera and so on. So GraphQL is a specification and it's defined as a query language for the APIs. That means that basically we can send a document to our GraphQL API and then we get back a result. So basically it's the client that is in charge of saying what the data is needed for their application. A difference with REST APIs is that you only have one single HCP endpoint, which
usually is slash GraphQL, and you would send a post request with a document. saying oh this is the data I need. And a document would look something more or less like this. So in this case we are saying oh I need the user, their name, their email and their list of friends with the name And when we send this request, as soon as if we have data on the back end, we get something like this back, which is basically what we asked for. If we change the document, we can we basically are changing the response as well. Another interesting thing of GraphicQL is that you have types. So every field in your API is typed. You have two different types. One is One is scolars, which are basically like base types like integer, float, string, and so on. You can also define custom types if you need to define
like date time and so on. And then you have object types, which are basically a collection of types. So you have different fields where you can either have another scolar type or another object type For example, in our previous API we can have a type of user, they have name, an email, and a list of friends, and then you have a type of friend which is a which only has a name. Another cool thing I think is the introspection. So every GraphQL API by default returns a schema. So basically you can get all the fields that you have on this in this API. This allows to use tools like Graphicode to basically introspect the API without actually having to read the code or remembering everything. And I'm gonna show you a quick demo of this later.
For example, in this case we are getting the information about this API without having to read the documentation. So I only show you how to show you how to do queries. Of course, we want to do multiple operations. And in Graphical you have three main operations which are query mutations and substitute subscriptions. subscription. Queer allows you to get data from the back end. Mutation allows you to do any operation with side effects like creating data or sending emails. else. And then you have subscription, which allows you to subscribe to events on the server for example when something changes. This is a document that you send to do a query and since query is like
It's a common operation. This is like the short version of doing a query. The actual syntax looks like this, which basically you have the first token is the operation type then there is a operation name which is basically used only for debugging then you can have parameters and something interesting of this GraphQL is also that you can have parameters for like nested fields. So for example in this case you can limit the number of friends in the response. And then same for mutation, you have the type, name of the operation, and optional parameters. And substitution works the same. So syntax is quite simple and easy to use. So this is really nice.
8:43 Graphene and Django Integration
Patrick Arminio
We can we can we can use a bit Python using this library called GraphenePython. And I think it's the only library available so far. for GraphQL. It's easy to install just to prep install graphene and then to create a small hello world you can create a class called query where you define the fields. And in this case we are just defining hello field, which is returning a string in this case. And then you need to specify the resolver function. Resolver functions are basically the methods that are being called when you request a field. So in this case when we request the hello field, the resolve hello is going to be called. And it's gonna return only high Django conference now. And also you can execute them directly, but usually you would have a like a Django
view or like a HCP call to execute this schema instead of executing indirectly. And yes, there is also an extension for Django. This allows to use all the Django features like forms and models and so on. It's easy to install need to add to the installer app so you can use the views and then you need to specify the path to the schema so the Django view is able to fetch the schema. You add the view to the file to the URLs and you can also enable the enable the ID graphical. And then it's quite easy. You can basically use the models to create the graphical types without typing again the older fields that you have. And then in the resolver function you can just return
10:15 Building a Polls API
Patrick Arminio
a query set which is basically gonna be converted by graphene to graphical types. That was quite quick. Let's let's create a simple API and This is based on the Django pools application more or less. Let's say that we have two models. One is pool, which is only a question, and then there is a choice which is linked to a pool. It's got a choice text and Number of roots. So the first thing we want to do is to create the object types, which are basically the types for GraphQL. Those types are gonna be shown in the in your API. So using jung object type and it's quite easy to create those types because it it's basically up to the this base class to create all these the fields that are needed for the models.
You can also you can also extend add additional fields and additional resolvers if you need to Then the first query we can do is the to list all the pools and is the document that we can send to the backend to fetch all the pools will look something like this. So you we fetch the field called pool, then we fetch the question for this pool and then the choice set. And in Python will look something like this. So we have a query and the field is a list of pool types and then there is a resolver function that's returning all the pools from the database. Then we can do a query for a single post. As I said, in GraphQL we can pass arguments to each field.
So in this case, for example, we want to fetch the pool with ID, ABC. And we can do it like this. And the rest is similar to the previous one. The only difference that the field name is pull singular and accept an argument In Python looks like this, we define a graphene field, and then we pass the list of arguments. In this case just ID, which is a typo graphine. id and then in the resolver function we also get this parameter that we return a pool object then for the mutation we can create one that allows you allows us to create a pool. So the document that we can send looks like this. Basically it's like a function that accepts a question and a list of choices. And then we get back the
pull object. And in Python will look something like this. We need to extend the Graphene mutation, define the fields that this mutation is returning, and then the list of arguments. And then we need to create a mutation mutated function that it's basically if you use forms it's like the save in a in a Django form, then gets all the arguments and then you can create the pool duck. So let's quickly test it Okay. So I have this fine, it's not showing. Cool. Should be
13:16 API Demonstration
Patrick Arminio
So I already have an instance of Django running with this backend code. And so let's say I want to fetch just a list of pools with the question text. I can easily do like this. So basically every time I need to do like an API call, I can just send the document that I need with the structure I need back and I can fetch it like this. And if you wanna get the choice set, you can just do something like this. And then I can back I can get back the list of choices for this pool. There's also the ability to get like a single pool as I showed you.
So in this case we are passing an argument with ID one and then we get the data for just that single pool and if you wanna do if you wanna create a new a new pool we can use the mutation create pool Then but they are type also it's since everything is type the ID is telling me that there are some errors. So in this case it's telling me that I probably meant choices. And when I run this mutation, it's basically gonna create the pool on the back
14:51 Subscriptions and Django Integrations
Patrick Arminio
and it's also gonna return me return that to me, which is quite nice. Also like a quick demo I wanted to show you. There is support for Django channels, it's still not much of yet, but you basically can have a subscription like this in this case. So basically every time a pool is updated the number of votes is gonna update in real time. So for I have a vote mutation where basically I can just send a vote to the to this pool. So every time I click this it's gonna update in both the pages. So the on the left side basically we get the response from the back end, but on the right side we have a web socket connection
Running with Django channels that's receiving the updates in real time. So it's quite handy. The only issue is I think I find that's still not measure yet. But hopefully soon we're gonna have gonna have a nicer way to use Django channels with your fin but it can be done. So There's also integration with RAS framework and with Django forms. So basically you can reuse the forms that you have and the serializers that you have to create mutation. The problem that this I would say it's in beta. It's no i it works but doesn't have all the features that we need. And I'm gonna be working on this during the sprints if you wanna help and see
16:23 Authentication and Query Security
Patrick Arminio
how actually works. So that that's cool. This is it's really nice at least for my opinion. Problem is like it's a new technology especially in the Python world And there are some things that we need to keep in mind, especially with security. One of the most asked question on GitHub and on SAC Overflow is how to do authentication. And there are three ways to do to do authentication. One is to use Django session and this works really well if you have an API that only works on your website so you don't have any mobile applications. The others the other way is to use headers like you do with a REST API so send like a token and the last one is to use parameters.
So since you can add arguments to all the fields that you have, you can for example send the token as an argument for a mutation. And this might work in some cases when you only have one mutation that needs authentication. So it's up to your requirements So another thing is permission. So like if you if you've been used to Django Ras framework, it's really easy to add permission to all the resources that you have. Unfortunately there is no builtkin features in Graphene yet But something nice I really want to work on is having permissions at on the field level. So for example, you can have an API where you have a user and the email only it's only shown if the user is the current user or if
a super user. user like git GitHub is doing something like that where they have a single graphical API that's being used also for like public access but also private access. And they have some fields are only available to the private API. But they only have one code base. Also it's really easy to build malicious queries because we are giving loads of power to the front end. So you can build something like this and imagine that this goes on and on. So you basically can do a query that takes a lot of time and it's gonna it's easy to someone to dose your server I guess. Some strategies to fix those issues, for example, could be having timeouts.
So you could say if a query takes more than one second, you can discard it because one second is already too much for a user and it might not terminate anyway. You can also do limits on the nesting which basically says oh if the if the user is requesting a field that's I don't know four levels deep. I'm not gonna do this query because it shouldn't be happening. They can also have a query cost. Basically you can add the score to each field and calculate the cost of query So if you have nested fields you can increment the cost based on the number of fields that you have. And this basically allows you to say, oh I wanna only wanna run query that are less expensive, I don't know, the
fifty, which is a made up number. And you can also do static queries. It's something that there are a few companies doing. I think Instagram is doing it. Basically Since they have control of the old pipeline, basically they can build a list of queries they're doing on the on their application and basically save it on the back end. in either in the database or on files. And basically the b the front end is gonna send, instead of sending a JSON document is gonna send an ID that corresponds to a query. And this allows you to also fix an issue that it's that we have with caching, which is basically we are doing post request and It's as you know, PostRequest is not easy to cache, so you need to either do the back-end cache or
20:14 GraphQL Adoption and Future Work
Patrick Arminio
client cache. So with that said, I one of the reason I want to give this talk is because I want to see more people using GraphQL in Python and also wanna see this library improve a lot because it's It's nice but it's not there yet. I think there is loads of room for infographic from this library. And also I think GraphQL is amazing using technology especially for like developers when you have to work with front-end people and people working on I can different clients and also it's good for the user because we are not wasting the user bandwidth. Imagine if you have like a s like lower hand phone or if you have a connection that's really slow. You only send in the data that the client needs
and it should be performant. So I'm gonna be at the sprints if you want to work on graphene. And thank you.
21:14 Questions
Speaker 2
So usually when you develop a library like that, you have like a problem that it solves. Can you kind of say in general what this solves?
Patrick Arminio
Oh yeah, so as I said solves most of the issues that we you have might have with REST API. So basically overfetching and underfetching of the data and also writing documentation. In my experience when I built graphical API I said didn't really have to write any documentation because the people working on the front end, we just read using the graphical IDE to fetch the date the information about the API so I didn't really have to explain to them but this is the query that you need to do and also every time they had to do like a new screen on the application. I didn't have to build another endpoint because basically they can change the response that can get sent the to
Speaker 3
And how does this look from the client side from the JavaScript? How does you usually create these queries that are
Patrick Arminio
so there are different ways you can go vanilla, so basically just some Sending an HTTP request with the it's it's basically it's a JSON with the query. Or you can use loads of there are a few frameworks. There is Apollo and Relay. Apollo is like the community one made by it's I think now it's a company but it's like all open source and there there's also relay that's being made by Facebook. I really u I use Apollo and mainly because it works with different frameworks. You can use it with VR, Angular, V. js, and so on. But we can chat later if you want to have a look and how it works because it's another talk. Thank you.