Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

GraphQL :  Yet Another API Spec?  Part 1

DZone's Guide to

GraphQL :  Yet Another API Spec?  Part 1

Let's take a quick look at GraphQL as well as what it offers to native developers.

Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

What Does It Offer to Native Developers?

GraphQL is a specification created by Facebook and they have open sourced it a few years ago. The promise of this specification is it will ease the development experience of both front-end mobile app developers and the server side API developers.

In this post, let’s find out whether GraphQL is yet another specification?

Does it solve the shortcomings of the existing API specifications like REST?

I promise by end of this series, you will have a clear understanding of the need for GraphQL and how it changes the native developer experience.

We will use practical examples to understand the GraphQL and how it differs from REST. We will use GitHub API V4, which is based on GraphQL. Refer here for the original announcement of GitHub adopting GraphQL.

Simple Queries With Complex Answers

Problem Statement

We want to create a native app page that lists the top 3 of repositories for the given user and the lists top 3 repository names of users that given user is following.

Let’s say given username is user A, user A follows [user B, user C]

User repositories and following users info

Let’s try to get the needed information with REST APIs of GitHub i.e. https://api.github.com V3.

In order to accomplish the results we need, we will have to call at least four APIs

What Kind of Data Do Each of These API Calls Return?

You can use the postman to play with the APIs.

Type in the GET as https://api.github.com/users/{yourUserName}, substitute the {yourUserName} with your GitHub username

Sample User Data

1st API response — lists the user repositories and contains a lot of data, whereas we are interested only in repository names of the user A.

Have a look at the picture on your left, it is the much-simplified view of the sampledata that you will get when querying for the list of repositories

We are getting around 90 data elements, where we need only the name of the repository. That’s a lot of unwanted data.

Let’s check the 2nd Query, use Postman. Type in the GET as

https://api.github.com/users/{yourUserName}/following

2nd API response — lists the users that user A follows also have plenty of data we don’t need. Have a look at the sample data for the followers below:

Following users

Remember, we are interested in only the below information:

  • Top 3 repositories name of user A
  • Top 3 repositories name of the users that user A following

I am not listing the responses of repositories of user B and user C, it will be similar to the 1st API response — plenty of data we don’t need.

By this time, you may have realized that the data we are getting from APIs are:

  • Over fetching — we get way too much data than we need
  • Under fetching — we need to execute at least 4 queries to get the needed response, n+1 requests problem
  • No metadata about the data being served

Complex Queries With Simple Answers

Let’s try to retrieve the same information using GraphQL.

Note: If you are new to GraphQL & don’t understand the syntax, don’t worry you will understand that eventually as part of the series.

Querying in GraphQL

We will use the GraphQL tools to understand the introspection, open the GitHub GraphQL explorer, in this editor you need to authenticate yourself with your GitHub account. Follow this link, when you need more help.

Copy paste the following query in the top left-hand window of the GraphQL explorer:

query UserAndFollowersInfo ($login: String!) {
  user(login: $login) {
    repositories(first: 3, orderBy: {field: STARGAZERS, direction: DESC}) {
      nodes {
        repoName: name
        description
        repoUrl: url
      }
    }
    following(first:3){
      totalCount
      nodes{
        login
        name
        userUrl:url 
      }
      nodes {
        repositories(first: 3, orderBy: {field: STARGAZERS, direction: DESC}) {
          nodes {
            followerRepoName:name
            repoUrl: url
          }
        }
      }
    }

  }
}

For the parameters on the left-hand bottom side of the explorer, pass the data such as:

{"login": "typeyourloginnamehere"}

The response will look similar to the below example:

{
  "data": {
    "user": {
      "repositories": {
        "nodes": [
          { "name": "android-clean-code" },
          { "name": "androidcleancode-generator" },
          { "name": "rx-rekotlin-router-gh-example"}
         ]
      },
      "following": {
        "totalCount": 2,
        "nodes": [
          {
            "name": "user A",
            "repositories": {
              "nodes": [
                { "name": "repo 1" },
                { "name": "repo 2" },
                {  "name": "repo 3" }
              ]
            }
          },
          {
            "name": "user B",
            "repositories": {
              "nodes": [
                { "name": "repo 1" },
                { "name": "repo 2" },
                {  "name": "repo 3" }
              ]
            }
          }
        ]
      }
    }
  }
}
Things to be noted

No multiple server trips — in REST API, we need to call at least 4 times to accomplish the result.

You specify exactly what you need, no extra data, no over or under-fetching

Strongly Typed and Introspection

In the REST environment, we have a swagger editor that enables to understand the API.GraphQL provides a more intuitive tool that enables to introspect the API. We will use GitHub GraphQL explorer.

Let’s find out the other information that User type provides? Open the explorer and copy paste the below contents

query {
  __type(name: "User") {
    name
    kind
    description
    kind
    fields {
      name
      type {
        kind
        name
        description
        fields {
          name
        }
      }
    }
  }
}

Run the query, you should be able to introspect each type of the given API. Play with the tool, check other types such as Repositories.

By end of this exercise, I hope you will be able to appreciate the facts

  • Introspection — gives you clear data about the API
  • Clear specification of each element types — metadata about the endpoint is available for iterations

Strongly Typed

GraphQL schema is strongly typed, ensures querying APIs safer. Let’s understand with a practical example. Open the explorer and run the below query, this query will list the first five starred repositories.

query($login: String!) { 
  user(login: $login) {
    starredRepositories(first: 5) {
      edges {
        starredAt
        node {
          name 
          stargazers {
            totalCount
          }
        }
      }
    }
  }
}

For the parameters, pass your username such as

Now, try changing the line 3 text “starredRepositories(first: 5)” to string, such as “starredRepositories(first: “5”)”

Note the editor will show an error, still, run the query and see the results. you will see the error message similar to the below message.

{
  "data": null,
  "errors": [
    {
      "message": "Argument 'first' on Field 'starredRepositories' has an invalid value. Expected type 'Int'.",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ]
    }
  ]
}

The error message is super clear and very intuitive.

Single End Point vs. Multiple End Points

Unlike REST, GraphQL provides a single endpoint. The single endpoint provides you the nested data that spreads across multiple types. For example, in the previous query, we are able to query the user repositories and repositories of the users that given user follows as well in a single server trip.

So far, we have seen the querying in GraphQL. In the next post, we will explore more about the query and how we can use GraphQL in a native app.

Download A Buyer's Guide to Application and Data Integration, your one-stop-shop for research, checklists, and explanations for an application and data integration solution.

Topics:
graphql ,graphql api ,rest api ,developer experience ,developer advocate ,performance ,server performance ,integration ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}