DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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โ€.

Top comments (0)

๐ŸŒš Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. ๐ŸŒˆ