Unified APIs and Federated Gateways – Part 3: GraphQL, GraphQL Mesh, Federated Gateways

Continuing on the post series on Unified APIs and Federated Gateways.

GraphQL vs REST

GraphQL is a specification, a query language, while REST is an architectural concept for network-based software. Both aim to allow you to involve sending an HTTP request and receiving some result. You can use them separately and together in combination. This section is heavily based on: https://www.apollographql.com/blog/graphql/basics/graphql-vs-rest/



With REST the type, or shape, of the resource and the way you fetch that resource are coupled.

// GET /books/1 

  "title": "Black Hole Blues",
  "author": { 
    "firstName": "Janna",
    "lastName": "Levin"
  // ... more fields here

In the example above you have a GET HTTP method with a /books endpoint.

So with GraphQL you have your data type/schema separate from the query aspect, how you fetch you data.

type Book {
  id: ID
  title: String
  published: Date
  price: String
  author: Author

type Author {
  id: ID
  firstName: String
  lastName: String
  books: [Book]

In the above example the data is described but not how or what you want from it this can be done separately by creating a query type:

type Query {
  book(id: ID!): Book
  author(id: ID!): Author

Then you make an actualy REST request:

// GET /graphql?query={ book(id: "1") { title, author { firstName } } }

  "title": "Black Hole Blues",
  "author": {
    "firstName": "Janna",

Things to notice:

  • You are querying only the fields/data you need
  • You don’t need the server to tell you what to get
  • Different identities/resources are not coupled with multiple ways of retrieving them

Similar: Both have the idea of a resource, and can specify IDs for those resources.

Similar: Both can be fetched via an HTTP GET request with a URL.

Similar: Both can return JSON data in the request.

Different: In REST, the endpoint you call is the identity of that object. In GraphQL, the identity is separate from how you fetch it.

Different: In REST, the shape and size of the resource is determined by the server. In GraphQL, the server declares what resources are available, and the client asks for what it needs at the time.


URL Routes vs GraphQL Schema

In REST, the space of accessible data is described as a linear list of endpoints, and in GraphQL it’s a schema with relationships.

Similar: The list of endpoints in a REST API is similar to the list of fields on the Query and Mutation types in a GraphQL API. They are both the entry points into the data.

Similar: Both have a way to differentiate if an API request is meant to read data or write it.

Different: In GraphQL, you can traverse from the entry point to related data, following relationships defined in the schema, in a single request. In REST, you have to call multiple endpoints to fetch related resources.

Different: In GraphQL, there’s no difference between the fields on the Query type and the fields on any other type, except that only the query type is accessible at the root of a query. For example, you can have arguments in any field in a query. In REST, there’s no first-class concept of a nested URL.

Different: In REST, you specify a write by changing the HTTP verb from GET to something else like POST. In GraphQL, you change a keyword in the query.


Rest endpoints:

GET /books/:id
GET /authors/:id
GET /books/:id/comments
POST /books/:id/comments

GraphQL Schema:

type Query {
  book(id: ID!): Book
  author(id: ID!): Author

type Mutation {
  addComment(input: AddCommentInput): Comment

type Book { ... }
type Author { ... }
type Comment { ... }
input AddCommentInput { ... }

Route Handlers vs. Resolvers

At the end of the day, both REST and GraphQL APIs are just fancy ways to call functions over a network. If you’re familiar with building a REST API, implementing a GraphQL API won’t feel too different. But GraphQL has a big leg up because it lets you call several related functions without multiple roundtrips.

Similar: Endpoints in REST and fields in GraphQL both end up calling functions on the server.

Similar: Both REST and GraphQL usually rely on frameworks and libraries to handle the nitty-gritty networking boilerplate.

Different: In REST, each request usually calls exactly one route handler function. In GraphQL, one query can call many resolvers to construct a nested response with multiple resources.

Different: In REST, you construct the shape of the response yourself. In GraphQL, the shape of the response is built up by the GraphQL execution library to match the shape of the query.


Other differences

  • Data fetching: REST suffers from over fetching and under fetching which leads too hard to design APIs, meaning getting too much or too little data.
  • Schema and Type Safety: GraphQL has a strongly typed data through schema definition.
  • Schema Stitching: GraphQL can combine multiple schemas into a single schema to be accessible by a client.

The core difference between GraphQL and REST APIs is that GraphQL is a specification, a query language, while REST is an architectural concept for network-based software.

GraphQL is great for being strongly typed, and self-documenting based on schema types and descriptions and integrates with code generator tools to reduce development time.

With GraphQL you have a greater control what you want to get, with REST you might have to adapt to what you get like a burger example below:

GraphQL Vs. REST APIs.png

Opting for GraphQL against or with REST is a highly subjective decision, heavily influenced by the use-case. It is important not to consider GraphQL as an alternative to REST, nor as a replacement. To help simplify that decision, here are some key differentiators:

A query language for solving common problems when integrating APIsAn architectural style largely viewed as a conventional standard for designing APIs
Deployed over HTTP using a single endpoint that provides the full capabilities of the exposed serviceDeployed over a set of URLs where each of them exposes a single resource
Uses a client-driven architectureUses a server-driven architecture
Lacks in-built caching mechanismUses caching automatically
No API versioning requiredSupports multiple API versions
Response output in JSONResponse output usually in XML, JSON, and YAML
Offers type-safety and auto-generated documentationDoesn’t offer type-safety or auto-generated documentation
Allows for schema stitching and remote data fetchingSimplifying work with multiple endpoints requires expensive custom middleware

Pros of using a REST API

REST is the industry standard. It has the most mature developer tooling and has been around since Roy Fielding presented it in 2000.

REST APIs use HTTP methods, making the implementation predictable for the client.

REST APIs support various data formats (XML, JSON, HTML, plain text, etc.).

REST allows data to be cacheable, which might improve performance and scalability.


Cons of using a REST API

As the representation is defined by the server, it’s complicated to customize the requests and bring only specific data. This can cause over-fetching: bringing data that we don’t need.

All the requests return one resource representation from a unique source.

Generally, we need multiple round trips to get all the needed data.


When to make REST APIs

Public APIs where we want to determine what to expose to the clients.

Simple applications that we don’t want to overcomplicate.


Pros of using GraphQL

One unique endpoint to query.

No over-fetching or under-fetching: As the client is responsible to define the data requirements, it won’t download more (or less) information than needed from the API.

Query one or more resources in the same request. This will avoid making multiple API calls for an operation.

Defining a type system and a GraphQL schema helps to understand what can be requested and returned from the server. After that, Frontend and Backend teams can work without depending on each other.

Extending APIs and adding functionality wouldn’t affect existing client GraphQL queries.

A growing and maturing ecosystem of tooling.


Cons of using GraphQL

GraphQL uses a single endpoint and custom requests, so caching is complicated.

Adding the support for custom queries to an API makes it more exposed to arbitrary requests.

Only supports JSON representation for responses.

GraphQL queries can become large. We have to specify everything we want to bring, and sometimes we are tempted to do a lot in one request.


When to use GraphQL

Applications where we usually need nested data to be fetched. i.e. blog posts with their comments and people details.

APIs that will be consumed by mobile devices, smartwatches, etc., where we need to limit bandwidth usage.

Apps that receive data from multiple APIs/sources. For example, bringing data from different analytics tools to display in a control panel.

When we want to handle different microservices.


GraphlQL Mesh

GraphQL Mesh allows you to create an API SDK or API Gateway for your system using GraphQL as the query language against many types of data sources. A good thing about this is that you can create a GraphQL representation of your API or database without touching your implementation. You only need to provide the API definitions or database schema in a format that is understood by the GraphQL Mesh.

GraphQL Mesh allows you to use GraphQL query language to access data in remote APIs that don’t run GraphQL (and also ones that do run GraphQL). It can be used as a gateway to other services, or run as a local GraphQL schema that aggregates data from remote APIs.

The goal of GraphQL Mesh is to simplify access to your data-sources, and use GraphQL language to query it easily. You can link, merge, aggregate, transform, modify and link your data-sources, and later query it using GraphQL queries.

You can use one of the handlers that we wrote (GraphQL, gRPC, Swagger, OpenAPI, SOAP, Postgres and more), or write your own handler to access your data.


How it works?

Collect API schema specifications from services

Create a runtime instance of fully-typed SDK for the services.

Convert API specs to GraphQL schema

Applies custom schema transformations and schema extensions

Creates fully-typed, single schema and GraphQL SDK to fetch data from your services.


Federated Gateway

Federated Gateway is similar to a Unified API, it’s actually the same on the feature level. In a federated gateway or federated architecture at the moment, you will be using GraphQL. Here are some key points:

  • Federated architecture brings different services together into one API endpoint.
  • Clients do not need to call each service separately, and they do not need to know anything about them. They only need to access one single point of access that hides the underlying complexity and takes care of the data requests without requiring clients to have deep server side knowledge.
  • With Federation, there is a separation of concerns, as different teams can independently work on specified portions of the graph simultaneously.
  • Quick to understand and implement by new engineers, who can work independently yet synchronously on different portions of the graph schema
  • Easier to modify with new features or bug fixes
  • Easier to scale and deploy
  • More manageable, thanks to less dependency and coupling between the different services
  • Incrementally adoptable
  • Helpful for companies with multiple teams that contribute to different portions of a single API or to enforce domain boundaries with separate services.

Notice: A federated gateway is different from scheme stitching with GraphQL.:

Schema stitching was the previous solution for microservice architecture. Both federation and schema stitching do offer the same functionality on the surface, gathering multiple services into one unified gateway, but the implementation is different.

With GraphQL federation, you tell the gateway where it needs to look for the different objects and what URLs they live at. The subgraphs provide metadata that the gateway uses to automatically stitch everything together. This is a low-maintenance approach that gives your team a lot of flexibility.

With schema stitching, you must define the “stitching” in the gateway yourself. Your team now has a separate service that needs to be altered, which limits flexibility. The use case for schema stitching is when your underlying services are not all GraphQL. Schema stitching allows you to create a gateway connected to a REST API, for example, while federation only works with GraphQL.

So when should you use either one? Many will say that federation is the overall winner, as it allows teams to focus on their application without needing to maintain a gateway. But if you have different types of APIs, you have to go with schema stitching.


Challenges with using GraphQL federation

The greatest difficulty in using federation is figuring out _when_ to use it. Many teams find it improves their infrastructure and increases performance. But that isn’t true in all cases.

For instance, does your frontend use many different endpoints to make a single piece of the application function? If so, then federation may be a good choice for you. If you only use one or two endpoints, then the extra complexity added by having to manage a gateway may not be worth it.

Federation requires extra infrastructure, and every new piece added brings more complexity. Also, you will need to work with your services a bit differently. Adding federation may be simple, but adding it effectively takes more work and time. You need to understand the new paradigm it offers and be sure your specific infrastructure can take advantage of it.


Design and implementation

Implementing a federated graph architecture involves:

The different graph servers or schemas

A gateway that unifies these different graph schemas and composes them into one graph API endpoint


The gateway has a query planner. The query plan panel is visible on the GraphQL Playground, where we can see see how the gateway is executing all requests. When clients send their requests via the gateway, it splits these queries into smaller chunks or sub-queries that walk through each of these graph schemas. The gateway layer already understands the interrelationships between these services, as we have previously discussed.

Basically, the query planner helps in planning and executing the query over all the graph schemas, then composes them into one API endpoint for the client to query. Additionally, there is a graph manager, which helps with tracking a schema’s full history and usage.


Apollo GraphQL Gateway

Apollo GraphQL Gateway is a federated gateway solution that is based on JavaScript, it seems to have support for Kotlin and Java. It’s architecture involves subgraphs and a gateway that combines these subgraphs. It also provides different tools and features that can be used for your gateway.

Netflix Federated Gateway

The Netfilx Federated Gateway is an interesting solution which I recommend reading. In summary is does the things described above on Federated Gateways and what Apollo Gateway does with some twists. It consists of three aspects:

Studio Edge Architecture Diagram
  • Domain Graph Service (DGS): Each service has this and is responsible for creating a schema and pushing it to the Scheme Registry.
  • Schema Registry: Holds and passes on the combined schemas from the DGS to the Gateway.
  • GraphQL Gateway: Client gateway for queries and distributing the queries to the right locations.

Other important aspects are:

  • Schema Composition
  • Query Planning and Execution
  • Entity Resolver
  • Security
  • Monitoring
  • Failure Tolerance

This is based on Java and Spring Boot, so you are tied to these technologies, at least at the moment.



Sources for this blog post



















2 thoughts on “Unified APIs and Federated Gateways – Part 3: GraphQL, GraphQL Mesh, Federated Gateways

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.