REST API or GraphQL that is the question

GraphQL is not something related to databases, even if QL that stands for Query Language can let us to think that.

Danilo Del Fio
Sep 19, 2017 · 6 min read

Nowadays seems normal to use REST API to connect our server backend with the frontend and It is considered the best way to do that.

Sometimes, however, we don’t need all the stuff the server send us back to the client, so we have to choose the best way to afford this situation.

  • We can ask for all the data from the server and then manipulate them in our client
  • or, we need to split our endpoints to fit our fine-grained requests.

GraphQL is defined as data query language and runtime. In fact we can define our requests from our client to a server that “speak the same language”, that is GraphQL, to ask what we want to obtain.

In few words:

The GraphQL query (defined on our clients), describes the shape of what we want to obtain from server.

So, now we know that GraphQL is a new language

You don’t have to be scared, because if you know JavaScript Object Notation (aka JSON), GraphQL language is pretty close to it.

In the other side, the GraphQL runtime layer, that can be written in any language, define a generic graph-based schema to publish the capabilities of the data service it represents.

With this paradigm we have the real separation of concerns, because the server knows what is possible, meanwhile the client knows what it needs.

A graphQL operation can be either a query, for read operations, or mutation for write ones.

Here you can see a simple Query that describe that we want to ask for a task with id=12 and we want to obtain only the name, the description and the assignee. A possible response can be:

If we strip out all the values from JSON Dictionary (the response from our server), we get the GraphQL query we have used for the request.

GraphQL just shift the mindset from server to frontend developers, because until now we think about of what services we want to expose to the client and then build it reflecting this shape. Now, instead, we can shift the command stick to client side that express what it need with queries and the server can build it’s runtime separately. Furthermore client can request multiple resources within the same request and customize the fields needed from all of them.

With GraphQL, client and server are indipendent so they can change indipendently.

Let’s explain the mind shift with a simple example. Suppose that we want to build an application that shows an event with the information it brings with itself. Then suppose that our event has some related resources, like the list of attendees with their information.

Our first call can be something like: /events/{id}

The response can be something like:

I’ve followed the RESTful syntax, that is with the specification of the URLs that we need to follow to fetch related informations, like attendees and organizer. With this kind of pattern we have to call the server at least five times to obtain all the informations we need.

We can, of course, create a specified endpoint to obtain all the attendees for an event: /events/1/attendees.

Proceeding in this way, first, we don’t control the fields returned by the services we are calling and then the complexity can growth quickly if we have other related resources, so we can have:

  • /events/1/attendees
  • /events/1/attendees_and_organizer
  • /events/1/attendees_from_Rome

and so on. Usually we just add custom endpoints to efficiently satisfy the growing clients’ needs.

In GraphQL we can ask for all the informations in a sigle round trip.

We can ask for these informations from a simple query that is the shape of what we have received.

Even if GraphQL is relative new (became Open Source in 2015), there are a lot of big companies that use it. First of all Facebook that has invented it.

Let’s get started with a simple example. We are going to wrap some REST endpoints with GraphQL.

First of all, let’s install json-server that helps us to build a simple REST api server starting from a json file (obviously you can create your own API or use an already existing one). To do that we need to install a library that lets us make calls to our REST endpoints. To do that we install axios library:

npm install json-server axios — save

Create a script into package.json that launches our json server with our data:

...
"scripts": {
"dev:server": "nodemon server.js",
"json:server": "json-server --watch persistence/db.json"
},
...

after that we can create a simple json file with the data we want to provide and launch json-server watching on that file.

In my project I’ve created a persistence/db.json file, like this:

Simple “database” data for json-server REST API Server

now we can run (from our root directory) :

npm json:server

With your browser you can point now to http://localhost:30000/events and you will obtain something like this:

You can also check that we can call http://localhost:3000/events/1 getting only the first event with the right id.

The next step is to call these endpoint through our GraphQL server with the help of the other library we have already installed, called axios.

First of all we need to install express, graphql, express-graphql modules

npm install express graphql express-graphql --save

To create our server we need to require express and express-graphql modules, and then use them.

Like you can see, the express server use our expressGraphQL module with an object that is useful to configure it :

app.use('/graphql', expressGraphQL({    
schema: schema,
graphiql: true
}))

The object that configure our expressGraphQL contains two attribute (there are many other attributes but we will not use them):

  • schema: define the GraphQLSchema of our APIs
  • graphiql: It’s a web, graphic interface to test our endpoints. In development mode is quite useful.

The previous schema, like you can see in the code below, corresponds to the exported RootQuery of GraphQL that is the entry point of our server.

To build the shape of our endpoints we need to define the RootQuery, that is the exposed list of endpoints that we can call from a client (or from another server). To copy the REST API saw before, we define two fields:

  • event: define “the shape” of the response for a single event
  • events: define the list of events

Like you can see the field is defined with:

  • type: that define the returned type of the endpoint
  • args: that allow us to list the arguments we can use to filter the returned values.
  • resolve: that is the function that allow us to define the logic to return the values requested to the caller.

The rest of the code is self explanatory, like exposed below.

You can see the use of axios library to call our REST API exposed with our json-server.

To test it with your browser you can simply go to http://localhost:4000/http://localhost:4000/graphql, where you can find the previous mentioned GraphiQL tool.

In this web tool you can write your requests on the left side of the page (with autocompletion) and find the responses to the center of it. You should note that to the right you can find the Documentations that are created for us automatically.

In the next posts we will see the mutations (that are a way to write data on our server) and some other features of GraphQL

Here https://github.com/danilodelfio/node-graphql-events you can find the repo for this example.

Danilo Del Fio

Written by

Crazy developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade