I have seen a lot of tutorials online about how to build a graphql api and i must say lack one thing, the basics. So what i am going to do here is have this tutorial in two parts. Part 1 will talk about what graphql is and go ahead to setup a simple server with express alongside graphql.
What you will learn in this tutorial isn't solely for javascript folks as i will make sure i take you through the basics and you can go ahead and look at the libraries for other languages and start building on the knowledge acquired here.
Part 2 will be an advanced part where we actually build a full api that we will test with postman and the graphiql interface. At the end of this tutorial i hope you will be able to build your own api for any app you are working on or a new project you would like to start. So lets get started.
Graphql is simply a query language for whichever api you are building. When i say query language i mean, a way of interacting with your api itself and not a database as we used to know it, when we hear about the word "query". If you have been programming for long, i know you have come across query when working with SQl(Standard query language) databases such as MYSQL and POSTGRESQl. We use to query databases with the standard language mentioned above so something like
I guess you remember something like that, now what this allows us to do is select data that we need, when we need it. When retrieving data from the database using SQL we have the flexibility of getting what we need and not more than that. However, if you are familiar with rest apis, you realize that data is given to you usually in a JSON format when you send a GET or POST request to an endpoint. Most of the data the REST api sends won't be used by the client side but bandwidth will be consumed. This one of the things graphql is solving by allowing you to query your api like we did with SQl. Now that you understand how it works, i will take you through the terms you will be mostly using when working with graphql.
When working with graphql, all your request to the single endpoint will be post requests. I know you are wondering how you will just get data like you use to do in the REST architecture. That brings us to the term, Query. Query is used to get data from your api. But what use is an api if you can't also manipulate data on the server side as well, so that brings us to the term, Mutation. Mutation is just like POST, DELETE, PUT in the rest architecture. There are other terms like subscriptions and fragments, but we will be focusing on queries and mutations for the purpose of this tutorial, but feel free to read about them on their page, Learn more about Graphql
Now that you know the terms, let us see some code right away. My favorite part. I assume you know a bit of js and node. If you don't please leave a comment and my next article will take you through the basics of node. First off, we create a server using node and express. You can create a new folder in whichever workspace you are ok with so open your directory or create a new on using cmd
After creating the directory for the app, run "cmd" in the address bar(assuming you are on windows to open the command line in that folder.
Lets start a new project with npm init
Just go with the defaults and in the end, you should have something like this
Afterwards, let us install all the packages we will need, by running the following in that same directory
You can also install the body-parser package to turn our requests into json
Express is the ever popular framework for node, graphql is what we just talked about and express-graphql contains some important modules we will be using to build our server and api and mongoose will help us connect to our mongodb database with ease.
You can then open the newly created project with your favorite IDE and craete a new file named index.js if you went with the defaults of npm init, or whichever file you names as the main in your package.json file. After creating the file we create a simple server in this file with express. Something like
Now you have the express server setup with graphql. Express is being used to start our server and we require graphql http from express graphql to use as a middleware for our api. That is going to handle all the request that goes to the graphql route given. In the graphqlhttp module imported, we are going to give the options with which graphql is going to work with. Some of them are the schema, which will let graphql know how we are going to query our data and how we want our data to be like. Another option is also the root value that will take all our resolvers thats the functions that will allow us create and manipulate data in graphql. Another useful option is the "graphiql" which will give us the ability to interact with our api using an interface when we navigate to the "graphql" route in our browser. So let us add the options now
In the above gist, we can see the schema and graphiql options added to our code now. The schema is required to have graphql run successfully, because that is the only way graphql will understand our request to the api we are about to build. So i created a function called defineSchema which basically defines our schema. In the schema, we have "buildSchema" which was imported from the graphql package. this is what will build our schema using the string we give it.
MainQuery is a GraphQL Object Type that has a field named library. the library field is of Strings, which means only strings will be in that field and the exclamation mark after it means, it is not nullable. So whenever we query our api for library an empty array will come to show that it is empty or an array of strings will be given by the api based on what that field has.
There is also a getlibrary function that gets the books in the library, for now it is just an array because we haven't connected a database yet. The name of the schema in your queries should match the name of the function keys in your rootValue, this will help graphql know what you want and get you exactly that. So the more schema types we add to the queries the more mtaching functions we add to the rootValue. Schema defines the data, rootValue gets us the data.
So if you start your server using node and navigate to the graphql route, you should see this simple interface that will allow you to interact with the api you just created. For now, it doesn't do much, but i hope you understand how it works. This should be what you see at your "/graphql" route
Now lets query our new graphql api now and get the books in our library using the GraphQL schema language.
From this query and curly braces the next level is the name as stated in our rootValue, thats the function to get the data. If you enter the code in your new graphql explorer, you should have the getlibrary function called and books returned as the data. So using the same route, we can state another schema and root value and query it with ease, thats the power of graphql. I hope you enjoyed this tutorial and learnt something today. Will continue with the next part where we actually build a fully functioning api, where we store and retrieve data from our mongodb database. See you in the next post. Connect with me on twitter @AugustusOtu with any questions or comment here for any explanations. Share to your circles.
Happy coding....Bye for now
Top comments (8)
Can't wait to see the next section! I've just started building APIs with node and express and I've heard a lot of people saying GraphQL is really cool and this was a great introduction
Glad you like it. The next part will be more fun as we build something real 😉
Amazing post!
Thanks ben😊😊😊
No part 2?
Thanks for the post. Great explanation of the basics.
amazing, how about authentication and authorization wiht JWT ?
Ohk, i think that could be after we setup all we need for graphql, but am preparing a post for the continuation of this then how to accept stripe payments. Will do a post on authentication and authorization soon and JWT is part so watch out. But feel free to reach me on twitter if you have any questions and will be glad to assist.