Creating A GraphQL Server With Node.js And Express

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys this is Sebastian again from coding the smart way comm and today in this new video we are going to dive into graph QL I will show you how to set up from scratch set up a server a graph QL server was no GS and Express you will learn how to use the Express graph QL middleware to set up a graph QL server and once the server is running I will show you how you can send queries or mutations to your graph QL API and yeah let's get started and start with the first step and take a look at graph QL so first of all let's take a look at the graph QL website and you can find the website at graph QL dot org and here on this side you will find basic information about graph QL about how to use graph QL on your server and how to use graph QL for our sending queries from your client you can even see a very simple example here on the start page so graph QL is used on both sides it's used on the server side to just describe your data and describes the operations your API is offering and then you can use a graph QL query language on client side to yeah to send queries to your graph QL server and you get results in the graph QL format so this is a way graph QL is working and there are different or there are various advantages of using graph QL for your API just let me summarize the most important ones first of all ref QL is decorative this means that clear responses are always decided by the client rather than the server so a graph QL curry always return returns exactly the result the client asks for and nothing more next one is graph QL as compositional so a graph QL query is a hierarchical set of fields and the query is shaped just like the data it returns so it's a very natural way of describing your data requirements new requirements to ask for data from an API and the next advantages graph QL is strongly typed so a graphical a query can be ensured to be valid within a graph QL type system so you are defining the types of your data when you are describing your data on server side and then if you send your query to the server the validation against the type system is taking place so this just just give you a first impression of some of the advantages and what we are doing next is we are proceeding with a practical part so let's switch over to the command line in rouen the first project we want to start here is to set up a graph QL server with no trace and Express and the first step of course we need to take is to create a new project directory so let me do this we are starting with creating a new directory here become graph QL - server so let's change into that directory so the first thing I'm doing here in the project directory is to initiate and node.js project and in particular adding a package.json file so that we have a file where all our dependencies goes into and the way we can do so is by using the npm command so you should make sure to have no js' and the node package manager npm installed on your system so if this is the case we can call npm in it which is initializing the project and creating a package dot JSON file we are being asked some questions here but I can just hit return for all those questions and if I now take a look in inside my directory you can see a package dot JSON file has been created so we do need a our script file to implement our code which is needed to setup the service so I'm creating a new Mt our script file here we are naming this file server daughter Janus and finally we need to add of course some dependencies some NPM packages and to install those dependencies on using the NPM install command again and first package we need here is graph QL then we need of course Express and finally we need that the Express graph to our middleware which is Express - graph QL and then I'm saying - - safe to add all those dependencies - packaged up Jason hit return and you can see it's downloading and installing all the needed dependencies into my project so once it is done let's take a look inside you can see we now have a node underscore modules directory where all the dependencies have been installed into ok so now that the project setup is ready we can start and right the code we need to set up the node.js server and here in the project directory I'm starting my code editor which is Visual Studio code so I can simply type in code dot start Visual Studio code and the project directory is loaded automatically as you can see here of course you can use any other code editor you want to use that's not a problem and I have already opened up a server yes as you can see here and the first thing now I need to do is to yeah import some modules I do you need so first of all let's import Express by saying our Express equals require and then I'm passing in the string Express because at the name of the module next I do need the Express graph QL middleware so let's say require and then the module name here is Express - graph QL like so and finally we need to import a function which is called built schema and this function is imported from the graph QL module itself okay now we have imported everything we need to set up the server and the next thing is to define the graph QL schema by using the build schema function so what is the schema used for of the graphic yuan schema is used to first of all describes the api's type system it includes we complete a set of data and D and defines at the same time how a client can access the data so it defines what operations are available to query or yeah create or update at the data and each time the client makes an API call the call is validated against that schema and only if the validation has success is successful as the operation is executed otherwise an error is returned so now how to define a first simple schema so let's stop adding a comment here that's the section for the graph QL schemer and as mentioned we will use a build schema method and the store has a schemer in a new variable called schema so and this is equal to built at schemer and then we need to pass over the schemer and I'm using a multi-line string here so using backticks to define that multi-line string okay so we will start with a very simple schemer so we have one theory so a query operation which can then be used by the client and we have one query and that is message and the message query is simply returning the string so you can see what is meant by strongly typed we are setting the return type of the masses message query to string so this is a very simple schema we have no object type defined we have no high racket hierarchy involved in defining our API type system here it's just a very basic schema with one query just returning a string okay that is all what we need at first and then we need to implement a so called resolver and by using a resolver we can attach a function which is called each time clearly from our schema is needs to be executed because a client is requesting to execute this query and the root resolver will be defined in the following way here so we are saying about root equals and then the object containing a list of queries so we have only one that's the message theory here and then we are assigning the function which is executed and the function is of course a very simple one because we only need to make sure that the function is returning a string because that is what we were expecting to get back when the message query is executed and I'm setting it to use a string hello world so that each time this query is executed the same string is returned okay like so so now we have the schema in place the root resolver in place now we can bring in as a code which is needed to setup the Express server and attach a graph QL endpoint to on the server so let's say create an Express server and graph QL endpoint that is a task and to do so we are saying bar app equal to Express so here we are getting back the instance of our Express server and now we can say app use to attach the Express graph QL middleware to an endpoint so we need to pass the endpoint first and that should be on slash graph QL so if our server later on is running on a local host for example you can access local host which is a port number and then say slash graph KL and you will be on the endpoint okay next yes the middle way we are going to attach to the endpoint and the dessert cause Express graph QL and this call of Express underscore graph QL is expecting to get one parameter and the parameter is a configuration object containing various configuration properties so let's add those properties here as the first thing we need to set the schema of course schema is available in the variable schema next we need to attach the resolver object so the property is route value and we need to assign how I would resolve an object which is route okay and then there is a property which is called graphical so graph iql and we need to set this to true graphical is a tool running on the browser which gives you an a user interface when you access an endpoint so that you can directly type in your graph QL query in the user interface and then by using that user interface graphical you have the object directly execute it and see the result coming back into what you see in the browser so this is a very nice tool and we will use graphical later on to try out our API so we are we need to set it here to true to make sure that this is running at the specific endpoint okay like so so then we need one final line of code because we need to start up the server that is done by saying F dot listen and we are passing as a first parameter the pot let's say 4,000 and then passing a function here which is executed once the server is running and by using that function we can print something out to Z console by saying cone zone lock and printing out a string for example which is saying Express graph QL server now running on a local host port 4000 /r f ql that's our end point okay like so so that is a code we need to set up a basic a very basic graph QL server with no trace and Express and now let's try it out so to start up the server i've already open up the integrated terminal here in Visual Studio code which you can see here and here was in the project directory are now can say note and pass over the file name where our code is stored into and that is server dot ojs hit return and you can see it's starting up the server and it's printing out the string we have defined here saying Express graph QL server now running on local host port 4000 /r f ql so let's check it out in the browser you can see it here if I'm accessing that URL you can see it's starting up graphical so this is the user interface and the window you can see here is split into two areas here on the left side you can type in your graph QL query you have an example here and on the right side you will get back of the result and then there is an input of field available here if I move it a little bit up you can see it here it's called query variables and if our query is using dynamic input variables you can define the values for those variables here in that window ok so let's try it out our server is running our API is up so we can execute a query for our message query and see if we are getting back the result spring have a world and yeah check if everything is working as expected so let me first of all remove the default content here in the query window and then I start with opening curly braces and of course closing it and within the curly braces I'm including the query I'd like to execute and you can see it here we have yeah something like intellisense here it's already coming upwards the proposal message if I start typing so I can hit a return and then message is inserted here and that's everything I need so let's hit hit execute query here is at this button and you can see we are getting back an object containing a property data containing an object with property message and the value of messages hello world so our API is returning the correct string and everything is working as expected okay see example so far was quite simple so let's go back to the code editor and now I'd like to implement a more sophisticated example and yeah just show you how to extend the schema at first a little bit bringing in some dummy data and define multiple queries and to define mutation - although update data and yeah first of all it stops the server process which is still running here and I will copy this file and create a second file so servitude rjs okay here we are let's open that file now let's first extend the schemer here a little bit and what we are going to build is an API offering you access to a list of online classes and we will define to query types the first query with first query you will be able to request one cross record by passing in the ID and with the second query you will be able to Qwest a list of courses for a certain topic okay so let's remove the message query here but before bringing in the nucleus let's define our object type first and that is cause and cause is containing a set of properties first of all we need an ID here which is in integer then we need a title here which should be of type string then we have also property which is also a string a description which is a string topic and finally a URL which is also a string okay this is our object type here now we can use that type course to define our queries so the first query is called course and it's taking in parameter ID of type int and I'm putting in an exclamation mark here as well to indicate that this parameter needs to be filled and we are expecting to get an return type of course so this is the first query second theory is called cause causes and takes in a parameter which is called topic type spring and we are expecting to get back an array of course objects so we are using brackets here and putting the object type inside the brackets okay like so so next because we want like to work with Kwas data in our API we do need some dummy data and that's the reason I've already prepared an array here so copy and passed it in you can see it here it's called causes data and it's an array containing three objects one two three and each object is a course object you can compare it it has the same set of properties so each objects also of those objects comes with an ID title also a description topic and ul so this is the set of data we will be working with and now of course we can continue to adapt the route resolver so message is no longer needed here now we need to assign functions for query course and for precursors and the function which will be assigned to you the first query type is get course so and the second function is get courses and of course now we need to implement both functions here in 70.3 s as well so let me insert get course first so it's a function of course and it takes the arcs parameter and now the logic we need to implement is we need to first extract a zrd which is passed in the ID parameter and then find the data set from our courses data array which has exact busy that ID and return that object so first of all how to read out the IDS it's straightforward so we are defining the T variable here and then saying our stop ID and next we are returning what we are getting back from closest data dot filter and then we need to pass in the filter function like so and we are returning that object from the causes data array when applying that filter here which is containing the same ID so cost dot our D equals ID okay and as we are getting back an array here we need to select the first element which is at index 0 like so ok so next let's implement the second function as let's get closest ok this time we need to check for the parameter topic because we would like to select all courses which belong to a certain topic so first of all it's check if topic has been passed over so then it should be in arcs dot topic if that is the case we can continue here else we are simply returning on the complete array and if we can continue with a topic we first store the topic in topic and then return again from closest data we are applying a filter here to only return cause objects from that array where the course dot topic property is equal to topic okay like so so let's try it out again so I'm using the node command once again this time passing over the server to dot J s and here you can see it the server is again running so I'm not switching back to the browser let's refresh it here okay so it's running a graphical graphical is a Weibull we can start typing in our query operation and this time I'm using the following syntax I'd like to start with a pure keyword here because now I would like to bring in a named query operation and the name I'm going to use here is get single course and this get a single cost curry operation is taking in one dynamic parameter and to define that parameter we're using the dollar sign here and then giving it the name which is cause ID and this should be of type int and again I'm using the exclamation mark here to indicate that this parameter needs to be supplied okay curly braces and then we are bringing in the query we would like to execute and this is first of all we are trying out course to get a single course based on an ID and this time we can set the IDs across Korea's expecting to use the dynamic value which is available in dollar sign course ID okay and now was graph QL we can define the fields we would like to get back and there is title author description topic of course and the URL okay now we are nearly ready to execute but of course we need to make sure that quad ID is set to you a value and that elsewhere Curie variables comes into play here and now we can set cross ID for example to the very one and the way to do that is always start with curly braces here then include cause ID and yeah then assign the value here which should be one so this is all we need let's try it out and you can see we are getting back the cause object containing all the fields which are defined here in our course query with the corresponding values so the API is working and now we have tried out the first query let's try out the second one as well okay let's change the name of the query operation maybe to get yet cause us for topic the parameter name needs to be changed as well because this time we do not need to supply an ID but instead we need across topic which is of type string so the query which I'd like to execute is called quasars the topic parameter is set to dollar sign cause topic and we need to change it here in the query variables section as well so course topic let's say we would like to have all courses for topic note dot j s well it's executed ok we have an error here it's saying course is not defined let's see I think this must be on error in our server implementation in the function get classes so let's see course not define okay that's because we uses courses here else the input parameter for this function and here the we need to delete that s okay so let's start the server again going back into graphical trying to execute the Korean now you can see it's working it's returning to courses those for topic nodejs and that is exactly what we want to have okay let's do another example here and graphical because you are able to include the queries in one query operation and this is what we are going to do now in the following example so let's delete it here and we are going to start with defining a new career operation and this time else I'd like to include two queries for two crosses I will introduce it to a concept which is called fragments at the same time and is this the reason why I'm naming it get process was fragments and because we would like to retrieve two consuls we need to IDs so to dynamic parameters and the first one is called cross ID one and the second one is of course cause ID to like so and now we can include the two queries and we are going to include both queries by assigning an alias and of giannios for the first curious cause one okay let's so we need to pass in the value which is Weibull and dollar sign cause ID one so this is the first query let's copy it and pass the dinner a second time now we are using the alias cause two and we are setting the ID to value dollar sign cause ID - okay like so now we need to bring in the values here for our cause ID one and two so once change it back to course ID 1 and the value here should be 1 and let's use cause on D 2 and the value is 2 like so ok now we need to include the fields in our query and instead of bringing in the same set of fields two times one time here in course one query and the second time here in cost to query we are defining a fragment first and that is done by using the fragment keyword we are naming it cause fields on course so on our custom cost type and now I'm bringing in the list of fields I'd like to have here in this fragment that is title author description topic and ul and now I can make use of this fragment here in both queries by saying three times dot dot okay and then ya bring in the name of the fragment and that is cause fields and the same needs to be done here as well okay so the fragment basically makes the list of fields reusable and multiple queries so it makes the syntax a little bit more readable and if I now execute the query you can see it's again containing two two results here one for coins one and the second for cost - so the name of the earliest we defined here is also used in our resulting data structure else you can see here so far we have only seen examples which fetches data from our graph QL server but of course was graphic ul it's over possible to modify data by using mutations and to be able to use a mutation with our graph QL server we first needed to add code to our server implementation in our server to dot J's file so I'm going back here to Visual Studio code yeah it stops the server here and to define a mutation I need to start here with my schema definition and I need to bring in another type here and the type is called mutation like so and the mutation I'd like to define for my arm API is called update cross topic so I think the name is making Clearwater this operation to do each time the client executes an update cause topic mutation the topic value of a certain cause should be updated so we need to supply that mutation with two parameters first parameter we do need here is the ID of the Court which should be updated of type int and the second parameter we do need here is the topic value we will use for updating and that is of type string we are returning a cause and the cause is the new object containing the updated topic value okay so next thing I need to do is of course go to resolver and add a function which is connected with my mutation so I need to bring in another property here the property is the name of my mutation which is update cost topic and I need to assign as a value a function here and the function is called update cost topic as well so having defined at that and the resolver I now need of course implement my update cost topic function and I will do it here right above so our update cost topic equals function and now the function is getting one parameter and the parameter is an object containing the ID and the topic information so we can use this syntax here and yeah the logic of the function is of course the update logic we do need here and to do an update we are calling causes data dot map and we are passing in a function here which takes one parameter that's the cause and then the function body and the logic here is if the cause ID is equal to ID then we can perform the update and we're updating close dot topic of course with the value of topic and finally we are returning the cause object okay and then we need to make sure that update cause topic is returning the updated the updated course as well as a final statement here so to find a bad course again we are accessing courses they once again calling the filter method and passing in a faction which is doing the filtering and the filtering which needs to be applied here is that we need to select the object where course dot ID equals ID and as we're getting back an array we need to select the first element from that array here okay let's again try it out back in as a browser let's change the code here in the query section we can keep of the fragment which is defined here but we need to delete the query section here and instead I'm using the mutation keyword to define a mutation operation and the name of that operation should be update cause topic and it takes two dynamic parameters the first is dollar sign ID and it's of type int and it's mandatory so see I put the exclamation mark here the second one is of course topic of time string again mandatory so within the update across the topic operation type we are calling our mutation that is update caused topic and we are assigning the ID parameter to of the value of dollar sign ID and the topic parameter is assigned the value of dollar sign topic ok let's again use the fragment here so it's cause fields like so and now we need to change the query variable section here so first thing we need to supply as an ID and the second thing we need to supply is a new value for topic and that is a string so let's say for the data set was ID 1 we would like to set the value we have a script okay let's try it out you can see it here we are getting a returned of the cause which has been updated you can see it here the value is JavaScript so just demonstrated we can set it back to the original value which was not--don't j/s let's execute it again and you can see here it's changing back to node.js so the mutation is working as expected so this was Sebastian from codings a smart way comm I hope you do like my videos if so please don't forget to subscribe to my channel on YouTube please give me a thumbs up if you do like my video and please also don't forget to visit my website at codings a smart way comm and I hope very much to see you in the next videos bye you
Info
Channel: CodingTheSmartWay.com
Views: 58,412
Rating: undefined out of 5
Keywords: GraphQL, Express, Express.js, Node, Node.js, NodeJS, GraphQL Node, GraphQL Node.js, Learn GraphQL, express-graphql, Express Server GraphQL, GraphQL queries, GraphQL mutations, GraphiQL, GraphQL Tutorial, Building a GraphQL Server, JavaScript, Getting Started With GraphQL, GraphQL for beginners, CodingTheSmartWay.com, GraphQL with Node.js, GraphQL From Scratch
Id: Vs_CBxCfFHk
Channel Id: undefined
Length: 46min 15sec (2775 seconds)
Published: Sun Jan 21 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.