GraphQL vs REST: What's The Difference And When To Use Which?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] rest versus graphql you're probably thinking ah this is one of those videos again where we're supposed to find out which one is better but then it becomes a lame it depends on what you want to use it for so which one is better well it depends you know why because we're nuanced people the world of software development is not black and white it's 254 shades gray 50 amateurs so we're gonna dive into the details talk about some pros and cons of rest and graphql i'll show you a couple of examples and then i'll give you some of my thoughts on when to use one over the other but before we dive in let's first talk about the sponsor of this video skillshare skillshare is an online learning community with thousands of inspiring classes for creators explore new skills deepen existing passions and get lost in creativity skillshare has many classes on web development programming in python software engineering and software design at the moment i'm following frank kane's course on data science and machine learning with python it's really comprehensive it contains lessons about statistics data types clustering algorithms decision trees covers libraries such as pandas basically everything you need to know in order to get started skillshare is curated for learning there are no ads and they're always launching new premium classes so you can stay focused and follow wherever your creativity takes you the first 1000 of my subscribers to click the link in the description will get a one month free trial of skillshare so you can start exploring your creativity today the rest interface is already quite old it was originated in 2000 by roy fielding in his psd thesis architectural styles and the design of network based software architectures rest stands for representational state transfer the basic idea is that when you want to take some action on a resource you send a request an http request and the body of that request contains the desired new state and the server will then reply with the actual state after handling the request rest interfaces are therefore resource oriented this is different from the rpc style interfaces remote procedure calls which are action oriented you call a remote function that performs a certain task and you get the result back for example you could have an rpc set block title that you pass my title and get back okay instead of the new block now let's take a look at how we can create a simple rest interface in python using flask this is a basic example of a rest api for blogs and blogs authors i'm using flask to create the api and then i'm defining a number of routes one for each of the api endpoints so this route here is the root route and that just returns hello world let me start the server and then when i switch to my browser like so and then i do this request so here we have the local host and the port in this case is 5000 so when i do this get request which is basically what this is then i'm going to get hello world as a return value there's a couple of other things here as well for example i have a blogs route which calls the all blogs function and then turns that into a json data structure so i have a data.pi file as well in this project that provides me with a number of basic operations to do on data on blogs and on authors i have a bunch of classes here like there's a blog class so a blog has an id a title content and an author id i have a payload this is basically what we're going to use when we update a blog so we want to be able to update the title and the content of blog post and we have an author that has simply an id and a name normally you would obviously have way more things in here but this is just to give a simple example and then i also have hard-coded here in the data.pi file i have a number of blogs and a number of authors normally this would be a database but since i don't want to talk too much about database stuff in this video i just made a very simple thing like this and now we have a couple of functions that we can use to read and write this data so finally i have a class not found error that's basically an exception that's going to be erased when we couldn't find a blog at a given id and then have bonus functions like this returns all the blogs this gets a blog with a particular blog id this updates a blog we have getting all the authors and getting a specific offer so these are just a couple of common operations you maybe want to do in a blog system and as you can see in app.pi i just add a couple of routes here i have a route to get the blocks route to get a blog with a particular id this is how you set that up in flask so you provide the id here as part of the route and then gets passed as a parameter to the function and same for the authors and foreign author of a particular id so for example let me switch back to the browser and then when i'm going to put here something like this this is going to give me all the blocks so then i'm just getting this array of blog objects in a json format and i can also get a block with a particular id so let me get block with id 2 for example and then we don't get anything because i think i have to put an s here yeah there we go so now we have to block with id 2. so very straightforward now obviously if you look back at the app.pi file i didn't add any anything else then get request if you want to update a blog well then you have to add an api route for that so currently i'm not doing that so let's add a simple route here to also update the block and that's actually relatively straightforward so i can just add a route here app dot route and then let's say we're going to use the same route so blog slash id and we're going to use you could use a put request or you could use a post request like so and now we have a post request and let's add a function here let's call that route update blog and you see that i'm using actually github copilot here it's already suggesting the things that i should type so basically we have an id that's a parameter and we get the payload i'm not sure that this.json is actually going to work i'm actually generally doing it like this with the get json function call so that gives me the payload and then we call update block i pass the id but have to convert it to an integer because ids are stored as an integer in the system and we pass the payload and then we're also going to return the result of this update blog function call and what object block function call does is that it returns the updated block as you can see here so going back into app.pi so let's restart the server that happens automatically and now let me move to another terminal and now i'm going to place a post request and update a particular block let's just look back so this is currently block 2 so we have this title and we have this content so now let's change the title of this particular block so for that i'm going to do this post request so i'm sending a body with json data which contains a title that's what we're going to update and we post it to this server url slash blogs slash two so that's going to update the second blog for us like so and now you see we also get json back as a result with the updated title and if i go to my browser again and i repeat this get request you also see that the title is now updated so this is how we set up a simple rest api and as you can see we have routes for blogs we have also routes for authors if you want to introduce new concepts into the system like publishers or books or anything else you just have to add a separate route for this and then you can process create read update delete request via that route one thing that's not so great about this design is that we're directly returning the data that we get from operations such as get blog and update blog and that might lead to security issues i'll talk more about that in a minute but this is basically how you set up a basic rest api there are a couple of issues with rest interfaces by the way if you're enjoying the video so far give it a thumbs up that helps spread the word about this channel first issue is that you kind of have to make sure yourself that your rest interface adheres to the standard a good starting point to help you with this is swagger in the open ai standard they also provide tools to help you design your apis while making sure they adhere to the standard i'll put a link to swagger and open ai in description of this video another issue with rest interface that you'll see in this example is that here getting the author of a blog requires a separate request you could implement a population mechanism of some kind but there's not really any standard way of doing this and that leads to having to coordinate several requests in the front end to get the data you need and waiting for these requests to complete which ultimately slows down the user experience a third issue is that rest doesn't enforce a distinction between the structure of the data in the database and the structure of the data that you receive and send via the api this invites developers to just directly send back data retrieved from the database leading to potential security issues for example you might accidentally send back information you don't want to be public such as a user's email address or password and if you're not careful it's really easy to make mistakes here and finally with rest there's no way to control how much data you get back from request now blogs are not that big but if you have a document with a lot of fields you might want to control this in some way you could build something for that but again there's no standard way to do it in rest graphql tries to find a solution to all these issues as opposed to rest which has multiple endpoints and uses various http verbs you know get post delete etc to interact with the server graphql uses a single endpoint and a query language to interact with the server the ql in graphql stands for query language and what about the graph well basically that illustrates the difference between rest and graphql which is that graphql views the data as a graph structure where objects are connected by relationships and thus forming a graph and this is then combined with the query language which allows you to specify exactly what data you want to get back from the server and more specifically which part of the graph structure you want to retrieve as opposed to rest getting blog post and its associated offers is then handled in a single request furthermore you define the interface with the graphql backend via schema and there you specify exactly what the data looks like and this solves a lot of security issues if try to do something that's not specified in the graphql schema you're going to get an error so now let's turn our rest interface into a graphql interface and see how that works so i've already done some of the scaffolding for the graphql example this is basically what the main app file looks like so i'm still using flask to set up the actual server for this but then for my graphql server i'm using a library called ariadne and there is other libraries as well for graphql you also have graphene and strawberry they each have their pros and their cons i might do comparison of all these graphview libraries in the future but basically ariadne is a wrapper library that allows you to easily define a graphql server with graphql types and as you can see there's a major difference between a rest api and a graphql api which is that graphql just has two routes there is a get request that is actually used mainly to get a playground so you have like automatically built in a web server where you can run queries and see what the result is so that's this normally in production you would switch this off and then you have the main graphql interface which is actually a post request to that same url so server slash graphql or you can choose anything you like but this is kind of the standard way to do it and there it gets the json from request because anything you do with graphical any way you interact with it is going to be through json and then it's going to process that request it creates a graphical schema which defines the structure of the request that you can do to the graphical surface and then it runs that request through the schema and through the resolvers in that schema and then it's going to return a json structure containing the result of that particular graphql request and this part here i basically copy pasted this from the ariatni project website we're not going to change this this is we're going to leave this as is this all boilerplate that we're going to need for our graphql server and then handling the request and modeling that whole system is going to be different that's going to happen somewhere else so i did also a few extra things so here we have a simple file that is there just to create a graphql schema for the moment that also doesn't do much it's just relying on the type definition which i'm taking from this file and a mutation and a query now in graphql let me i'll show you in this file there are two main ways that you're going to interact with the graphql servers one is by posting a query that basically means that you're retrieving data and the other is by doing a mutation and mutation basically means a change in some way so these two things you're going to need they're kind of similar to what you have in a um in a rest api with a get request versus a put post or delete request so i have queries and limitations and you always need to define these and you can define your own custom versions of this later on i'll show you in a minute and then we have the type definition in this case the type definition is empty so actually this graphical service doesn't expose anything and as you can see i've here the file structure for this so i made a schema folder that contains this create.pi and types.pi file and then the app loads these and just creates the schema in this particular graphical route so it's very basic at the moment there's nothing in here dealing with blogs or authors yet the first thing that i'm going to do is define a couple of types and queries so let's start with the queries and i'm going to add here to the main typedef a type query which github copied already fills in and then we're going to have the blogs because we want to retrieve the blocks and that's going to return an array of block that's how we define it in graphql then we're going to have a blog that we're going to get via an id and this is what github comes up with but actually we want this id to be not on end but we want it to be an actual id so this is what we're going to do here and this is also going to return block with an exclamation mark which means that this is either always going to return a block or it's going to raise an error so exclamation mark means it's not an optional value basically and we're going to do the same thing for the authors so i have here the authors that's an array of a list of authors and then i'm going to have author by id and that's going to return the author so these are the basic queries that we also had in the previous rest api and i defined them right here now of course i'm using a couple of types but i've blog here and author that are at the moment not defined so let's define these as well and in order to do that i'm going to create another file here inside the schema folder that i'm going to call let's start with the blog so i'm going to call this blog.pi where i'm going to store the blog type data so let me create a blog type def here which is just a string constant containing the type definitions for the blog and that's going to have a type blog like so and there we're going to have an id each blog is going to have a title it's going to have content which is also string and there's going to be an author and let's also put an exclamation mark behind that let's assume each block actually has an author and then we have a brace that we still need to add so this is basically our blog type definition and now what we can do is actually handle here the various queries that we defined in the types here so we have blogs and we have getting a blog by id so these basically correspond to what we had in the rest api before and these things they're going to be part of this main query type thing that we have here so block and blocks are going to be part of this and the way that you do it in ariatni is like so what we first need to do is import from schema dot types the query because we're going to add the block queries here so we're going to need that object and then we're going to add a field to this so query actually behaves like a decorator in ariatne so i can have field here and that's the field blocks because we're going to read all the blocks and then i will add a function here let's call that resolve blocks and that's going to get some parameters so this info object that's actually of type graph ql resolve info and this is going to return a list of blog and now of course we need a couple of imports to resolve all those things so what we will need is from graphql we're going to need graphql resolve info and from data we're going to need block because that's what we're going to return and we're also going to need all blocks and we're going to need gut blog as well so all blogs and get logs then our resolver here is actually really simple because here we're just going to return all blocks like so and we can do the same thing for block with a particular id so let's also add another field to the query called blog and let's define a function resolve block and this is going to get also the info object but it's also going to get a blog id so that's how we set up a simple resolve for blogs and for a particular block and also support all these things i need to also add this type definition that we just made here to the schema so when i go back to create i need to add it to the create schema function here so let's add it here blog typedef and that's going to automatically import it like so so now the type definition is also available to our schema and that means that it's exposed via the graphql api so i'm going to run the application now so now it started the graphql server so when you have graphql server you basically also have this playground which allows to easily write queries and get the results so for example what i could do is write a query here and we're going to get all the logs and for each block we want to have the id and we want to have the title and we want to have the content and then when i run this query i get the blocks just like when i used it with the rest api but here i'm just defining it as a graphql query so see i didn't have to specify the endpoints i'm specifying the way that queries and mutations are handled in graphql and because in the query we specify what we want to retrieve on the backend we have a lot more control now over the data so for example if i just need the ids of the block i can just remove these two things from the query then run this query again and then i just get the ids so this gives you on the front end basically a lot more control over the data that you need and it reduces the amount of data that the server needs to send back to you and that will overall speed up your application i want to show you one more thing in this graphql example which is to allow for limitations so instead of just defining a type here if we let's say you want to update the block as well well then we're going to need an input which is a block payload and that's going to get the title so that's not obligatory it's optional and we also have content and then finally we need a type mutation with which we can update the block so let's call that update block and it's going to get an id and a payload and it's going to return a block and then what we need to do in our graphql system is that we need to define a resolver for this update block mutation and maybe because it's python we should also name it like so to follow kind of the python structure you don't have to you could also use the camel case version the only thing that we're going to need is to add an extra import here which is the mutation because we're going to add a mutation and then we're going to do exactly the same thing as we did with the query field we're going to add a mutation field and that's a update block and then we're going to write a resolve update block so we see we already got that here and that's going to call the update blog function and then update the block and return that as a result so it's very similar to how you would set it up in a rest interface but here we're using resolvers to do it and there's one more thing that i want to show you that's actually quite nice with graphql and we kind of already did that when we specified the types but we noted that if you look here in the blog tab we have an author field which returns the author and that's the nice thing about graphical that you can create these kind of connections that kind of creates this graph like structure that is so nice let me show you how that works so in order to do this i need to specify a special query type for blogs specifically and we can do that right here it's just one line of code with ariatni so i'm just going to create a blog query which is a so-called object type and that's a block like so that's our blog query object and we can attach resolvers now to our blog object and the resolver that we're going to add is the author field resolver so let me add here a blog query field which is called author and then we have a resolve author resolve block author we could also call it so what github generates here is not entirely correct in fact this first thing that we have here this is actually the block so the first thing that we get here in the resolver is the actual block that this field belongs to and then what this is going to return is of course the author and then we're going to return get author and then we give it the author id of the blog and we should access that through a dictionary so this is then what happens let me save this and now let's go back to our playground here and now what i can do oh this doesn't work somehow i think i forgot something somewhere over here let's see so i need to add the block query to the schema so let's import that here and then let's add it to the list here log query obviously if you define a query object you also need to make sure that it's part of the schema so that's what i have now so let's try this one more time so now we're back in the playgrounds and initially we got the vlogs like so but now what we can do because of the author resolve that we just added i can now write here author and then from the author i can get the id and the name for example and now let's run this query and you see that now for each blog we get the author so this is exactly the graph like structure that graphql allows you to create and i don't want this video to be too much about graphql it's mainly about the difference between rest and graphql but here you see a major difference that instead of having to do two requests like what you have to do with the rest interface here you just add it to the query and then you get exactly the data that you need though graphql doesn't have many of the problems that the rest interface has it also introduces some problems of its own let's look at some of the cons of graphql one of the cons of graphql is that sending a request to the server is a bit more complicated than with a rest interface since you have to specify the query or the invitation that you want to make and with the rest that's just encoded in the endpoint and the http verb the second issue with graphql is that it suffers from the n plus one problem if you retrieve a bunch of blogs with authors a separate database request is going to be made for each offer and that potentially slows things down in order to fix that you need to introduce some kind of local caching mechanism in the back end to avoid all those different database requests or a mechanism to group resolvers in graphql most graphql libraries don't offer something for that at the moment another thing that i think can be improved is the query language it's quite for both in some cases for example specifying notation is a pain you have to define variables both in invitation name and implementation call i think that can be shortened to make it easier to use and finally not everything in graphql is standardized for example would be nice to have a standard way to do search with pagination with page sizes and results or using cursors or something like that also having some standard options for authentications rules permissions would be a great improvement i have few thoughts about when to use rest interfaces versus when to use graphql first because rest interfaces are really simple to use they're great for smaller applications and for public-facing apis but really important you have to take care of security only expose data that you want to be public so make sure you use some kind of layered architecture where you explicitly translate data from the database into its public form for more complex applications that are tightly integrated and need specific sets of data graphql is really a great option your front end is going to be much easier to manage especially if you use a graphql client like apollo that supports things like automatic caching of local data subscribing to changes and more i hope this video has been helpful give it a thumbs up if you liked it and consider subscribing to my channel if you want to learn more about software design and development thanks for watching take care and see you soon
Info
Channel: ArjanCodes
Views: 187,640
Rating: undefined out of 5
Keywords: graphql vs rest, rest vs graphql, rest api, graphql api, what is graphql, graphql vs rest api, graphql tutorial, graphql for beginners, rest api tutorial, why graphql, what is rest api, graphql or rest, graphql vs rest caching, graphql vs rest 2022, graphql vs rest pros cons, rest api explained, rest api python, graphql, graphql vs rest vs rpc, graphql python, graphql resolvers, rest api design, web development, graphql server, Graphql vs rest vs soap, graphql mutation
Id: 7ccdWqGgHaM
Channel Id: undefined
Length: 26min 57sec (1617 seconds)
Published: Fri Feb 11 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.