Choosing the right API for your website:
GraphQL vs REST API

Last updated on Sep 12, 2024

Choosing the right API for your website:
GraphQL vs REST API

A decoupled CMS is only as good as its data API – the Application Programming Interface that acts as the data contract between your backend server and frontend application. This is as true for a headless or decoupled WordPress setup as it is for any other Content Management System. 

REST API vs GraphQL

In WordPress, the most popular choices are the WordPress REST API or GraphQL, powered by a plugin like WPGraphQL. However, there are specific considerations when choosing the CMS that powers the bulk of the web that basic comparisons of GraphQL vs Rest API don’t take into account. This can make it hard to determine which API is right for you.

In this post, we address some common misconceptions and compare the differences between using REST and GraphQL in WordPress, and help you decide which API makes the most sense for your decoupled application. 

What is REST API?

REST (Representational State Transfer) is one of the most common API design patterns for decoupled applications. “RESTful” APIs expose their data using individual endpoints corresponding to specific resources – where for example a list of posts is available at api/posts and api/posts/1 will fetch the data associated to a single post (with the ID of 1) – or interactions – such as /api/posts/create which could be used to create a new post object.

REST endpoints are easy to implement, which explains their widespread adoption. At its core, each endpoint receives a list of possible arguments, and returns a payload representing the object, usually in JSON format. However, care should be taken when designing a REST API: too generic an endpoint, and you risk continuously overfetching data; too specific and you risk coupling your API too closely with your frontend logic, replacing over-fetching issues with multiple round trips to the server to get all the data you need.

WordPress REST API

WordPress core includes the WordPress REST API, providing numerous endpoints both to retrieve data and to power various functionalities, such as the Editor interface and the frontend Interactivity API. As of WordPress 6.6, there are 21 different REST endpoints included in core. Additionally, the WordPress REST API supports the automatic generation of endpoints for custom WordPress data type, such as Post Types, Terms, and Settings, the API makes it easy to register fully custom REST endpoints too, and a plethora of WordPress Actions and Filters allow for easy customization of existing behavior.

Due to its “first party” nature, it is also common to see many free and premium WordPress plugins released with built-in support for the REST API, albeit usually limited to supporting specific Editor functionality (e.g. custom blocks) or bespoke decoupled behavior (e.g. a frontend filter view or widget). If you’re able to safely adopt these APIs in your headless or decoupled application, that’s significantly less development time and tech debt to maintain.

However, these REST API “benefits” come at the cost of exacerbating the fundamental issues with REST – overfetching and overcoupling. Resource-based endpoints remain overly generic – an issue exacerbated in a fully-headless site, with a single ‘WordPress’ object rarely representing a complete frontend view – or too specific to safely rely on. 

For example, when serving an author page, you don’t just need the data representing the author, and will probably need to fetch their connected posts, comments, or even connected data on those objects. Your options are either to make multiple requests to multiple WordPress REST endpoints, or create a custom endpoint – which you would then need to service and change as your frontend needs evolve, effectively coupling backend changes with every frontend update.

The ease of extensibility, made worse by a lack of type-safety built into WordPress core, means you cannot rely on the API contract to be maintained long-term. Even implementing specific WordPress functionalities meant to help with over-fetching, such as REST API “_fields” and batch queries, can often create an additional and unwanted coupling between the API’s logic and frontend functionality. 

Rest API with WordPress

What is GraphQL?

GraphQL, in contrast to REST, is more than just an API contract but rather functions as a comprehensive query language and runtime server. Instead of multiple endpoints, GraphQL utilizes a single endpoint to the server, with developers composing targeted queries to request or manipulate only the specific data they need. This reduces over-fetching issues usually experienced with REST, and improves the separation between your backend and frontend, since your components and views no longer need to be tied to a specific endpoint.

Arguably, GraphQL’s biggest strength lies in its schema, which is both self-documenting and strictly typed. This feature eliminates the need for developers to understand how the backend is configured when implementing APIs in their applications. They can rely solely on the generated schema, and take advantage of CLI tools, IDE extensions, and linters to ship code with fewer bugs and more quickly. It is even possible to be notified when a backend change may break your frontend, preventing users from experiencing any breakages.

However, while GraphQL APIs are a breeze to consume, they can be quite complicated to implement. Care must be taken to design robust types, and ensure the underlying queries and data modeling is both performant and secure. 

WPGraphQL – GraphQL for WordPress

Luckily, the WordPress ecosystem has taken care of much of the complexity for implementing GraphQL API.

WPGraphQL (WordPress GraphQL) is the most popular GraphQL solution in the WordPress ecosystem. Released by Jason Bahl and sponsored by companies such as WPEngine and GatsbyJS, the plugin covers most core WordPress functionalities and is accompanied by a  number of official and third-party extensions, and a large, friendly developer community. While alternatives like Gato GraphQL exist, WPGraphQL remains the preferred choice for enterprise.

Like the WordPress REST API, WPGraphQL provides a robust developer experience, with classes and methods to expose custom data and types to the schema, and a plethora of WordPress actions and filters to modify behavior. That’s particularly important for developers building bespoke web-apps relying on lots of third-party functionality or custom data types; since WPGraphQL is a community plugin, most other plugins don’t expose their data “out of the box”, and you’ll likely need to register a significant number of custom GraphQL types and fields. 

WPGraphQL with WordPress

Debunking common misconceptions

Before we can compare using REST and GraphQL to power your decoupled or headless application, we need to address several common misconceptions that arise in the context of WordPress. Some of these arise from conflating implementing an API vs consuming one. Others are based on outdated information, a frequent occurrence in the fast-paced, headless WordPress ecosystem. Regardless of why, it’s time to put them to rest.

API performance

Concern: Businesses might be concerned that one API may significantly outperform the other, impacting user experience and system efficiency. As we noted above, reliance on REST APIs often results in overfetching, while designing performant GraphQL schemas require thought and skill. GraphQL also gets a bad reputation for being harder to cache, since it doesn’t have resource specific endpoints.

The reality: As a platform powering a large portion of the web, both the WordPress REST API and WPGraphQL take performance into account. 

The REST API’s support for field selection and batch queries help prevent overfetching and multiple trips to the server by grouping requests together and limiting the data returned. While REST doesn’t offer the full granularity of GraphQL, these features can make the differences marginal in most cases. 

Meanwhile, WPGraphQL (WordPress GraphQL) implements performant patterns such as DataLoaders and cursor-based Connections, which puts the complexity of schema design on par with the WordPress Rest API. Frontend support for GraphQL GET requests coupled with an extension like WPGraphQL Smart Cache can even lead to better and more nuanced caching strategies – and more performant responses – than the WordPress REST API with its own caching layer; it just requires a bit more to set up.

GraphQL’s flexible query language, while a huge advantage over REST, comes with its own performance risk: it’s really easy to request complex sets of data. Care should be taken to only query for data you need, when you need it, using features like reusable fragments, cursor-based pagination, and sensible connections when composing your GraphQL queries.

The practical difference: If your application only requires handling simple data requirements that are mostly represented by WordPress’s object structure, the WordPress REST API – when combined with “_fields” and batch queries – will likely be the most performant and easiest to optimize against.

If, on the other hand, you’re building complex data views composed of different WordPress objects such as those needed to power a headless CMS, GraphQL’s ability to fine-tune data requests could make it the better choice—provided your team has the expertise to configure it and use its query language effectively.

API security

Concern: There may be concerns that one API offers superior security features, making it a safer choice for protecting sensitive data. A particularly common misconception is that REST is inherently more secure than GraphQL since REST can make use of the security and authentication built into the HTTP protocol, while GraphQL doesn’t have a native security or authentication layer.

The reality: Both REST and GraphQL in WordPress incorporate robust security layers leveraging user roles and capabilities, and can be made secure with proper configuration that requires the same amount of effort – and near-identical techniques – for each API. Additionally, numerous plugins exist for both APIs to facilitate headless authentication using methods like JSON Web Tokens (JWT), native WordPress cookies, OAuth2, and more. 

The practical difference: Since both APIs can handle authentications and permissions effectively, the choice between them should focus more on other implementation needs. It should be noted that since REST is closely integrated with core WordPress features, the “out-of-the-box” implementation may meet the needs of simpler projects with less configuration.

API compatibility

Concern: Companies might worry about long-term compatibility and maintenance, fearing that one API could introduce more breaking changes or be harder to support as their system evolves. A common misconception is that REST is less future-compatible since endpoints are usually versioned, while GraphQL schemas are designed to be versionless.

The reality: WordPress’s commitment to backward compatibility means that REST endpoints are versioned rarely and deliberately, and even when they are, the old endpoints remain providing your decoupled project time to migrate. However, the lack of type safety in WordPress’s REST API means you still must guard around “non-versioned” breaking changes that can occur on some core WordPress APIs or as a result of customizations from other plugins.

Conversely, the active development within the GraphQL ecosystem may occasionally introduce breaking changes, despite GraphQL’s schema design principles aiming for future compatibility. This can be especially true when relying on community extensions. However, breaking changes are easier to identify and prevent due to the built in type-safety of the schema.

The practical difference: For straightforward projects with a simple and controlled plugin stack, the WordPress REST API might be the more stable choice that requires less ongoing maintenance to keep compatible with WordPress’s latest. However, GraphQL’s type-safe schema makes it easy to prevent shipping breaking changes and update your code for compatibility, which are invaluable in a complex stack or an application with an ongoing development cycle.

API implementation

Concern: A common belief is that it’s easier to implement REST APIs than define a GraphQL schema. Since REST is just a collection of endpoints returning a simple JSON payload, teams don’t need to spend time defining custom GraphQL types or thinking about performant data models.

The reality: Thanks to the WordPress REST API and WPGraphQL, the amount of custom API design is already fairly minimal, and the robust Developer APIs for both make the process of exposing custom data easy regardless of which one you choose. Instead, the two APIs differ on where in the design/implementation process the complexity lies. REST’s untyped nature makes it easy to scaffold an endpoint without much forethought. Additional care must be taken when consuming the response data, as well as that your custom endpoints aren’t too coupled to your frontend use case. Similarly, WPGraphQL requires you to consider your schema design upfront and understand efficient data loading patterns; while a lack of consideration for these concerns when developing custom REST endpoint will result in long-term issues for your team and application, they aren’t strictly required.

The practical difference: If your project involves straightforward data interactions and you prefer flexibility in implementation, REST might be the better choice. However, for projects requiring complex, type-safe data exchanges, WPGraphQL could reduce long-term complexity and errors, ultimately saving time and resources.

Additional Pros and Cons

Not all common arguments in favor of WPGraphQL versus the WordPress REST API are invalid. Here are some more differences between the two APIs you should consider before choosing which is best for your decoupled/headless use case.

  • Learning Curve: As a query language, GraphQL has a much higher learning curve, since you need to take care to craft smart and performant queries. REST forces you to write simple queries, since every endpoint is just a dump of predefined values.
  • Developer Experience:  GraphQL often offers a superior developer experience due to its strictly typed schema, enabling powerful tools like WPGraphiQL Explorer and GraphQL Voyager, which are particularly beneficial in headless or decoupled CMS projects. The WordPress REST API allows you to “hint” a schema, but it does not enforce it, leading to potential bugs, edge cases, and overall increased tech debt.
  • Stack Fragility: The WordPress REST API is an integral part of WordPress and implemented by most plugins – at least to an extent. Meanwhile, WPGraphQL is an external plugin and a collection of third-party extensions, each with differing levels of code quality and support. That extra fragility represents a significant risk of assumed tech debt from potential bugs and plugin updates.

Choosing the right API

Benefits of REST API 

Consider the WordPress REST API when –  

  • Your data needs are simple and already exposed via WordPress core or plugins.
  • Your use case for a decoupled application is straightforward, and wouldn’t benefit from robust DX or type validation.
  • You need to rapidly prototype APIs during development.
  • Your team is already familiar with WordPress’s REST APIs or Gutenberg.
  • Your “backend” tech debt costs, such as managing WordPress plugins and debugging PHP code, are lower than your “frontend” costs, such as component/UX design and frontend development.

Benefits of WordPress GraphQL – 

Opt for WPGraphQL when – 

  • Your frontend interfaces rely on complex data structures and custom UX.
  • You need to maintain a “separation of concerns” between backend and frontend knowledge, such as a React frontend team that can work independently of a “WordPress/PHP” team. 
  • You need to expose the same data for multiple scenarios or user experiences, such as custom web views, or Mobile and IoT applications.
  • You need robust developer tools and type validation in your IDE tool.
  • Your frontend development team is already familiar with GraphQL’s query language.

REST, GraphQL, or a hybrid approach?

As shown, the choice between REST and GraphQL depends strongly on the needs of your team and your WordPress project. REST’s ease-of-implementation and built-in support make it a great choice for simple frontend requirements. It is well-suited for rapid prototyping, especially when the same developers work on both the frontend and the WordPress backend. 

WPGraphQL is best for complex projects. It makes it easy to create bespoke user experiences and fully headless frontends. WPGraphQL also helps enforce clear separations between frontend and backend development and scaling for enterprise. This is especially true if your developers are already familiar with GraphQL’s syntax.

However, the decision isn’t always binary. Smart developers often leverage both APIs within a single headless or decoupled WordPress implementation, choosing the ideal one for the specific needs of the application logic. For instance, they might use GraphQL to render UX interfaces while employing REST for simpler data exchanges like RSS feeds, client-side authorization, or triggering server jobs.

REST API and WPGraphQL with WordPress

No one-size-fits-all solution

As with any technology decision, the key is to remain adaptable. The decision between GraphQL vs REST API is not a one-size-fits-all. It depends on your project’s specific needs, team expertise, and long-term goals. Carefully weigh the pros and cons of each API approach while implementing a headless or decoupled architecture and contact us to make an informed decision.

On this page

Comments

Leave a Reply