Hackernoon logoWiring up a GraphQL server with Node and Express by@KondovAlexander

Wiring up a GraphQL server with Node and Express

Alexander Kondov Hacker Noon profile picture

@KondovAlexanderAlexander Kondov

Software Engineer

GraphQL or Graph Query Language is one of those things that you see mentioned in blog posts and articles but you are unsure exactly what it is. It is pitched as a wrapper around your API that allows you to query only for the data that you need.

Sounds great, the examples also look great, but how does it work? Is it worth putting in the time into it and where do I start? Sounds complicated, how hard is it to set up this GraphQL thing? I’ve been playing around with it lately and I’ll try to answer those exact questions here.

What is GraphQL?

GraphQL is basically a query language for APIs created by Facebook. It allows us to create some interface, some wrapper that stands on top of our different APIs allowing us to query them easily. It has a simple intuitive markup that allows you to get for only what you need. You can also think of it as an alternative to REST.

When you do an http request to e REST service you usually have something like this: http://some.api.com/posts. On this endpoint you will most likely get a list of all posts but you can’t specify what fields you need from every post. Actually depending on the API you may be able to do that with some query parameters like http://some.api.com/posts?fields=name,image but you see how obnoxious this will become. Then if you want to also get the post comments with that query http://some.api.com/posts/comments?fields=name,image.

With GraphQL you use a simplified language to specify what collections and fields you want to access. It’s made to be as simple as possible and is similar to the object notation we are used to. Notice how the structure of the response is structured the same as the requested data.

Now that we have a visual understanding of what it does let’s go a little deeper. Even though I will focus on the JavaScript context, GraphQL has many implementations and is not limited to any one language.

It’s main point is to abstract away the complexity of the APIs you’re using. No matter if they are your own services or you are using some 3rd party ones or even both, putting them under GQL allows you to remove the details and provide a super simple interface to query data. Some APIs are still using XML while others may have an unpleasant nested structure. This is too much work on the client just for parsing some response. By doing it on the server with GraphQL your Single Page Application will only have to know how to work with one endpoint.

For those reasons GQL is liked by the front end community — they can specify the data they need in a really simple and straight-forward manner without having to learn the API implementation or how it relies on the parameters being structured.

You can use GraphQL for both getting and posting data. For now we will not be covering data posting, just letting you know that the option is there.

Setting up GraphQL

Front end developers are widely accepting GraphQL as a replacement for REST. It’s much more intuitive when it comes to request structure, knowing what to query and what to send. But implementing it is more work for the back-end developers.

Server side devs are those who will have to do the majority of the work and trust me it’s not a small task. There is no automatic mapping between your database and GraphQL, you need to write everything on your own, create the collections, their fields and their relationships.

Thankfully, the libraries that you will most probably use are well documented so you will have a guide in the process of abstracting your APIs behind GraphQL.

Building a GraphQL server with Node and Express

In the rest of the article we’ll focus on building a basic GraphQL server using Node and Express. First off, we need to install the libraries we will be using.

npm install express graphql express-graphql

I mentioned earlier that GraphQL is not language specific and it has many implementations. This is why we will need the express-graphql additional package to make that connection. After that make an empty JS file called server or index or whatever you like to call your entry point.

There won’t be too much modifications going on on the Express side, so let’s get our basic setup:

We won’t be doing much work in this file and as you can see wiring up GQL with our Express app is as simple as registering a middleware. The expressGraphQL function takes an object as a parameter. One of the properties of that object is graphiql. By setting it to true, we specify that when we go to /graphql we want to see a panel (like in the screenshot above) in which we can test our queries. Also it will automatically generate some documentation for all the queries you’ve got.

If you go to /graphql you will probably see an error saying that the GraphQL middleware needs a schema. This is because we haven’t wired our queries yet and GQL is a little bit pretentious when it comes to that. So we will create another file called schema.js in the same folder.

In this file we will define our root query. This is the main entry point for querying data out of our server. Inside of the root query we add the behavior for every piece of data that it will be responsible for (different fields, query params).

First we need to require graphql, then we destructure two objects out of it. The most important part is initializing the RootQuery — it should be a new GraphQLObjectType with two parameters — name and fields(what you will be querying).

The export you see at the end is necessary so we can add this to our GraphQL initialization. After you’ve done this we can easily import it in our server.js file.

This is the final version of the entry point of our application and we will not be doing anything more in this file for now. So let’s build our first query! In order to query anything we need to create a new type. If we want to query posts we need a PostType, if we want to query users we need a UserType. If you have previous experience with backend development, types are like models — they are the description of your schema. Let’s make a super simple version of our post type and wire it to the schema. Then we’ll finally be able to get a sensible response from GraphQL!

There we go, we got our server running! Right now we are accessing the data through some admin panel but in reality we’d like to do it with a client-side request. There are some client libraries that help you do exactly that, but for simplicity’s sake we’ll use a simple http request. Go to server.js and comment out the line that sets graphiql to true and fire off this request(if you don’t you will see the admin panel again).

This is all great, but how is it different than having a simple express server? GraphQL should be an entry point to your different services, so behind every GQL query you will most likely fire an additional request to the appropriate service. By using different Object Types you can actually query data from multiple sources with a simple request. Usually our Post Type will sit behind some other API or service, then we can have a Weather Type that could query data from somewhere else.

Replace your root query with this one and after refreshing you should be able to query all the posts from this sample API. Something to note here is the use of fetch. Because we’re running node and we are not in the browser, we don’t have access to fetch that is provided there. To make use of the same syntax, I have imported the node-fetch library. You can do so by running:

npm install node-fetch — save

and then require it at the top of the file with:

const fetch = require(‘node-fetch’)

Of course this example is the simplest one possible but it’s enough to get you going with the idea behind GraphQL. In the next post we’ll have a look at advanced querying and using multiple Object Types.

Thank you for the read, please hold the clap button if this article was helpful and share your feedback!


Join Hacker Noon

Create your free account to unlock your custom reading experience.