GraphQL vs. REST: Exploring how they work

Updated on December 19, 2024

·

Originally published on August 16, 2023

GraphQL vs REST

Application programming interfaces, or APIs, are sets of rules for software systems to communicate with each other and share data. They can allow developers to build complex features without having to start from scratch. GraphQL and REST are two different approaches for building APIs. The main difference between them is how they handle data retrieval. 

In this post, we’ll take a closer look at what these approaches are, give some examples to demonstrate how each of them works, and help you know when to use GraphQL vs. REST APIs.

What is REST?

REST (REpresentational State Transfer) has been the standard way of creating APIs for a while. It was created back in the year 2000 by Roy Fielding (one of the authors of HTTP) for his PhD dissertation. REST APIs are defined as "an architectural style for distributed hypermedia systems." 

Here are the main features of REST APIs:

  • No transient state is kept by the server between requests (hence, state transfer).

  • Endpoints are explicit.

  • HTTP “verbs” like HEAD, GET, POST, PUT, DELETE, and PATCH explain what’s happening to the data.

  • REST separates the client and server concerns, allowing each to grow independently as long as the interface between them is consistent.

  • REST responses are cacheable, which can improve performance.

  • REST is designed to be layered, meaning intermediaries like load balancers can be put between the client and server to improve performance.

As it’s written in the dissertation, the main concept behind REST APIs is that "Each request from client to server must contain all the information necessary to understand the request and cannot take advantage of any stored context on the server." Caching is also mentioned as being a focus in the design of REST.

Show a rest API

Diagram showing a basic REST API request from a client device to a server, including a simple syntax snippet for the request.

Benefits of REST APIs

  • It’s all in the URL: Reading the URL of the request gives you information about what you’re doing. 

  • Standards-based: REST relies on standard HTTP methods and status codes.

  • Caching: REST stands on the shoulders of the decades of work on HTTP caching, which can improve performance by reducing server load.

  • Scalability: Since there’s no client state to maintain, the stateless nature and layered architecture of REST makes it highly scalable, and resources can be distributed efficiently across servers.

  • Language-agnostic: REST is not tied to any one platform or language, and with its uniform architecture, it can be consumed by clients written in a multitude of different languages.

  • Strong community: Owing to its popularity, REST has strong backing with a community of developers who have contributed to useful tools, making it easier to work with REST APIs.

Disadvantages of REST APIs

  • Over-fetching or under-fetching data: Clients might receive more data than they need (over-fetching) or might need to make multiple requests to fetch all required data (under-fetching).

  • Versioning: When the API evolves, it may require versioning to maintain backward compatibility (hence the /v1/ that you see in URLs).

  • Limited real-time capability: REST is designed to be request-response and doesn't support real-time communication natively. This can be a limitation for applications requiring live streams or updates.

REST syntax

Let’s see what the most minimal API call with a REST API looks like. With curl on any Unix-based computer, this is all you have to do:

curl "https://api.github.com/users/octocat"

One of the key ideas with REST APIs is that by looking at the endpoint alone, you know what kind of response you’ll receive. In the example above, you’ll receive a response from the GitHub API about a user with the username “octocat” which is used for demo purposes.

REST resources

REST has a concept of "resources" that essentially refers to any entities in the API. In general, we have one endpoint for one resource.

Take GitHub's REST API for example:

  • A user is a "resource." We can interact with this resource by making a GET request to https://api.github.com/users/{username}. We replace {username} with the actual username of the user we're interested in. There’s no other way to get a user’s info.

  • Similarly, a repository is also a "resource." We can get info about a specific repository with a GET request to https://api.github.com/repos/{owner}/{repo}, replacing {owner} and {repo} with the respective values.

What is GraphQL?

GraphQL is a JSON-like language that was invented in 2012 by engineers at Facebook as a response to limitations of the website’s Graph API. The company used it internally for three years before making it open source in 2015. In 2019, the ownership was transferred away from Facebook to the GraphQL Foundation.

GraphQL is a type of API that works via its own Query Language (that’s where the QL bit comes from). Unlike REST, which is an architectural style and can vary widely in implementation, GraphQL is a full-featured language with a complete specification, just like SQL.

Show a GraphQL API call

Diagram showing a GraphQL API request from a client device to a server, featuring a basic query syntax snippet for fetching data.

Benefits of GraphQL APIs

  • Client-specified data requirements: Clients can request exactly the data they need, which reduces over-fetching and under-fetching issues.

  • Single endpoint: All data is accessed through a single endpoint, which simplifies the API structure.

  • Single request: A single GraphQL query can retrieve all necessary data, since nested queries reflect data relationships.

  • Strong typing: GraphQL schemas define the data types providing good validation and a clear structure.

  • Real-time data with subscriptions: GraphQL supports real-time updates by pushing data changes to clients when they occur.

  • Evolution: Changes to the server schema do not necessarily require clients to be updated.

Disadvantages of GraphQL APIs

  • Complexity: Implementing a GraphQL server can be more complex than a REST API, especially when dealing with complex data models.

  • Caching: Because requests are more specific, and thus more unique, caching in GraphQL is more challenging to implement.

  • Learning curve: The query language and schema design requires developers to learn new concepts, which can be a barrier for teams only familiar with REST.

  • Potential for inefficient queries: Because clients have the flexibility to request any combination of fields, this lack of restriction can sometimes lead to inefficient queries if not managed correctly.

  • Support: GraphQL is not as widely supported, either by public APIs or data-fetching libraries.

GraphQL syntax

Here’s an API call, with GraphQL, again using curl to the endpoint https://swapi-graphql.netlify.app/.netlify/functions/index (a demo GraphQL API that responds with data from the Star Wars universe):

As you see, it's still HTTP, so there’s no need for a library or framework to use GraphQL.

A few things jump out:

  • With GraphQL, the request is longer but more explicit.

  • The important information about the request is in the query, rather than in the URL, like in REST.

  • The URL stays the same, and the endpoint is different. It’s rare to see both GraphQL and REST use a single endpoint. With our Contentful API, the REST API is on https://cdn.contentful.com and the GraphQL API is on https://graphql.contentful.com

If you unroll the payload of the API call above, you get this:

Graph Query Language

GraphQL's query language is designed for both frontend and backend developers. Generally, most of the learning curve comes down to the jargon (you'll hear about mutations, resolvers, etc.); but at the end of the day, if you can write JSON, you can write GraphQL.

GraphQL comes with a sweet tool to help you write it: The GraphQL Playground.

Screenshot of the GraphQL Playground interface

This tool is designed to simplify interaction with the API. These playgrounds offer features such as autocompletion, the ability to send requests, and real time responses. This is similar to what tools like Postman provide for REST APIs (and to be clear, Postman also supports GraphQL.)

For instance, the screenshot above is from GraphQLBin, a website that allows you to create a playground from any public GraphQL endpoint. At Contentful, we also offer a playground and GitHub provides one for its API as well.

What are the limits of REST vs. GraphQL?

GraphQL was designed and built to address several limits of REST APIs. REST always returns entire datasets tied to specific endpoints; GraphQL, on the other hand, allows clients to request only the data they need. This reduces over-fetching and improves performance. REST's rigid design also often requires multiple endpoints to retrieve related data, which can result in increased round trips. To sum it up, GraphQL's single, flexible endpoint and query structure was designed to help developers request complex, nested data relationships in one request and receive only the data that is needed, when it's needed.

Similarities and differences between GraphQL vs. REST

REST = Relational

A good way to think about "GraphQL vs. REST" is to think of relational and graph databases. REST behaves like a relational database, where data is organized into tables. Here's a rough diagram:

Diagram showing REST data organized in tables, like a relational database

On the other hand, GraphQL is like a graph database, where data is represented as nodes (entities) that are connected by edges (relationships). Here's another rough diagram:

Diagram showing GraphQL data as nodes and relationships

This structure lets you fetch data directly, because nodes can be traversed in a single query. Just as traditional databases define tables and their relationships, GraphQL uses a schema to describe entities and how they are connected.

Below is a table outlining the similarities and differences between REST vs. GraphQL:

Aspect

REST

GraphQL

Data fetching

Returns entire datasets from specific endpoints

Returns only the data requested from the client

Endpoints

Multiple endpoints for different resources

Single endpoint for all data requests

Over-fetching/Under-fetching

Common issue due to fixed endpoints

Reduced due to flexible, client-specified queries

Caching

Leverages HTTP caching natively

More challenging, requires custom caching solutions

Real-time support

Limited, often requires WebSockets

Supports real-time updates with subscriptions

Complexity

Typically simpler to set up

Can be more complex to implement and manage

Versioning in REST vs. GraphQL APIs

REST APIs require explicit versioning when breaking changes are made. You can do this by including version numbers in the URL (for example, /api/v1/apples). This allows developers to maintain multiple versions concurrently, offering backward compatibility.

GraphQL is different in its approach and promotes a design that doesn't require versions. In place of creating new versions, GraphQL encourages things like field deprecation, where outdated fields can be gradually phased out.

Popularity of GraphQL vs. REST APIs

Both GraphQL and REST are widely used for building APIs, but they seem to have different levels of popularity across different use cases or industries:

REST remains the most popular API architecture, especially when looking at traditional web development due to its simplicity and established standards.

GraphQL is a newer innovation, but it has rapidly gained popularity, especially in applications that require flexibility and efficiency in data fetching, such as social media platforms and ecommerce sites. It's also a favorite among frontend-heavy teams due to it only fetching the data you need on the client.

An example query with REST vs. GraphQL

The similarities and differences between GraphQL and Rest APIs can be shown with a basic example query. In this example, we’ll use the unofficial Star Wars API, which has both a REST and a GraphQL endpoint, to fetch a list of all the droids (robot characters). In this API, the droids are classified as people and have a species ID of 2.

Finding the droids you’re looking for with REST

In JavaScript with native fetch in Node.js v18 or using node-fetch, we can grab a list of all the droids and their heights from the Star Wars API like this:

With this REST request, you should see console output that combines information from both of the REST API endpoints that were accessed in the above JavaScript code example:

Finding the droids you’re looking for with GraphQL

With GraphQL, you’re not constrained by the concept of “one endpoint, one resource” — you only need to make one request, as demonstrated in this query:

Here's how you'd make that request in Node.js. and assign the response JSON to a JavaScript object for use:

Although, with REST, you could do something similar with a relational database and join the information, but it would likely result in over-fetching data, since the endpoint would return all fields for species and people. As can be seen here, in GraphQL you can make one request to return only the requested information.

So, how did they do?

As you can see, both REST and GraphQL can achieve the same result, but GraphQL does it in a single request.

Side-by-side comparison of GraphQL vs REST workflows for fetching related data

When to use GraphQL vs. REST?

While GraphQL has more features than REST, each is suited to different use cases, so one isn’t inherently better than the other. Choosing between GraphQL and REST can be a difficult decision and should be based on the specific needs of your project. For instance, GraphQL is useful in projects where precise, client-specified data-fetching is required, while REST works better in simpler, resource-oriented applications. 

When to use REST

  • Building a simple API: Ideal for CRUD operations and resource-based APIs.

  • Wide compatibility: REST is universally supported across platforms, making it easier to integrate across various systems.

  • Lower setup complexity: Easier to implement for small projects or where your project doesn't have complex data requirements.

When to use GraphQL

  • Complex, data-intensive apps: Great for applications that need nested, highly specific data queries.

  • Real-time updates: GraphQL has better support for live updates with the subscription feature.

  • Dynamic frontends: GraphQL can be good for diverse or evolving client needs such as a fast-growing startup, as it allows flexibility in data requests and versioning.

  • Reduced network calls: You can request specific nested data as you need it, reducing the amount of round trips you might need as opposed to REST.

Future proofing — GraphQL

GraphQL might be a good choice if you are expecting to be making frequent changes to your schema, as it allows you to add new fields and types without breaking existing queries. It also offers a few tools to make your API visible to development teams. Even if you don’t anticipate that you need GraphQL’s features now, it may be worth considering for projects expected to grow or change significantly. However, if your use case is simple and clear cut, REST may be the better, more efficient choice.

How to build REST and GraphQL APIs 

There are an abundance of different tools and libraries to help you build REST and GraphQL APIs. For REST, libraries like Express.js provide routing and middleware out of the box, and you can use tools like Postman to help with API testing. For GraphQL, you can use libraries such as express-graphql or Apollo server to help build flexible, schema-driven APIs.

Load any content from Contentful's REST and GraphQL APIs

Building something cool? Maybe an ecommerce website? A viral app? Putting together a broadcast or media campaign? A digital billboard? An AI assistant? Something we've not heard of yet? 

As with any other web or app development technology, the choice between GraphQL vs. REST depends on your specific use cases. The good news is that Contentful supports both REST and GraphQL APIs that can be accessed from anywhere on the globe using our high-speed CDN, so you can choose the approach that best aligns with your project. Whether you're building a simple blog or conquering a new market, we have you covered.

Subscribe for updates

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

Alvin Bryan

Alvin Bryan

Developer Advocate, Contentful

Alvin is a developer advocate and creative coder. He's worked on many things like games, charts, 3D graphics, marketing sites, data visualizations, design systems, and maps.

David Fateh

David Fateh

Software Engineer, Contentful

David Fateh is a software engineer with a penchant for web development. He helped build the Contentful App Framework and now works with developers that want to take advantage of it.

Related articles

Find out everything you need to know about vector databases, including their architecture, use cases, and how to integrate and leverage them in your apps.
Guides

What are vector databases and should you be using one?

June 20, 2024

Illustrated graphic representing what is REST API
Guides

What is a REST API?

October 4, 2021

Websites still play a key role in meeting customer expectations. Read on for tips to modernize your brand’s web strategies and deliver great experiences.
Guides

Modernize your web strategy and deliver customer-winning experiences

January 11, 2024

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