Introduction to GraphQL for Developers

Introduction to GraphQL for Developers

GraphQL is a powerful query language for APIs and a runtime for resolving queries with data. In this article, we’ll explore GraphQL’s story and core features.

GraphQL stands for “Graph Query Language,” but unlike other query languages like SQL (Structured Query Language), It is not a language for talking directly with a database. Rather, it establishes a contract via which a client interacts with an API server.

There is no official GraphQL implementation because the language is specified under an open standard.

As long as it adheres to the specifications specified in the specification, a GraphQL implementation can be created in any programming language, integrated with any kind of database, and supported by any client (including mobile and online applications).

The most well-known commercial GraphQL implementation is Apollo GraphQL, which boasts a number of GraphQL client and server implementations. However, using Apollo is not required to use or comprehend GraphQL.

The Story of GraphQL

These days, REST seems to be the standard method for creating APIs, usually based on the well-known HTTP protocol. Despite being widely used and reasonably easy to use, REST occasionally lacks flexibility because it uses numerous endpoints to address resources.

With such a strict methodology, some clients will over-fetch (get more data than they actually need), while others won’t receive enough data from a single endpoint (under-fetching). This is a typical problem with endpoint-based APIs, such as REST, and API clients must make accommodations for it. For instance, they may make several requests or perform the necessary client-side data preparation work.

However, clients can use GraphQL to just request the data they require — no more, no less — similar to querying particular database columns. When Facebook was redesigning its mobile apps and in need of a data-fetching solution that was suitable for low-resource devices, they created GraphQL. In 2018, it was transferred to the GraphQL Foundation after being open-sourced in 2015.

Features of GraphQL

REST and GraphQL are similar in certain ways. Through a request-response protocol, often implemented on top of HTTP, it enables clients to make data requests to and manage data from APIs. However, there are significant differences in the manner that data is arranged, sought, and provided.

GraphQL provides the following operations to work with data, via a single endpoint:

  • Queries: Allow clients to request data (similar to a GET request in REST).

  • Mutations: Allow clients to manipulate data (i.e., create, update, or delete, similar to POST, PUT, or DELETE, respectively).

  • Subscriptions: Allow clients to subscribe to real-time updates.

Features of GraphQL

Therefore, at the surface, GraphQL can cover your typical API requirements. Do not be misled by the “QL” into thinking that it’s used just for data retrieval.

Queries

You can use the information in the API docs to create your first query:

query {
  humans {
    id
    name
  }
}

This humans query gives us a list of entities, which are of type Human, and we list the fields we want returned inside the inner curly brackets. In this case we're specifying that we want id and name, but we could also have returned any combination of fields supported by the Human type. This returns the following output:

{
  "data": {
    "humans": [
      {
        "id": "1000",
        "name": "Luke Skywalker"
      },
      {
        "id": "1001",
        "name": "Darth Vader"
      },
      {
        "id": "1002",
        "name": "Han Solo"
      },
      {
        "id": "1003",
        "name": "Leia Organa"
      },
      {
        "id": "1004",
        "name": "Wilhuff Tarkin"
      }
    ]
  }
}

If we wanted to get specific information about one of these humans, we could use the human query, passing in the specific id value as an input to the query, as shown below:

query {
  human (id: 1001) {
    homePlanet
  }
}

Again, the data we get back in the response corresponds to the fields we requested, as shown below:

{
  "data": {
    "human": {
      "homePlanet": "Tatooine"
    }
  }
}

You can add other fields that you want returned, which you can discover by examining the aforementioned API and schema documentation, or simply by seeing the suggestions in GraphQL Playground as you type. Let's try a slightly bigger query:

query {
  human(id: 1001) {
    homePlanet
    name
    appearsIn
    starships {
      id
    name
    }
  }
}

This is a little more interesting because it also queries related data, in this case a starships field, in which we are arbitrarily retrieving the id and name of a list of starships (entities of type Starship). The response for this query is:

{
  "data": {
    "human": {
      "homePlanet": "Tatooine",
      "name": "Darth Vader",
      "appearsIn": [
        "NEWHOPE",
        "EMPIRE",
        "JEDI"
      ],
      "starships": [
        {
          "id": "3002",
          "name": "TIE Advanced x1"
        }
      ]
    }
  }
}

While there is a lot more to be said about querying GraphQL APIs, these simple examples demonstrate how easy it is to consume a GraphQL API. With a single API, it's possible to serve a wide variety of clients with very different needs. For example, a mobile client might want to request only a subset of the data that a web app would need.

Mutations and Subscriptions

GraphQL can do more than just query data. The Star Wars example we're using provides one mutation example (adding a review) and one subscription example (getting notified when a review is added). Let's go back to GraphQL Playground and execute the following to start a subscription:

subscription {
  reviewAdded {
    episode
    stars
    commentary
  }
}

What this does is to wait for updates related to a review being added, and when they're available, it returns the episode, stars, and commentary fields. Just as with queries, we choose what data we're interested in receiving. Since we can't continue writing queries while listening on a subscription, we can simply open a new tab in GraphQL Playground and execute the following mutation:

mutation {
  createReview(episode: NEWHOPE, review: {
    stars: 5,
    commentary: "Awesome"
  }) {
    episode
    stars
    commentary
  }
}

As with queries, the inputs are in the round brackets (including a non-trivial review object in this case), and the outputs are listed in curly brackets. In this particular example, the inputs and outputs are the same, which is not very useful; however, the output of a mutation can be used to retrieve information about a newly added entity, such as an identifier. The result of this mutation is the following:

{
  "data": {
    "createReview": {
      "episode": "NEWHOPE",
      "stars": 5,
      "commentary": "Awesome"
    }
  }
}

Whether you want clients to query data, manipulate it, or receive real-time updates, GraphQL has you covered. It also offers a lot more functionality that we haven't covered, so please check the Queries and Mutations documentation to learn more about the available features.

References

Introduction to GraphQL GraphQL Best Practices

Follow me on GitHub: MadhushaPrasad

example repo with express-graphQL