Developing GraphQL API in Django using Graphene
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Subtitle |
| |
Title of Series | ||
Number of Parts | 130 | |
Author | ||
License | CC Attribution - NonCommercial - ShareAlike 3.0 Unported: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this | |
Identifiers | 10.5446/50085 (DOI) | |
Publisher | ||
Release Date | ||
Language |
Content Metadata
Subject Area | ||
Genre | ||
Abstract |
|
EuroPython 2020124 / 130
2
4
7
8
13
16
21
23
25
26
27
30
33
36
39
46
50
53
54
56
60
61
62
65
68
73
82
85
86
95
100
101
102
106
108
109
113
118
119
120
125
00:00
TouchscreenWhiteboardQuicksortCircleInheritance (object-oriented programming)Goodness of fitMeeting/Interview
00:46
Software developerComputer virusStudent's t-testPoint (geometry)View (database)BuildingLogicInterface (computing)Communications protocolDependent and independent variablesClient (computing)Server (computing)CodeOpen sourceQuery languagePhysical systemFormal languageProduct (business)Variable (mathematics)Exclusive orAreaConnected spaceBuildingGoodness of fitArithmetic meanFunctional (mathematics)Object (grammar)Labour Party (Malta)Bit rateText editorSpacetimeNichtlineares GleichungssystemDivision (mathematics)Shape (magazine)Open sourceNumberSoftware testingState of matterType theoryCartesian coordinate systemComplete metric spaceStudent's t-testPoint (geometry)CASE <Informatik>PlanningGroup actionEntropie <Informationstheorie>Profil (magazine)GodPay televisionRegulator geneForcing (mathematics)QuicksortIdentity managementOperator (mathematics)Numbering schemeForm (programming)Game theoryInformationDemosceneFormal languageMedical imagingPhysical systemRaw image formatRoutingData structureChainDecision theoryPhysical lawDifferent (Kate Ryan album)Streaming mediaScaling (geometry)Food energyMachine visionSoftwareWhiteboardData storage deviceCoefficient of determinationShift operatorProduct (business)LogicServer (computing)Variable (mathematics)Query languageField (computer science)Client (computing)Total S.A.Electronic mailing listMathematicsFront and back endsResultantCommunications protocolSoftware developerEmailCodeInteractive televisionReal-time operating systemScalar fieldEvent horizon2 (number)AuthenticationMultiplicationExterior algebraDatabaseDependent and independent variablesTrailModal logicRepresentational state transferData typeView (database)Graph (mathematics)Core dumpComputer animation
09:56
Sanitary sewerCodeBuildingIntegrated development environmentType theoryObject (grammar)Graph (mathematics)Query languageScalar fieldConvex hullServer (computing)AuthenticationMobile appToken ringData structureWritingQuery languageCodeField (computer science)Type theoryEndliche ModelltheorieMathematicsComputer fileServer (computing)Block (periodic table)Theory of relativityNumberClient (computing)BuildingProjective planeObject (grammar)Operator (mathematics)2 (number)Product (business)InformationLibrary (computing)Integrated development environmentConnected spaceReal-time operating systemOnline chatScalar fieldElectronic mailing listAreaData structureDatabaseService (economics)Positional notationEvent horizonResolvent formalismMachine codeArithmetic meanRight angleFunctional (mathematics)Lattice (order)Inheritance (object-oriented programming)Software repositoryAuthenticationQuarkFront and back endsMobile appRootString (computer science)DampingIntegerMetadataData typeVariable (mathematics)Dependent and independent variablesSocial classPrototypeSet (mathematics)LoginRepository (publishing)Parameter (computer programming)LogicNumbering schemeDimensional analysisTheoryThermal radiationCondition numberAngleProcess (computing)GodGame theoryExecution unitPeer-to-peerMereologyOpen setLevel (video gaming)ResultantView (database)Price indexGradientBoss CorporationDecision theoryLogic gateGraph coloringUrinary bladderCore dumpHypermediaPhysical lawMenu (computing)Labour Party (Malta)Form (programming)Group actionObservational studyWeb pageWater vaporMusical ensembleBridging (networking)Equaliser (mathematics)Network topologyPoint (geometry)Goodness of fit
19:06
Query languageObject (grammar)Type theoryWritingView (database)AuthenticationLoginToken ringEmailDisk read-and-write headWebsiteRepository (publishing)MaizeOpen sourceBuildingComputer fileQuery languageLine (geometry)Client (computing)AuthorizationType theoryRight angleString (computer science)MiddlewareSlide ruleDependent and independent variablesSoftware repositoryBoilerplate (text)Complete metric spaceCodeField (computer science)EmailFunction (mathematics)AuthenticationObject (grammar)Patch (Unix)TouchscreenSpacetimeParameter (computer programming)Variable (mathematics)Product (business)Graph (mathematics)View (database)Server (computing)Software developerGraph (mathematics)Functional (mathematics)Hydraulic jumpProjective planeToken ringLoginResolvent formalismSocial classFront and back endsWebsitePhysical systemOperator (mathematics)DampingRow (database)LogicData typeWeb browserError messageRepresentational state transferCache (computing)Mechanism designComplex (psychology)Multiplication signVisualization (computer graphics)Point (geometry)CASE <Informatik>Machine visionPrice indexCondition numberInternet forumAdditionGoogolOpen setExecution unitText editorFood energyDesign of experimentsDifferent (Kate Ryan album)Inequality (mathematics)Arithmetic meanGame theoryGroup actionTwitterQuicksortECosObservational studyPlanningResultantProcess (computing)WordLevel (video gaming)Set (mathematics)Bridging (networking)Envelope (mathematics)Term (mathematics)SequelCausality
28:15
Graph (mathematics)AerodynamicsResolvent formalismSocial classParameter (computer programming)Field (computer science)Object (grammar)Multiplication signCodeOptimization problemPhysical systemSingle-precision floating-point formatQuery languageElectric generatorType theoryRight angleRepresentational state transferCache (computing)Machine visionNumbering schemeComputer programmingArithmetic meanRow (database)InternetworkingPoint (geometry)TunisSystem callBuildingSequelComputer animationMeeting/Interview
Transcript: English(auto-generated)
00:07
So, Nisar is going to be talking about how to develop a GraphQL API in Django using graphm. That's super interesting.
00:21
Okay. So, the audience is in yours. I can see your screen. That's perfect. So, you are ready to go. Good luck. Thank you. So, just a reminder, if anyone has a question during the talk, you can click in the Q&A, ask the question, and then I'm going to ask those questions to Nisar at the end of the talk. Okay? Good luck. Yeah. Thank you.
00:47
Yeah. So, hi, everyone. Today, I'll be talking about developing GraphQL APIs in Django using graphm. So, first of all, let me introduce myself. I am Nisar Ikshay from India. I am currently an undergrad CS student. I'm also the software developer at
01:06
twitozi product, and I am the co-creator of courses around product. So, first of all, let's talk about the main points of the today's talk, right? So, like, I'll be starting with the general views on the APIs. Then I'll move, so, like,
01:25
then I'll shift towards the RESTful APIs and the GraphQL APIs. Then I'll discuss a few concepts of the GraphQL, and then we'll implement the GraphQL APIs in Django using graphing. Now, basically, in today's age, most of the applications use APIs in the
01:45
backend, right? And then they connect them with different end. Now, the core logic is written in a function, which could be called when a particular API is called by a client, and then the data is sent to the client from the server. So, basically, what happens
02:02
that a client called the API backend function gets executed and the client gets the data, right? Now, some of the popular API protocols which are currently used are so pressed and there are a few more too. Now, let's talk about, like, this RESTful API.
02:21
RESTful APIs have particular methods such as get, put, post, get, put, post, and delete, right? So, the developer needs to build different endpoints according to the different requirements, such as if a developer wants to fetch the data from the server, then a get method API needs to be developed, and if there needs some modification
02:43
of the server, then put, post, or delete API needs to be developed, right? So, here are the some endpoints of the REST APIs, right? Now, like, whenever this API is called, a piece of code gets executed and the response is sent to the client, right? And also in REST,
03:04
in some of the APIs, you need to pass some headers mentioning the type of the response, such as JSON or like anything, and also, if you want to secure the API, then, so, like, you need to pass some specific token for the authentication.
03:21
Now, what can be the problems faced while building RESTful APIs? First thing is there are multiple number of endpoints which are developed in REST for a single application. Now, this would require a very good amount of documentation or otherwise it may occur some problem at some time. The second is over fetching. Now, what over fetching means? It means the
03:43
client gets the unnecessary data which is not required in that particular function or feature. Now, for example, just imagine if you want to display all speakers name and you have one endpoint name slash speakers which returns JSON objects which includes profiles of all the users,
04:02
which means it includes all the data of a particular user. Now, the client only means the name of the speaker and the other data is not needed for that particular feature. So, this is known as over fetching and the under fetching. Now, the under fetching means a client is not receiving the complete required data for a particular function and so client needs to call
04:24
multiple endpoints like the client first get the data from the first request and then a second request needs to be made for the required data. So, what could be the alternative of REST and what can be used? So, that's GraphQL. But yes, there are also some cases where REST
04:43
is more preferred over GraphQL. Basically, GraphQL is open source and it's a query based language. So, like you just need to write the queries for that and it uses the schema based system and it also has like good community support. So, now why GraphQL basically? Now,
05:05
as its code, it's a language for querying the database from the client-side applications, which means the client needs to request whichever data is required at its side and due to this, it improves the client-server interaction by it's enabling the former to make precise data
05:24
request and obtain no more, no less, but exactly the data which is needed to client for a functionality. And the other thing is just a single endpoint. There's only a one post endpoint,
05:42
no other endpoints, no over-fetching, no under-fetching as the client gets the data which is required only and the other thing is auto-generation of API documentation is done while you are building the GraphQL APIs, which means if you write a code, then the documentation of that code is directly done in the GraphQL like you. Now, let's learn about the GraphQL.
06:10
We'll learn a few concepts about schema, mutations, queries, and the subscriptions. So, first of all, schema. Now, basically schema is the object type or like we can say that
06:22
we can find that which data is available in the API, which means we can say that the schema holds the complete definition of the API or the complete structure to be more precise, right? So, here my schema name is product and I have various fields such as product ID, name, category,
06:40
price, and this, right? So, these are the fields or we can also say it as variables, right? And this ID, string, float, these are the built-in scalar types, which we can also say as the data types, right? Now, this exclamation mark, it means this field is like, so like this field is, so basically this field is required or this field is a necessary
07:06
field, right? And like we can also build our own scalar types such as list of an object types or something like that, right? So, basically and also here by using this schema, it's easy to find the usages of a particular type of data type that which data type is used more,
07:25
and also we can track the usages of schema by using few tools such as which schema is used more and which query is used more. The next is mutational. So, mutation are used for changing
07:40
or so like basically for updating or like changing the data to the server, right? So, now here I have mentioned one mutation name it's add product and the required variables which are needed to add a product into the server are passed into this add product mutation. Now,
08:03
here I have mentioned the fields which I'm expecting back from the server on the successful operations. So, these are the fields which I'm expecting back from the server on the successful operation. Now, here it is written the same thing. So, here it is written the same thing which the server has stored but you can also return some other objects according to your needs.
08:24
For example, by adding a product you want to send the total list of products to the client then also it could be done by making some of the changes. So, here I have shown this mutation
08:41
using the query variables. So, we can also declare these query variables and these query variables are passed to the mutation and then they are passed further to the add product. Now query, query is basically used for fetching data from the server, right? So, here you can see
09:01
that the query has exactly the same shape as the result. So, this is the result and the query has the same shape as the result, right? So, this is the benefit of GraphQL as we know that we will get back what we expected and the server knows exactly what fields the client is asking for. So, here I have asked for only the five fields instead of the complete object
09:24
and that's why I'm getting the response from the server of only five fields from the query. Subscription. So, subscription is a real-time connection to the server. So, it's a real-time
09:41
connection between client and the server which means a client subscribes to an event and then the server gives the data to the client when an event is occurred. Here I have subscription on this add product mutation which means here by getting the subscription query to the server,
10:01
the client is connected with the server in real time and the connection is established and now whenever the server performs this particular mutation of adding a product then server sends this information about the added product to the client back at the same time. Now, this can be used for real-time chat services or OTP and some few features too, right? Here
10:24
actually I have mentioned the example of notation but like you can subscribe queries also and like few other events too. Now, there are multiple like tools or libraries for building the GraphQL APIs in Python. I am particularly using Graphene library as it's
10:44
convenient to me. Now, Graphene uses the code first approach. Now, what is code first approach? The code first approach means we start by coding the resolvers or we start by coding the APIs and from the code we get this schema generated as a byproduct. That means we'll still have
11:04
a schema but instead of manually created it is created by running our API codes while the schema first approach which is used by area then schema first approach indicates means like we need to first define the complete schema and according to that schema we need to
11:26
develop the APIs and the API structures and the restriction should be matched to the schema, right? So, it's not that schema first approach is better than code first or code first is better than schema first. It's just a matter of convenience. So, now let's start building the
11:46
GraphQL APIs in Django, right? So, we'll be using Django, Graphene and the PostgreSQL as our database. So, these are the few steps for building the environment. So, I have set up a Django project named project or then so like you have to install this Graphene. So, like
12:11
I am using Graphene Django is because it provides Django object types. Now why Django object types are required, right? So, if I want to build a schema which is equivalent which is similar
12:24
to my Django model, right? So, suppose I have 10 fields in my Django model and I want that all 10 fields to the GraphQL schema then basically using this Django object type I can map that Django object into a GraphQL object or into a GraphQL schema or so like directly and that's
12:46
why Django object types are very useful and then also you need to make some settings like some changes for setting up the PostgreSQL. You need to also add this Graphene underscore Django in your install lab and this code snippet into a settings.py file. This project is
13:05
your project name of the Django. Now, let's understand a few concepts of Graphene. So, first one is the object type. Now, the object type is a block or we can say it as
13:21
basically a mediator which is used for defining the relations between my fields and my schema which means here. So, basically I'll be having a few number of fields in my product model. Now, I need to define a relation between these fields and my GraphQL schema
13:41
and for that this object type is used for defining the relation between my schema and my fields which are required in that schema. Now, how to build schema? So, basically schema is created by supplying the object type of each operation which means that the
14:02
of like relation which we have defined between my fields and the schema that needs to be passed for creating a schema. Now, schema can be built in two ways in Django. First is using this Django object type and the second is we can explicitly mention. Now, let's have a look on
14:24
building schema using Django object type. So, here what is happening that I like suppose I have 10 fields in my product model and I want to map all the 10 fields into my GraphQL schema. So, for that you can use this code snippet like you just need
14:44
to pass a Django object type into and so like middle of class and then this prototype needs to be passed to the query class and your GraphQL schema so like and your GraphQL schema is generated and if you want to mention the explicit fields suppose you want to only
15:02
mention only the four fields in your GraphQL schema then you can just manually add these fields and you can just assign the variables and then the schema of only these four variables will be generated instead of a complete model. Resolvers. Now, basically this resolver is a method
15:23
which will resolve the query of a particular schema which means here I have two schemas which is login and users and I have two functions which is resolve underscore users and resolve underscore login. So, whenever a request will be made for a login schema let's say
15:43
then the resolver function of the login schema will be called and this like business logic will be executed and the client will get the response like whichever is needed right. So, resolver method is used for resolving the queries of a particular schema and make sure
16:06
that the name of the resolver function it should be resolved underscore your schema name which is your login and it's your login too. Now, there are three main parameters of the resolvers. One is parent info and quarks. Now, parent is basically it's the parent
16:24
of the current root which means here I have a particular query which is a join query right and so now here the parent of repository is repo right so that repo will be passed as a parent and in info now the info variable contains some meta information about the user authentication
16:44
and like something like that and in quarks basically carries the graphical arguments such as suppose when you are so suppose when you you are executing a query which uses the variables then that variables are passed in the quarks.
17:01
Scalars now basically scalars are nothing but just like the data types right so it's a string float or integer id so like so basically cracking towards many inbuilt scalar types but also you can build your own scalar type such as like just create a schema of that
17:23
data type and just reference that schema into a particular schema and pass it as an array so you can build your own scalar such as a list of objects or areas or something like that so it can be built according to the requirements. Now we'll be looking over the
17:43
code snippets for queries mutations pagination and authentication pagination is basically sending a particular data or a particular bunch of data to the client instead of sending the complete data and the authentication is for securing the backend APIs so here is my
18:03
file structure I have made two jeng works one is e-commerce and one is users and I have defined a file name schema.py in which I'll be writing all the queries and all the mutations of e-commerce so like muted app and here is schema.py file in user so
18:22
that you can build a file with any user so like with any name but in the last this all files needs to be mapped to a schema.py file of your main project so that you need to take care of so let's see for writing the queries right so what's the steps are for writing queries first
18:45
of all you need to mention your schema which is done in your products schema right and I am building this by passing the product type and this product type is using Django object type which means all the fields of the models will be mapped to a GraphQL schema right
19:01
so after mentioning your schema like you need to build a resolver function which will resolve your query so here is my resolver function and in this I am passing a product name so like if you want to pass any variables from your query then you can pass like this here I
19:20
have so like mentioned here and so like it's a string so I need to so like also mention that it's a string and then this variable is passed to the resolver so like this resolver function and then this variable is used into your logic and then the appropriate output is written
19:42
back to the client which is required right so these are the concept used for building a particular query now writing mutations for mutations basically you need few variables right for a particular object which needs to build an object or which needs to be in the class right
20:02
so for that I have so it's the same like here I have mentioned add product schema by Django object type then I have one class named argument now in this arguments class I need to define all the fields which are required for their particular mutations
20:21
along with defining that particular data type which is here string float and I need to also mention which is required by making record is equal to true now all these variables are passed to a muted function and now inside the muted function you need to write your business logic or saving the object which I have done here this is production and I am building my
20:44
product model here and then I am just returning the product which is saved on the server but you can return yeah so like basically you can return whatever you want it's not just only the sealed product you can also return a complete list of products
21:02
or you can also like return something else so it's according to the requirements it's not necessary that you just return the product which is saved now by adding this patch into your urls.py file
21:21
and by hitting this localhost slash graphql so this particular endpoint into a web browser you'll be able to see this graph iql view screen right so basically here is a space where you can write your graphql queries or mutations and here you'll be getting your server responses
21:42
and on the extreme right-hand side this is the apa documentation which graphql provides which may and this documentation also has all the fields which are required for a particular mutation and the response which will which the client will get is mentioned here so if a
22:02
developer has developed a mutation then the front-end developers just need to pull the code and just need to run that and they will be able to see all the mutations and the parameters which are required as well as the response which will be so like the response which will be given to the client now for pagination for pagination uh it's same as uh we are fetching
22:26
the data from the server that means uh we need to build a query so i will build a query in a similar way only but i have introduced two variables one is first and second is jump right and then i'm uh using the concept of python slicing now what is python slicing and
22:43
how it can be used for pagination suppose i have 20 objects and i want to get the objects from 11 to 15 right so i can just uh make first is equal to five and jump is equal to 10 which means 10 objects will be jump and then the first five objects will be taken
23:00
right here jump then uh so first 10 objects will be jump and then the first five objects will be taken as a response and then that only five objects will be returned to the client as required so like this is how uh the pagination can be incorporated using the same queries now for authentication for authentication you need to add this code snippet
23:27
into your settings.py file which includes this graphing schema this and this authentication backends so like this so basically these are the middlewares which are required for building the authentication now so uh so basically in my previous slides i have told that
23:48
you need to map all this all that queries and mutations into a single schema.py file which i have shown here that i have built a project uh schema.py file and in this i have mapped the queries of e-commerce uh here and the mutations of e-commerce here so you need to
24:06
map all this uh your queries and mutations into a single file and then you for authentication you need to add these three lines for the authentication now by adding these three lines you will be able to see three more mutations one is token auth verify token and refresh token
24:25
and then using these mutations you can generate the jw tokens so let's see how that first of all i have created a mutation for creating a user and then i have created a user which which username is Nisar you can pass it is also Nisar right now i have one mutation
24:44
which is token auth which is uh obtained by adding this line right now by hitting this mutation i'll get a token which is a jw token and now this token can be saved on the front-end side for uh the further api calls right and also this mutation can be used as a login
25:07
mutation so as as soon as the user passes the credentials these credentials can be used to generate the token and the token can be saved on the front-end side here i have added this uh
25:20
like code in my queries and mutations so if uh i'll not find a token from my api request then i'll just declare it as the user is not logged in so now now basically if i'm passing a token in the headers then it will be an htdb request right so for htdb request i'm using and here i have added this token prefix by a string jwt in my in my this field in my header
25:47
and now i'm just uh querying the post api on localhost 80000 slash graphql and by hitting this mutation i'm getting uh the output or the data from this uh like so like this data so
26:06
means from the server right and if i don't include this jw token then i'll be getting this error message not logged in which means uh the server uh won't pass the uh data to the client without
26:21
this authorization token here are some helpful resources which i have used and these are also resources which could be learned for like which could be used for learning the graph in more detail right uh you can find all these code snippets in this particular github repo
26:42
we are building a type of so like we are preparing a boilerplate of an e-commerce right uh by implementing the graphical apis in jango so my goal is to provide a complete
27:01
backend goal on which a complete e-commerce website can be built using only few modifications so if you want to get updated or with this project then you can watch or start this on the guitar right also i'll be happy to discuss few ideas which are implemented which can be in this project as an ending note now i would like to add one point here that there are a few
27:25
cases where rest is also preferred over graph like if you want to implement a caching system then get the request in restful apis can be cached while while caching the graphical request you need to probably build your own mechanism right the other complexities sometimes routing
27:44
multiple endpoints are much easier than apply then just applying the join operations on your graphical schema and just building a very long schema as it would take much more time to get uh or to get resolved by the visual function right so thank you now like i would like to take
28:06
the questions from the audience thank you thank you what do you need a way to show you that these people listening to you so so thank you very much we have a question uh we have time
28:25
maybe for one more so if anyone has more questions click in the q a and ask so the first one is what are the cons for graph sql so graph ql sorry so what do you think are the cons on using it okay so basically uh so what i mentioned is that uh so uh
28:52
so basically uh while using uh graph ql right uh the caching like the uh system uh like
29:03
so basically for caching your apis uh you need to build either your own caching system or of in the rest apis basically the get requests can be cached very easily instead of graph ql also in graph ql there is one optimization problem which is n plus one problem which means uh
29:24
suppose uh so like basically in graphing if you have a lot of data and if a query is executed then it would take much more time rather than the rest so there are a few cons of graph ql but also there are some benefits which means only single ap endpoint and also no over fetching or
29:42
like no under fetching so like you should uh take as per you know so like your requirements okay so last one and you have like a less than one minute to answer is which are your favorite tools for generating python code oh generating python code okay no idea
30:10
yeah ah from sorry he's saying from graph ql schemas so to generate python code from a graph ql schema okay so uh so like uh sorry i'm not able to get the question that do i need to build
30:27
a schema from i think the question is how you create python code using the graph ql schema i think that was a question okay okay so basically for creating the python
30:41
code using so uh from the graph ql schema so what uh first of all is uh done is uh we need to define that which fields are required in a schema right and then just that fields are required to be added in your resolvers or your uh mutations in which the class argument is defined
31:01
right so from that only uh your uh fields in the queries and the mutations will be uh so like fetch from the schemas also for building the schema in python or basically more specifically in django there are two ways which i have shown one is like you can explicitly
31:21
mention the fields and the other is using django object type but if you are building schemas in flask and all that then you need to uh basically define the complete schema and also for tracking the schema there are few tools such as a graph inspector and all that where you can track your complete schema okay so sorry i'm going to interrupt you because we are out of time
31:41
there is a channel in discord so the name of the channel is talk graph ql api in django so you can people can go there you can continue the discussion in that channel so thank you very much for your talk thank you for presenting in aero python thank you um have a nice day thank you yeah