DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. GraphQL :  Yet Another API Spec?  Part 1

GraphQL :  Yet Another API Spec?  Part 1

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

Mohanraj Karatadipalayam user avatar by
Mohanraj Karatadipalayam
CORE ·
Oct. 22, 18 · Tutorial
Like (5)
Save
Tweet
Share
9.97K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • 1st is https://api.github.com/users/userA/repos to get the user A repositories
  • 2nd is https://api.github.com/users/userA/following to get the user A followers
  • 3rd is https://api.github.com/users/userA1/repos to get User B repositories
  • 4th is https://api.github.com/users/userA2/repos to get User C repositories

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.

API GraphQL Repository (version control) Data (computing) Database

Published at DZone with permission of Mohanraj Karatadipalayam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Cloud-Native Application Networking
  • Using JSON Web Encryption (JWE)
  • The Data Leakage Nightmare in AI
  • Connecting Your Devs' Work to the Business

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: