API Gateway
8 min read

What is GraphQL?

Have you ever worked on app development projects before? If so, then chances are that you have come across the term “GraphQL.” However, what exactly does it entail? Is it utilized in server or client-side configuration? Furthermore, when would Integration of GraphQL be preferred over other alternatives? In this guide, we will provide insight into all these inquiries whilst highlighting its benefits.

Primarily known for being an open-source API query language, GraphQL has rapidly evolved to become an essential element of application programming interface (API) design involving numerous advantages such as greater flexibility and efficiency during coding pipelines. Enabling developers to efficiently communicate between clients’ browsers/devices and the server effectively enables rapid execution of web features ensuring swiftness in developing apps as well as enhancing the applications thorough functionally. This text aims to provide a comprehensive overview of GraphQL, including its definition, operational mechanics, examples and use cases, as well as benefits.

What is GraphQL?

GraphQL is both an API type (or query language) and a runtime engine for responding to those queries. It provides a streamlined API ideal for mobile applications and implementations with complex schemas where only certain data subsets are required.

With GraphQL, developers can specify the data they want to fetch from an API. It also allows for fetching data on demand rather than all at once, apply changes immediately, and integrate third-party sources of data into an application.

Applications can call GraphQL services using GraphQL queries. These queries will return the exact data elements the client requests — nothing more or less. This saves multiple API calls, network bandwidth, and post-processing. For data-centric APIs and APIs sitting right at the edge close to consuming devices, like mobile phones and tablets, it’s an incredibly efficient solution.

The history of GraphQL

Created by Meta when the company was building the Facebook mobile app back in 2012 (and open sourced in 2015), GraphQL was designed to address some of the shortcomings of REST.

GraphQL adoption continues to increase today. It’s a solid choice for organizations looking to make their dispersed data easily available through APIs. Not surprisingly, big names like GitHub, PayPal, Shopify, Netflix, and Facebook use GraphQL.

Does GraphQL replace REST?

While REST remains the dominant method for API access, it cannot be replaced by GraphQL.

This is because REST is an architecture framework for constructing APIs while GraphQL functions as both a runtime engine and query language. Essentially, HTTP requests are used to interact with REST APIs while clients use URLs to consume API services provided by the server-side runtime engine in GraphQL.

When executing a query, the GraphQL API leverages several data sources simultaneously, including REST APIs, databases, and microservices. Concealing the disparate origins of the requested information, the server presents the data via a single API. A key difference from conventional query languages is that GraphQL permits accessing information across multiple segments in one call.

GraphQL use cases

Mobile and web apps

GraphQL brings efficiency and power to mobile and web applications. (After all, that’s Meta made it to build their mobile app.) By offering a single endpoint to query data without multiple requests to the server, GraphQL can mean reduced loading times and better user experiences.

Real-time dashboards and data aggregation

Interested in monitoring your data as it changes? Utilizing GraphQL to create real-time dashboard applications can offer a solution for keeping up with constantly evolving data sets. Implementing GraphQL also facilitates the integration of multiple data sources into one streamlined view, facilitating better overall analysis.

API aggregation and versioning

GraphQL can be used to combine multiple APIs into a single GraphQL endpoint. This makes it easier to keep track of the different versions of the APIs and provides a way to version the data.

Data caching

GraphQL can be used to cache data on the client side to accelerate loading times.

How does GraphQL work?

GraphQL was designed to address two requirements:

  1. That data returned by a source needs to fit exactly what the client is looking for
  2. That the design of an API or data source shouldn’t dictate the way the client consumes the data

To satisfy these requirements, a GraphQL service defines a schema.

Schemas, fields, types, and resolvers

A GraphQL schema describes the data clients can request from the GraphQL API. It encompasses all the possible data that the client may want the query to return. Ideally, this schema will be represented in the form of a Schema Definition Language (SDL) to make it more readable.

The schema comprises object types that define what kind of objects the queries will be able to access and the fields within those objects. For example, the snippet below shows the schema of a GraphQL query.

`type query {
    teacher
    students {
      name
    }
  }
}`

You can see that the schema has two fields, teacher and students.

If an application wanted to access the names of the students and their teachers from a traditional REST API, it would run a query against the API URL, and the API might return the teacher name, number of students in the class, the class subject, the student names, and student ages.

In other words, the client would have more data than it needed. However, if this schema was defined at the GraphQL service and the application ran the query, then the application would get only what it wanted: the students’ and their teacher’s names. The output may look something like this:

`{
   "data": {
     "teacher”: "Joe Bloggs",
     "students": [
       {
         "name": "Jane Doe"
       },
       {
         "name": "Joe Smith"
       },
       …
    ]
  }
}`

Each field within the object type will have a type of its own. A field’s type can be another object type or a scalar type like String, ID, Boolean, Int, or Float.

For example, the schema for the class object can be defined like this:

`type class {
  teacher: String
  student: [StudentName]
}

type StudentName{
  name: String
}`

Each field in the schema will then be attached to a resolver. A resolver is a function that fetches the data for that field for GraphQL queries. The GraphQL query engine compares every query against the schema during runtime to validate the query. If the query is valid, then the query engine runs each field’s resolver to fetch the data for that field.

GraphQL operations

As we keep talking about GraphQL queries reading data, it may seem that this is the only allowable operation type. This is not the case. A GraphQL client can request one of two types of operations: a query or a mutation.

GraphQL query

A GraphQL query is similar to a REST API’s GET method. This is what we have been talking about so far—this operation accesses data.

GraphQL mutation

A mutation is a request to add or modify data. This is similar to the REST API’s POST, PUT, PATCH, or DELETE methods.

GraphQL subscriptions

GraphQL subscriptions represent a powerful mechanism to receive real-time data from servers even without requesting it. With this tool, clients can receive notifications about changes or deletions in the database, eventually receiving a stream of updates regarding their related queries’ statuses. The way it works is by allowing the subscribing client to choose what events they are interested in and specify how data should be sent every time that event happens. Unlike GraphQL queries or mutation requests that rely on short-lived HTTP connections with servers, subscription requires clients to establish long-running bi-directional communication channels via WebSocket.

Once this connection is set up, clients can send their subscription queries to servers using it

GraphQL vs REST

REST (short for Representational State Transfer) APIs are widely used, but that doesn’t mean they’re best for every situation. GraphQL offers a more customizable alternative. And in the right use cases, it can prove the more efficient choice.

REST requires coordination between services authors and clients with a custom API for each screen. But with GraphQL, app developers say the data they need, service developers detail the data they can share, and the two are matched together.

However, the tried-and-true REST may be the best option for an application if you don’t have a compelling reason to look at GraphQL or gRPC.

Here are some other high-level differences between REST vs GraphQL.

  • GraphQL allows for much greater query flexibility than REST.
  • Data fetching with REST can require multiple trips between server and client, while GraphQL is done in a single trip (making it a potentially better fit for mobile apps or in use cases where bandwidth is a concern).
  • REST offers strong support for caching, while GraphQL does not — though third-party GraphQL libraries can help with this.
  • The learning curve for GraphQL is steep (teams may need a GraphQL tutorial and time to ramp up) compared to REST, which is easy to understand for those comfortable with HTTP and client-server architecture.
  • GraphQL is self-documenting through schema while REST is not.
  • GraphQL can require more work on the backend that REST but can make APIs easier to consume.
  • REST supports file uploading while GraphQL does not.

Benefits of GraphQL

Broad benefits of GraphQL include increased flexibility, consistency, and security and reduced bandwidth and complexity. Let’s take a deeper dive into some of its ideal uses and benefits.

No over-fetching or under-fetching

GraphQL’s principal benefit is its ability to present only the requested data, allowing for minimal over-fetching when compared to REST queries. When using REST and querying a single endpoint, there may be an abundance of extraneous information, whereas with GraphQL it’s easier to retrieve specific data. Additionally, if necessary data isn’t available from one source, REST requires multiple API calls which equates to under-fetching from any given location.

By specifying a schema, GraphQL resolves the aforementioned dilemmas by providing a precise roadmap that limits what data elements can be queried and returned.

Low network footprint

Getting a specific set of data each time also ensures GraphQL queries work with significantly smaller payloads than those received with over-fetching.

Also, as GraphQL queries don’t have to send multiple requests to multiple resources, there’s less network traffic. This is beneficial for distributed applications accessing one another over geographically separate networks.

HTTP/HTTPS protocols

GraphQL queries can use HTTP/HTTPS protocols for accessing the APIs. This means you don’t have to cater to new communication methods when designing your applications.

Evolving APIs

GraphQL APIs allow for progressive enhancement of the schema without disrupting queries. Like REST APIs, you can version a GraphQL API. However, unlike REST APIs, they provide a way to upgrade your schema continuously. Since only requested data elements return for each query, adding objects or fields will not break existing client requests. To incorporate new fields and objects, create additional queries.

Strongly typed schema

GraphQL schemas and their object types are defined in a hierarchical and declarative manner. This helps developers understand the relationship between data elements (such as the “Graph”) and fine-tune the query structure.

Also, the schemas and objects are strongly typed. The GraphQL runtime engine ensures the query is both syntactically accurate and its types match the requested schema’s fields and object types.

If there’s a mismatch, then the service returns an error message. Having strongly typed and well-defined schemas mean query behaviors are more predictable, and errors are easily detectable.

Rich set of tools

GraphQL boasts a vibrant ecosystem of development and testing tools. Some of these tools are open source, making them much easier to develop. Popular GraphQL tools include Apollo, Graphback, GraphiQL, GraphQL Playground, and GraphQL Explorer.

Conclusion

GraphQL is an alternative to REST. It lets developers declaratively define the data to be fetched from a server. Benefits of GraphQL over traditional REST APIs, include improved performance and efficiency while allowing clients to request only the data they need for their applications.