A Quick Dive Into GraphQL, Part 1: Building a GraphQL API
Tags: api, rest, webdev, backend
Published: 2018-11-16 12:27:52

---
title: A Quick Dive Into GraphQL, Part 1: Building a GraphQL API
published: true
description: GraphQL is a query language for your API that makes it easy to fetch many resources in a single request.
tags: API, REST, Web Development, Backend
---

## What is [GraphQL](https://graphql.org/)?
> “A query language for your API.”

Think of it as being able to send queries to an API endpoint to fetch exactly what you want, rather than the traditional REST way of having many endpoints per resource. The way that it personally clicked for me is thinking of it as

Take a look at this example from the GraphQL website to get an idea of how it works.


![](https://thepracticaldev.s3.amazonaws.com/i/6udeov2333yh7dkyem3c.gif)*request (GraphQL Query) is at the top, response is at the bottom*

As an API provider, GraphQL lets you do this by letting you define a schema and how to fetch the resources in it.

As an API consumer, all you have to do is build the query to fetch exactly what you need.

## Who is using it?

GraphQL just got [its own foundation](https://gql.foundation/), and you can see a full list showing [who’s using it](https://graphql.org/users/) from their website. Below are some notable articles from companies who’ve used GraphQL where they explain why they used it and their experiences with it:

* [GraphQL: A success story for PayPal Checkout](https://medium.com/paypal-engineering/graphql-a-success-story-for-paypal-checkout-3482f724fb53).

* [The GitHub GraphQL API](https://githubengineering.com/the-github-graphql-api/).

## Use cases
> “Ask for what you need, get exactly that.”

Sometimes you just want to get a person’s name, other times you want to get the person along with his name and date of birth.
> “Get many resources in a single request.”

Other times you might want to get the person, their home town, along with their friends and their home towns too. With other solutions, you’d usually either have to make different routes for each case, or write a way to request specific parameters yourself.

I see these two features as extremely useful for the frontend web development (particularly with frameworks like React, Vue, Angular, etc.) and mobile apps.

Another more advanced feature that I’ll cover in a later post is stitching, which lets you combine multiple schemas (from different APIs) into one; meaning you can fetch resources from different APIs with a single request.

## Consuming a GraphQL API

There’s a GraphQL “IDE” that you can use to explore GraphQL APIs called GraphiQL. They have a [demo playground here](https://graphql.github.io/swapi-graphql/?query=%7B%0A%20%20%23%20The%20first%202%20films%2C%20after%20a%20given%20cursor%20value%0A%20%20allFilms(first%3A%202%2C%20after%3A%20%22YXJyYXljb25uZWN0aW9uOjA%3D%22)%20%7B%0A%20%20%20%20%0A%20%20%20%20%23%20An%20edge%20is%20an%20entry%20in%20a%20%22list%22%0A%20%20%20%20edges%20%7B%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20%23%20Get%20a%20cursor%20value%20for%20each%20%22edge%22%0A%20%20%20%20%20%20%23%20Used%20for%20pagination%2C%20in%20combination%20with%20filters%20like%0A%20%20%20%20%20%20%23%20before%20and%20after.%0A%20%20%20%20%20%20cursor%0A%0A%20%20%20%20%20%20%23%20Each%20edge%20has%20a%20node%2C%20where%20the%20node%20usually%20has%0A%20%20%20%20%20%20%23%20the%20data%20we%27re%20interested%20in%0A%20%20%20%20%20%20node%20%7B%0A%20%20%20%20%20%20%20%20%23%20Film%20title%2C%20releae%20date%2C%20and%20director%0A%20%20%20%20%20%20%20%20title%0A%20%20%20%20%20%20%20%20releaseDate%0A%20%20%20%20%20%20%20%20director%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%23%20The%20first%202%20species%20that%20appeared%20in%20this%20film%0A%20%20%20%20%20%20%20%20speciesConnection(first%3A%202)%20%7B%0A%20%20%20%20%20%20%20%20%20%20edges%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20node%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20The%20name%20of%20the%20species%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20name%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%7D%20%20%20%20%20%20%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D) with Star Wars films info that I used to construct the next example. The real cool thing about GraphiQL is that you can just keep hitting CTRL + Space like you would in any IDE, and you’ll get intelligent autocomplete. If you’re currently within a block related to films, you’ll see film fields that you can query for. This really helps explore and try out GraphQL APIs quickly and easily. Here’s an example query that shows some of the power of GraphQL.

```graphql
{
  # The first 2 films, after a given cursor value
  allFilms(first: 2, after: "YXJyYXljb25uZWN0aW9uOjA=") {

    # An edge is an entry in a "list"
    edges {

      # Get a cursor value for each "edge"
      # Used for pagination, in combination with filters like
      # before and after.
      cursor

      # Each edge has a node, where the node has
      # the data we're interested in
      node {
        # Film title, release date, and director
        title
        releaseDate
        director

        # The first 2 species that appeared in this film
        speciesConnection(first: 2) {
          edges {
            node {
              # The name of the species
              name
            }
          }
        }
      }
    }
  }
}
```

This query gets the first 2 films (after a specific film’s cursor value) with their title, release date, and director. It also gets the names of the first 2 species that appeared in this film. We just fetched multiple resources with a single request.

Here’s what the result looks like

```json
{
  "data": {
    "allFilms": {
      "edges": [
        {
          "cursor": "YXJyYXljb25uZWN0aW9uOjE=",
          "node": {
            "title": "The Empire Strikes Back",
            "releaseDate": "1980-05-17",
            "director": "Irvin Kershner",
            "speciesConnection": {
              "edges": [
                {
                  "node": {
                    "name": "Human"
                  }
                },
                {
                  "node": {
                    "name": "Droid"
                  }
                }
              ]
            }
          }
        },
        {
          "cursor": "YXJyYXljb25uZWN0aW9uOjI=",
          "node": {
            "title": "Return of the Jedi",
            "releaseDate": "1983-05-25",
            "director": "Richard Marquand",
            "speciesConnection": {
              "edges": [
                {
                  "node": {
                    "name": "Human"
                  }
                },
                {
                  "node": {
                    "name": "Droid"
                  }
                }
              ]
            }
          }
        }
      ]
    }
  }
}
```

## Services and Tools

**[Gatsby](https://www.gatsbyjs.org/)**

[Gatsby](https://www.gatsbyjs.org/) is a new framework that’s rapidly rising in popularity (and very well documented), it’s static PWA ([Progressive WebApp](https://developers.google.com/web/progressive-web-apps/)) generator that lets you build websites using [React](https://reactjs.org/), and fetch data using GraphQL. Even though you’re deploying “static” files, you can build e-commerce solutions and CMS and just do a whole lot of stuff that you might not think is possible with a static website.

Gatsby abstracts things away via GraphQL. You want to [fetch a file from your disk](https://www.gatsbyjs.org/packages/gatsby-source-filesystem/?=filesystem)? You want to [fetch cards, boards, or lists from Trello](https://www.gatsbyjs.org/packages/gatsby-source-trello/?=trello)? You can do all of that just by sending GraphQL queries; usually through existing plugins that have already built the GraphQL API for you. It even comes with the GraphiQL IDE mentioned above and you can try fetching live data instantly, before you write even a single line of code.

I’ve personally had a very rapid and rich development experience with Gatsby; especially when interacting with the community, but I did struggle with one thing: localization. Localization can mean different things depending on who you ask. It could be just translating strings, different routes per locale, or a whole lot more. In my case I wanted to translate strings and style content differently (right to left, for Arabic) and while I always found a “Gatsby way” of doing things, this was on area where I had to fiddle around a lot but I did end up having something that worked well after some trial and error.

**[Hasura](https://hasura.io/)**

[Hasura](https://hasura.io) instantly and “automagically” builds a GraphQL API out of your PostgreSQL database (you can quickly choose what is exposed through the API and who has access to it); which was of course a very logical development, since both SQL and GraphQL use schemas. Hasura even goes beyondjust making a GraphQl API for you, it provides subscriptions to database changes, live queries, triggers when database changes happen, and a whole lot more.

**[Apollo](https://www.apollographql.com/)**

Apollo is probably one of the friendliest ways to deal with or adopt GraphQL. In the past, they used to offer a client (React, JS, iOS, and Android), engine (for tracing and error tracking), and a server that helped you incrementally adopt GraphQL (even tools to help translate your REST API to GraphQL). Their offerings have great DX and they have [dev tools](https://github.com/apollographql/apollo-client-devtools) and plugins for most editors, and all ofthat is open source. It really feels like they’re covering the GraphQL experience from A to Z.

They recently [launched the Apollo Platform](https://blog.apollographql.com/introducing-the-apollo-graphql-platform-8ef34bb269e5) which combines their open source tools with cloud services

## How do I use it?

I haven’t used GraphQL extensively yet, I’ve only used it in one of my projects, which is [a website](https://awesome-mena-conferences-and-meetups.netlify.com/) (work in progress) for listing tech conferences and meetups in the MENA region, and it’s built using Gatsby.

I also like to explore GraphQL APIs I come across using [Insomnia](https://insomnia.rest), because it has similar features to GraphiQL.

## Where do I get started?

* Official [Introduction to GraphQL](https://graphql.org/learn/)

* [Libraries for clients](https://graphql.org/code/#graphql-clients).

* [Awesome GraphQL](https://github.com/chentsulin/awesome-graphql) - This is a great list that should help you find anything you’re looking for.

## Closing Notes

The comparison between GraphQL and REST is always made so I’ll briefly add my opinion here. I see them both as different tools in your toolbox. As always choose the right tools for your needs and use cases, and most importantly choose something you and your team are familiar and comfortable with, and areable to stay productive in.

**Stay tuned for the upcoming Part 2, “Building a GraphQL API”.**