How to Retrieve Data From WordPress With REST-API And GraphQL
READING TIME: MIN
WordPress development is constantly evolving. Your favorite CMS is not only used for basic websites like blogs or forums but can also be used for creating more complex applications. Advanced WP developers need the right tools to build external apps using WordPress as their backend.
These days with all the hot technologies coming out every day, choosing your toolset is no more a trivial task. It can drastically impact the fluid creation of a project. Even more when talking about the way you access and interact with your data.
GraphQL is a great alternative to the conventional WordPress REST APIs. In this article, you’ll learn what GraphQL is, its differences from the REST API, and how to use it with your WordPress installation.
Understanding the WordPress REST-API
Since version 4.4, WordPress comes with a great documented REST API out of the box. You may have built some WordPress sites, or even some plugins and themes, but if you’re new to web development as a whole, probably, you’ve not heard about APIs before.
Let’s build these concepts out!
An API, meaning Application Programming Interface, is nothing but a way of communication between two or more computers. Imagine your WordPress blog. Someone types in your domain and a connection between two machines (viewer computer, and the web server) begin.
Simply put, the visitant is making a request and the server that has your WordPress install is giving them a response. This interaction occurs thanks to the API.
Our WordPress development agency is sure you see APIs in your everyday life. For example, when you log in to a site, it’s common to find the option of using social media accounts. Also, if you visit many eCommerce sites, you’ve probably had the “Pay with PayPal” option. In both cases, the services that you’re using work with external APIs to elevate the user experience.
APIs follow a structure, a set of rules that make the exchange of information viable. You can think of it as a contract, where your software will only respond to the user if they’ve met all the conditions.
The most popular “contract” constraint is called REST (REpresentational state transfer). It is the standard of modern web applications and enables multiple systems to communicate with each other in a well-structured way.
When talking about REST APIs, you’ll see the same concepts over and over, so let’s define some of the most important:
- Request: web browser to server communication over HTTP. It occurs when you type in an URL trying to retrieve information from the server (usually a web page).
- Response: If you send the proper request, you’ll get a response in JSON format.
- Endpoint: The URL you type in when making a request, usually including an HTTP method.
- URL: We use it every day so it’d be worth it to know its meaning. The Unique Resource Location is an address used to locate a resource on the Internet.
- JSON: A lightweight yet powerful format for storing and transporting data. It’s the standard in REST APIs.
- HTTP methods: The verbs you use to make a request. The most used are GET, POST, PUT, and DELETE.
- Schema: Metadata that defines how our data is structured.
Why Use the WordPress API?
The WP REST API is the easiest way to integrate the WordPress backend- namely all the data in your site and what the normal user can’t see- with different frontend, and mobile technologies.
[ad_show]
Imagine you have a successful forum running with WordPress, and you want to launch a mobile application. The common theme and plugin infrastructure don’t have you covered. You need a way to send all the data (posts and forum replies) to your mobile app, and the most straightforward way to our WordPress development agency is with an API.
The same thing happens if you want to level up your site. User experience has never been more important, and having a pretty and functional interface is a large steak of it.
Building your interfaces with frameworks such as React, Vue, and Angular is your way to go. That’s when the API comes to play since it’s the only way to connect the frontend of your site with the backend.
All of this seems great, so why even bother to change to something like GraphQL? Let’s take a quick look at this technology.
Introduction to GraphQL
GraphQL (Graph Query Language) is a query language for APIs created by Facebook and then made open-source to the community. It’s a flexible and more efficient alternative to REST APIs.
Now it’s maintained by a large group of companies and communities. You can take a look at the GraphQL source code for JavaScript in its GitHub repository.
It works by exposing a single endpoint (the URL you make the requests to) and responding to the queries you do. Contrary to the standardized REST APIs, GraphQL doesn’t have a lot of endpoints with fixed data to return, making it more effective to retrieve the data you’re really interested in.
Because GraphQL is a Query language — similar to SQL —, you can use it in the frontend with frameworks like React, as well as in the backend with Node JS. This is the most common stack when using GraphQL.
In a more technical sense, GraphQL makes you think about your database as a graph. This graph contains all the schemas and the relations between them and allows you to traverse it based on how it is connected. The queries you make navigate that graph and retrieve exactly what you need in a single endpoint.
If you’ve never touched on graph theory, here is an image to simplify this idea.
Here is a GraphQL query example:
query { character (id: 1){ name } }
And its respective response:
{ "data": { "character": "Daniel Diaz" } }
In the query above, assuming you have a database with a field “character”, you requesting the character with the field “id” equals 1. You get an object and then ask for its “name” field.
It’s worth mentioning that all GraphQL queries are done over a single endpoint, meaning an URL as the following:
http://yoursiteurl.com/graphql
To sum up this section, GraphQL is a language that lets you perform queries to a dataset, retrieving only the data you require, and removing the need for multiple endpoints.
Our WordPress agency’s experts recommend you to visit the GraphQL official site if you want to learn more.
GraphQL vs REST APIs
REST has been out there since the early 2000s, and it’s the standard for building modern APIs. GraphQL was developed to solve two main problems present in REST APIs: Over-fetching and under-fetching.
Over-fetching is fetching more data than what you’ll actually be using. Under-fetching on the other hand is not having enough data with a call to an endpoint, resulting in a call to a second endpoint. This can happen if you make a complex request using a REST API.
Our WordPress development agency warns you that both of them cause performance problems.
GraphQL takes a different approach by sending a single query to the server with all the data you need. The server then replies with a JSON object that includes the data you specified.
This makes app development faster because it allows more granulated and flexible queries. GraphQL empowers frontend developers to be faster by doing all the data they require using just an endpoint. This improves and removes the need for new endpoints if the frontend developer needs different data for the interface.
However, as with most technology, choosing GraphQL or not isn’t a one-size-fits-all situation. Let’s see some similarities and differences.
Structure
In GraphQL data is organized as a graph, and connections occur if your data has some kind of relationship (e.g User id, and a comment). You create a schema, which is a collection of types and the relationship between types. From those schemas, you can request the data you need using queries.
In a REST API, you have different endpoints which help you to interact with your data through the well-known HTTP methods.
Both approaches use JSON as the preferred data interchange format. Also, both options are language agnostic, meaning they can be implemented in any programming language.
Use cases
One of the best use cases of GraphQL is with highly related data. For example, a social network such as Facebook or Instagram has thousands and thousands of relations between each object.
If you need to query a lot of relational data, then GraphQL should be your choice.
The other benefit of using GraphQL is in frontend development, where you’ll be able to make a single call to get the specific data you need. With REST you’re forced to ask for blocks of data from which only a fraction is needed.
This is incredibly helpful in mobile apps which often have problems with bandwidth use.
In simple CRUD applications, such as Blogs, Todo-lists, or admin panels, REST is still the perfect choice.
Flexibility vs Reliability
How much flexibility do you really need? The truth is that with most modern web development frameworks, such as Django, Laravel, and Express JS, most functionality is already implemented. For instance the authentication system and the CRUD operations.
For most simple projects GraphQL could be a bit overkill.
Another GraphQL disadvantage is the lack of a comprehensive design pattern for complex apps, whereas REST has plenty of design patterns.
Community
REST has a large established community of users. No matter the technology you’re using you’ll find a great number of resources, as well as forums and questions that have been already solved.
GraphQL being a newer standard, doesn’t have an immense community. Nonetheless, its importance is growing every day, so you can expect to find more and more resources over time.
Advantages of GraphQL With WordPress
You can have all the benefits of using a GraphQL API in WordPress. There are several plugins for that purpose, but Our WordPress development agency’s recommendation is WPGraphQL.
It provides a GraphQL API that lets you fetch data from, and post data to your WordPress site. You’ll still be able to manage all of your content in WordPress, but with an API, you would be able to render your site using an external library or framework. For instance, modernize your site using a framework such as React, Vue, or even Gatsby making it much more interactive to your viewers.
Both REST and GraphQL APIs provide the required data. But REST is a more static approach, where the endpoints are already defined, while GraphQL encourages a dynamic approach where every query is custom-made.
GraphQL will grant you a good performance even on slow mobile connections. You should definitely try it if you plan to develop a mobile app for your site.
Large sites are running the WordPress and GraphQL combo. The best example is the New York times, which current stack revolves around having WordPress as the CMS and using GraphQL to supply React with all the data for the frontend of their site, and mobile app.
However, it’s worth thinking twice before using such an advanced stack just for a prettier interface. Do it if you feel the WordPress templates are no more an option, and that extra interactivity, like for example incorporated forms or quizzes at the end of your posts is worth the extra investment.
If you’re just learning or looking for a side project, then go ahead and improve your advanced WordPress development skills.
How to Use GraphQL With WordPress
As our WordPress agency always said, there’s a WordPress plugin for everything! You don’t need to build a GraphQL interface on your own, there’s already a plugin that does a pretty good job.
First, go to your WordPress dashboard. Example: https://example.com/wp-admin/, and click on the Plugin menu.
Then search for “WPGraphQL” and click on the install button.
After that, you can jump into the GraphQL IDE by clicking on the new icon at the top bar of your website, and start making queries.
In this case, I made a simple query to get the title of all the posts published.
query { posts { nodes { title } } }
If you want to make external queries with some mobile or frontend framework, you can use the GraphQL API path, located at https://yoursiteurl.com/graphql.
To follow up with your GraphQL and WordPress journey, you can check out the WPgraphQL documentation.
Wrapping Up
GraqhQL APIs are a great alternative to REST APIs. Especially if you need high scalability, or your data scheme has lots of relationships. It solves the problems of over-fetching and under-fetching by making queries that specify exactly the data that is needed.
WordPress and GraphQL help you to separate your CMS from your user interface, allowing you to use frontend and mobile frameworks to create custom presentation layers.
The best thing is that just by installing a plugin, you can start to create your own queries and configure your GraphQL endpoint for your frontend application.
Any doubt or trouble, let us know in the comment section!
More on The Topic
- 2) Enhancing Enterprise Digital Infrastructure with WordPress Solutions.docx
- From Planning to Deployment: Creating a WordPress Strategy for Enterprises
- WordPress Multisite: Managing Large-Scale Web Presences Efficiently
- PHP 8.4 Is Here: A Comprehensive Overview of the Latest Features
- Advanced Custom Fields in WordPress: Unlocking New Potentials for Enterprises
Tags: appapplicationdataflexibilityGraphQLJSONpluginqueryREST APIWordPress REST APIwordpress website