What is GraphQL? What a GraphQL API is and how to use it

Updated on February 8, 2024

·

Originally published on December 13, 2021

What is GraphQL? What a GraphQL API is and how to use it

GraphQL is an API query language that is often underutilized by developers who are used to using REST and SOAP APIs to query and retrieve data.

This article consolidates everything you need to know to get started using GraphQL APIs, providing a high-level introduction to GraphQL queries for developers looking to get started with (or brush up on) this powerful API tool.

If you’re new to development, we recommend you check out What is an API? to get a good grounding on APIs and the role they play in web and app development.

What is GraphQL?

GraphQL (from “Graph Query Language”) is a language used to communicate with backend systems through an API, allowing you to fetch and manipulate data. It was developed by Facebook in 2012, and made open source in 2015.

GraphQL is language-agnostic, which means it can be used with any framework or programming language. You usually interact with it via standard HTTP requests made from your web or app frontend.

A GraphQL API can be added to any backend so that developers can query the connected database using the GraphQL query language. To create a GraphQL server for your data source, you can implement it yourself using a library for your language or framework, or use specialized tools such as Apollo GraphQL that allow you to create a layer on top of your existing backend and database. 

How does GraphQL work (and what does the “graph” bit mean)?

GraphQL creates a representation of your data that is designed to feel familiar and natural. The “graph” in GraphQL describes a data structure of a collection of objects — or nodes — that are connected to each other through a set of links, or edges. 

A representation of a graph data structure

Like a graph, this representation is structured, readable, and something that can be described in human language. Objects and their relationships can be queried and represented in a user interface as a result of this graph structure.

Data structures in GraphQL are non-linear, meaning that one object can be connected to more than one other object, and relationships can be circular. The screenshot below shows the relationship between several objects retrieved from the Contentful GraphQL API: a blogPost node, which contains an author node, which in turn contains an image node, which contains a fileName of type String

Contentful GraphQL Playground

Contentful allows you to define a content model that represents everything you want to publish on your apps and websites, from product listings to blog posts and media, and populate it with content for access via the Contentful API.

The Contentful GraphQL Playground app used in this example provides a convenient way to query this data. The interface allows you to drill down and inspect the data types in each content type and understand how they’re related to each other. 

This gives you a high level of visibility and insight over the data structures that power your content and lets you query and inspect all the objects and types that exist in your data, which helps you build robust and scalable applications — perfect for microservices and mobile apps.

Why you should use GraphQL over REST APIs

REST APIs have been the standard for some time now, and developers are familiar with the benefits they provide, but there are some long-standing downsides of REST that GraphQL solves:

  • Efficiency: REST requires your frontend to make multiple requests to get related objects from different endpoints and doesn’t let you specify which fields to return.

  • Query complexity: Both your frontend and backend code is more complex — you need to maintain multiple API endpoints for different objects and complex queries, and for updating data that spans relations.

  • Flexibility: New frontend requirements often mean needing to write new backend endpoints for specific purposes.

GraphQL’s flexible query language addresses these problems by letting developers retrieve the exact data they require from a single endpoint.

Querying across relations is more efficient — and typed

GraphQL allows you to request data from multiple different resources, such as blog posts, pages, authors, or any other object, in one API call. Instead of fetching all of these in separate requests to a REST API,  GraphQL lets you request the exact data you need to build your websites and application frontends in a single request.

This makes your code simpler, as you don’t need to make separate requests to your backend for related objects and reassemble them on your frontend (for example, adding an author’s data to a blog post after retrieving them separately). It also reduces load on your infrastructure, as there is less traffic and you only retrieve the data and fields that are required. This also benefits your users — less data needs to be transferred and more acute caching strategies can be implemented, making web experiences faster and more responsive.

Below is an example of a GraphQL query that makes a request for blogPost, author, event, and talk collections from the Contentful GraphQL Content API

This shows how the different objects are queried, and how to only include specific fields in the response: The eventCollection object only asks for the name field for each of its items — any other fields are not included in the response.

Note that APIs differ in their functionality and may implement additional features to make them more convenient to use for developers — in this case, the Contentful API lets you append Collection to the name of the type being queried and lists all objects of that type.

Here’s the result of the data query.

Example query

This query is sent as a single request, whereas obtaining the same data via a REST API would take four separate requests to retrieve each type of object. The object keys returned are exactly the same as the ones requested, so you’re never going to download more information than you require (known as overfetching).

This makes GraphQL predictable and intuitive to use: You get exactly what you ask for in the response.

GraphQL diagram

If you want to take a deeper dive into types in GraphQL, take a look at the official GraphQL documentation on schemas and types.

Introspection queries let you expose your GraphQL schema

Query your GraphQL schema using GraphQL itself! GraphQL comes with an introspection query system that allows you to query the type system and data structures in your database in order to generate documentation and provide hints in the GraphQL UI. This root-level query returns all of the data types you have in your schema. 

The below code queries the GraphQL APIs schema (via the __schema field) and retrieves the name of each type in the schema.

Here is the result of running the above GraphQL query in the Contentful GraphQL Playground.

Introspection query

In the query response above, you can see three different types of data returned by an introspection query:

  • Types defined by the schema: in the case of a personal blog built with Contentful, types such as blogPost, author, talk, and so on.  

  • Types defined by the type of field data (scalar types): such as String, Boolean.

  • Internal introspection query types: such as __schema, __type,  and __field that are all prefixed by a double underscore.

It’s easier to write (and maintain) complex queries 

In GraphQL, each field in a query acts as a function that returns the next nested field type, followed by the next type, and the next type, until the field returned is a scalar value, such as a String or a Boolean.

This is demonstrated in the example above, where a blogPost object contained an author object, which contained an image object, which contained a fileName field of type String — a scalar value — so that’s where the journey ends.

When any field is executed, a resolver is called to produce the field value. If you’re developing your own GraphQL servers and making database changes, you’ll need to provide a resolver for each new field type you add to your API. 

Platforms can build on this functionality to make incredibly developer-friendly tools. For example, a great feature of the Contentful GraphQL API is that the schema for your data is generated at request time, meaning it’s always up to date with the current status of your Contentful space. You don’t need to worry about resolvers or developing your own GraphQL API for your content — Contentful handles everything for you. 

If you want to find out more about GraphQL introspection queries and how to watch them run in the network tab of your browser, check out this video on the Contentful YouTube channel.

GraphQL mutations let you write data to your backend

To mutate something means to change or manipulate it. You can manipulate your server-side data via GraphQL using the mutation keyword.

The example query above begins with the mutation keyword, followed by syntax similar to defining a function in JavaScript. The mutation is named CreateNewBlogPost, and must be passed a string as the $title variable (the ! denotes that this variable is required for the mutation to occur). Within this, there’s a call to a defined mutation from the GraphQL API (to see what mutations are available, you can use an introspection query). 

Note that the mutation keyword and  CreateNewBlogPost are part of the query that is sent to the API to perform the mutation, while createBlogPost is the mutation that will be performed on your data by the server. Within the mutation, the fields to include in the response are defined — in this case, the title field. Here’s the response you’ll see from the API after the mutation has completed. 

An example of how to connect to a GraphQL API

GraphQL is usually served over HTTP via a GraphQL server. There are other ways to communicate with GraphQL, such as via WebSocket, but HTTP is the most popular (and practical) choice.

GraphQL provides libraries for almost every major language and platform, accelerating the process of building and extending apps and frontends to connect to GraphQL APIs. If you’re building with the Contentful Composable Content Platform, we also provide our own SDKs tailored for retrieving content for your websites and apps.

If you’d like to read up on how to use GraphQL over HTTP with cURL, Python, JavaScript, Ruby, and PHP, check out this blog post: GraphQL via HTTP in five ways.

Here’s a quick example of how to request a title and excerpt from a blog post stored in Contentful via GraphQL, using JavaScript fetch()

This example sends an HTTP POST request (if you’re running this yourself you’ll need to replace yourSpaceId and yourAccessToken with details taken from your own Contentful account), including an access token in an Authorization header and the GraphQL query in the body of the request. The same request could be made via HTTP GET, but the query and access token would need to be appended to the URL of the request instead.

GraphQL plus composable content accelerates frontend development and content publishing

GraphQL is a powerful way to organize how your frontend applications and websites communicate with your backend services and databases using your choice of language and framework. Once you’ve familiarized yourself with GraphQL, you can write more efficient queries that require less maintenance of both your front- and backend code. 

For developers wanting to further streamline their development process and improve their user experiences, composable content allows you to define the Rich Text and media that you want to deliver to your users, and deliver it to your cross-channel apps and websites, from a single cohesive source that allows you to define (and redefine) your user journeys.

Looking to jump into GraphQL right away? Our GraphQL API cheat sheet will help get you started.

To find out how to use GraphQL to get your Contentful data — including published and preview content — check out the official Contentful documentation.

Subscribe for updates

Build better digital experiences with Contentful updates direct to your inbox.

Related articles

Optimizing images for your site? Learn how creators use the imgix integration for Contentful to seamlessly share, manage and collaborate on visual assets.
Guides

Simplify image workflow and optimize visual experiences with imgix and Contentful

June 2, 2022

Guides

The understated innovation of static site generators

July 17, 2018

In this tutorial, we'll build a basic Svelte app that will give you a good understanding of the core concepts in Svelte-like components, props, and more.
Guides

Svelte tutorial: An elegant framework for learning new things

September 6, 2023

Contentful Logo 2.5 Dark

Ready to start building?

Put everything you learned into action. Create and publish your content with Contentful — no credit card required.

Get started