Introducing GraphQL

Although REST has been a very popular way of server client API communication for the past years, it faces a strong challenge by a new API standard; GraphQL.

GraphQL provides a more efficient, powerful and flexible alternative to REST. Developed and later open sourced by Facebook, it is now maintained by a huge community of companies and dedicated individuals around the world.

GraphQL — API Query Language

Most client facing applications today, use some form of API communication to fetch data from a server where the data is stored in a database.

Client applications have evolved from being relatively simple static HTML pages to ultra dynamic, sophisticated, and complex websites using dedicated frameworks like ReactJS, AngularJS, and VueJS to name a few. All these frameworks rely heavily on REST APIs to expose data from a server.

Advantages

Strongly Typed Schema

One of the biggest problems surrounding REST API platforms, is the lack of strong contracts for what their operations look like. Unmaintained and deprecated API documentation and unannounced API upgrades make the developers lives difficult consuming the API.

To solve this issue, GraphQL uses a ‘schema’ for every API. The schema will clearly define the operations — queries, mutations, and subscriptions supported by the API including arguments and responses. Schemas are written in Schema Definition Language(SDL) and is strongly typed. Using SDL also allows auto generating API documentation, eliminating the need to write documentation manually.

An example of a ‘User’ model using SDL would look like:

type User {
id: ID!
name: String
email: String! @unique
password: String!
}

Over-fetching and Under-fetching

A common problem with which both frontend developers and security consultants are familiar with is over-fetching data from the REST API. In complicated use cases with multiple nest and eager queries there is a chance that the backend developer sends data thats not required by the client or data that is sensitive and should not be sent out to the client. Conversely, under-fetching is when data send by the API is inadequate and the client needs to trigger another API to get the data it needs. Under-fetching also introduces the N+1 requests issue, forcing the developer to make multiple calls to access a nested resource(refer to Fig1. for more info).

GraphQL solves this problem by allowing the developer to tailor the payloads from the API according to the client’s needs.

For example, if a client needs only the name of a user described using the ‘User’ model above, the query would look like this:

query {
user(id: "abc") {
name
}
}

One Endpoint

Each resource in a REST API ideally requires a new endpoint. Consider the case of a simple blogging site with Users, Posts, and Followers. The image below describes the sequence in which the three APIs will be triggered if the client needs to display the posts and the followers of a particular user.

Fig 1: N+1 requests problem and multiple endpoints.

Whereas with GraphQL, the three different endpoints are replaced with a single endpoint, and query concretely defines the data. For example, using GraphQL for the REST example above, notice that the structure of the server’s response follows precisely the nested structure defined in the query.

Fig 2: Client specifies concrete data requirements, server follows.

GraphQL Architecture Strategies

GraphQL is quite flexible and can be used at multiple tiers of an application architecture. It can seamlessly integrate with existing or legacy systems and create totally new applications as well.

  1. GraphQL with a connected database

The simplest way to experiment and understand how GraphQL works is to use it use it with a connected database. Consider a web server implementing a GraphQL server. When a request arrives at this server, it simply fetches the data from the database, and resolves the request according to the request’s payload.

Fig 3: GraphQL with a connected Database

GraphQL is database agnostic, it doesn’t care about the database or the format that is used to store the data. Both SQL and No-SQL databases are compatible and based on the needs of the application, the implementation can be tailored.

2. GraphQL as a thin server layer connecting to existing systems

This approach essentially allows developers to integrate multiple systems(existing REST APIs, legacy systems) behind a single endpoint based GraphQL API layer. This applies to projects where there are several different APIs with multiple endpoints and tend to increase developer and project overhead as it grows.

Fig 4: GraphQL as a thin server layer connecting to existing systems

Introducing a GraphQL server to unify these existing systems and hide away the complexity behind a single endpoint GraphQL Rest API. Henceforth, Client applications can now simply talk to the GraphQL server to fetch the data they need. GraphQL with React.

3. Hybrid Approach

Fig 5: Hybrid Approach

Effectively combining the two approaches, GraphQL can be used as an API to serve that connects to a(multiple) database(s) and consumes other third party APIs.

4. GraphQL as a database abstraction layer

The easiest ways to realise the power of GraphQL is by using it as an abstraction layer between the server and the database. This approach can be compared to using an ORM such as Sequelize, or ObjectionJS(using Knex), to connect and fetch data from the database, but GraphQL adds a lot more value compared to using an ORM.

With GraphQL, the structure of data to be fetched is available before-hand and the whole set can be requested in one payload. Compared to an Object Relationship Mapping library, GraphQL helps the developer understand the domain object relationship in a more human manner as opposed to a relational database schema.

Having a defined payload structure upfront also reduces over-fetching.

Fig 6: GraphQL as a database abstraction layer

GraphQL Integrations Patterns

Client Side

Frontend developers today are overloaded with the tasks of handling local state, managing how to locally cache and consume data while keeping the website responsive and conforming to set SLAs. Ideally the developer should be doing the job in just two steps:

  1. Describing the data a view needs
  2. Displaying the data according to design

GraphQL is particularly useful for frontend developers allowing them to build the website without completely understanding the complete database schema or the complex domain object models of a large application and cutting out the unnecessary overheads that frameworks like React, Angular, and Vue add.

There are two major GraphQL clients available at the moment. The first one is Apollo Client, which is a community-driven effort to build a powerful and flexible GraphQL client for all major development platforms. The second one is called Relay and it is Facebook’s homegrown GraphQL client.

Relay is heavily optimised for performance and tries to reduce network traffic where possible. An interesting side-note is that Relay itself actually started out as a routing framework that eventually got combined with data loading responsibilities. It thus evolved into a powerful data management solution that can be used in JavaScript apps to interface with GraphQL APIs.

The performance benefits of Relay come at the cost of a notable learning curve. Relay is a pretty complex framework and understanding all its bits and pieces does require some time to really get into it.

Apollo Client is a community-driven effort to build an easy-to-understand, flexible and powerful GraphQL client. Right now there is a JavaScript client with bindings for popular frameworks like React, Angular, Ember or Vue as well as early versions of iOS and Android clients. Apollo is production-ready and has handy features like caching, optimistic UI, subscription support and many more.

Server Side

Although majorly ‘sold’ as a frontend technology, the GraphQL API needs to be implemented on the server side. Let’s take a look at the popular frameworks and tools available today to get started with GraphQL API.

Prisma

The Prisma client is compatible with the Apollo ecosystem, has default support for GraphQL subscriptions and Relay-style pagination, provides end-to-end type safety and comes with a built-in dataloader to solve the N+1 problem.

Fig 7: Prisma Client and Prisma Server

Prisma Client and Server are available as part of Prisma Cloud and are completely open-source and hence are available for use as standalone infrastructure components.

Apollo-Server

Apollo Server can be used to quickly build a production-ready, self-documenting API for GraphQL clients, using data from any source.

Apollo Server implements a spec-compliant GraphQL server which can be queried from any GraphQL client, including Apollo Client, enabling:

  1. An easy start, so front-end and back-end developers can start fetching data quickly.
  2. Incremental adoption, allowing advanced features to be added when they’re needed.
  3. Universal compatibility with any data source, any build tool and any GraphQL client.
  4. Production readiness, and what you build in development works great in production.

Although GraphQL seems to the talk of developer town, but it still has a long way to go be able to replace REST APIs and existing frontend frameworks and tools popular today. With issues surrounding security, schema duplication, possible mismatch between client and server, it still has a long way to go, but it’s definitely here to stay.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store