DEV Community

Omar Bahareth
Omar Bahareth

Posted on

A Quick Dive Into GraphQL, Part 1: Building a GraphQL API

What is GraphQL?

“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.

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, and you can see a full list showing who’s using it 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:

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 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.

{
  # 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

{
  "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

Gatsby is a new framework that’s rapidly rising in popularity (and very well documented), it’s static PWA (Progressive WebApp) generator that lets you build websites using React, 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? You want to fetch cards, boards, or lists from 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

Hasura 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

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 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 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 (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, because it has similar features to GraphiQL.

Where do I get started?

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”.

Oldest comments (0)