Beyond REST: Running GraphQL queries in Contentful

Our latest Labs project, the cf-graphql library, enables Contentful users to generate schemas and query content in the GraphQL format. We are eager to learn about how REST and GraphQL interfaces fit into your tech stack and how the cf-graphql could be extended to support more specific scenarios.

On the face of it, there is nothing extraordinary about Facebook ads. Just like any other banner online, they use appealing images and catchy words to lure you away from the comfort of your social feed. But look closer, and what initially appeared to be a random ad turns out to be the result of an elaborate operation involving heavy data-crunching and a skillful use of social connections. The ad is shown to a particular demographics, targets your stated and implied interests, and highlights who among your friends likes the brand. Facebook – I have to admit – you had my curiosity, but now you have my attention!

NYTimes Facebook Ad

Consider for a moment all the information the Facebook app needs to process to place these ads into your social feed. For the ad itself, the app needs to know your interests, match those to the inventory of available campaigns, and pull in the right creative. For adding social context, the app needs to look up the list of your friends, analyze their likes, pick the ones who liked the advertised product and pull in their full names to be displayed next to the ad. Assembling all this data into one place requires multiple round trips to the server, which risks making the social feed slow and unresponsive. This is especially true for mobile applications where network conditions are variable, and multiple round trips not only slow down the app but also eat into customers’ data plans. Facebook has solved this challenge by inventing a new way of querying data.

Enter GraphQL

GraphQL is a query language for APIs and a runtime for fulfilling those queries. GraphQL sits between apps running on desktop and mobile devices (clients) and application back-end (server) and allows the two communicate in a more efficient way. It does so by building an abstract model of all the data that clients can fetch while providing a very intuitive format for querying the data. The nitty-gritty details such as where the data is coming from, how to build a schema, and what is the optimal way of batching multiple API calls are automatically handled by the GraphQL server. This allows developers working with it a chance to focus on high-level problems.

GraphQL has been steadily gaining in popularity among mobile and web developers ever since the Facebook engineering team open-sourced it two years ago. We were curious to see how GraphQL could be used with Contentful APIs which in turn motivated our engineers to work on an exciting project. Today these efforts came to fruition. We are happy to announce the availability of cf-graphql, an open-source library enabling you to generate GraphQL schemas and query the content stored in Contentful. The Github repo contains step-by-step instructions on getting started, and we will put together a tutorial on how to build an app powered by cf-graphql soon.

In the meantime, here are some exciting possibilities that the use of GraphQL brings to Contentful:

Easily fetch complex objects

When working with complex content models, developers often need to retrieve multiple, hierarchically-linked entries. For example, an API call to fetch a homepage entry on a recipe website would require the app to fetch a separate entry containing the recipe of the week. This entry might further reference individual ingredients.

When working with collection endpoints, our Content Delivery API (CDA) already allows you to collapse these multiple calls into a single call with the help of the includes operator. GraphQL extends that functionality further by removing the limit on the depth of nesting, automatically resolving links, and enabling its use with single entity API endpoints.

Here is how a typical query would look like in GraphQL implementation:

1
2
3
4
5
6
7
8
9
10
11
{
  posts {
    title
    slug
    featuredImage {url}
    author {
      name
      profilePhoto {url}
    }
  }
}

A common problem that developers run into while implementing their applications with Contentful is a need to refer a “parent” entity in a one-directional relationship. Say you work with a blog where each post references a certain category. Fetching posts with their categories is easy and requires a single API call. By contrast, getting the API to return all categories with the list of posts referencing them is not.

To resolve this problem, some organizations require editors to link entries both ways manually. Others rely on developers building custom fetching and filtering logic into their apps. Contentful’s API partially gets around this complication with the help of the search on references. cf-graphql goes one step further and adds a generic mechanism for supporting back-references as it generates a schema based on your space, which makes this a useful alternative for exploring links between individual entities.

Build mobile apps faster

As we already mentioned earlier, GraphQL found a very receptive audience among mobile developers. It reduces the number of API calls to the server, caches request data, and allows apps to fetch only the fields required for a given view. All of these features lead to more stable, faster mobile apps. In addition to that, GraphQL helps developers to be more productive by wrapping REST API functionality in a straightforward syntax and easy-to-debug error messages. Some of the frontend developers we interviewed told us that this enabled them to experiment with custom queries without adding to the backlog of the backend teams or polluting the API schema with ad-hoc endpoints.

Handle with care

Since GraphQL hides the complexities of backend implementation from the plain view, we would like to highlight a few important considerations to keep in mind before deploying cf-graphql into production environment:

  • cf-graphql acts as a proxy translating GraphQL queries to CDA calls. If your query is complex, it will fire multiple API calls which will count towards your monthly API quota.
  • cf-graphql is an additional component in your stack which will add some latency overhead to your queries due to networking and the query execution steps it has to perform before returning the data.
  • cf-graphql is a self-hosted library; it is up to you to ensure its routine maintenance and availability.

Time to experiment

Go check out the cf-graphql repository today. And once you have a working demo, let us know what you have built. We are always on the lookout for interesting projects to add to the Customers page.

Currently, the cf-graphql library is a standalone project hosted in Contentful Labs. We are in the process of evaluating customer feedback and monitoring its use before considering further integration steps with the Contentful platform. As with all labs projects, we make no guarantees about the long-term maintenance of the library.

Blog posts in your inbox

Subscribe to receive most important updates. We send emails once a month.