Your guide to understanding and using the API in WordPress

The API is one of the wonderful programming technologies that gives power to websites, and it can be used in two aspects. Through it, it can allow external programs to interact with the WordPress system without the need to deal with its graphical interfaces.

On the other hand, you can use it to allow the WordPress system to benefit from external application data and display it within your site with ease. For example, when you provide on your site to accept online payments using one of the payment gateways, you are in fact interacting with the API of this gateway to complete the payment process easily and securely. .

The WordPress system provides several interfaces that work behind the scenes and perform many functions in templates, plugins, content management, etc. For example, WordPress has an interface called the Shortcode API that enables you to use short codes in WordPress, and an interface called the Plugin API that helps in making plugins, but the REST API interface Which is also known as the JSON REST API, is the most famous interface and gives power to the WordPress system.

In today’s article, we will learn about the concept of the REST API for the WordPress system and explain how external applications can benefit from it to obtain data from WordPress sites and exchange data between different applications easily and flexibly.

What is the REST API in WordPress?

First, let us learn about the concept of the application programming interface (API), which is an abbreviation of three words ( Application Programming Interface ) . It is a set of rules that determine how to communicate between applications or programming interfaces . Its goal is to separate the backend of the application from the frontend by providing certain points that can Through which you can access data to read, modify, and delete it.

Thus, the interface provides developers with a simple way to access and deal with data easily and flexibly without the need to delve into the complexities of programming functions.

The REST API, also known as RESTful APIs, is an application programming interface for WordPress that conforms to the design principles of REST. REST stands for Representational State Transfer, which is a protocol that uses specific rules and operations.

The REST API enables you to connect your WordPress site to external applications. For example, a developer can develop a web application, website, or mobile application and use the REST API to fetch data from a WordPress site and display it in this application or site.

Previously, it was necessary to install an external plugin on a WordPress site in order to be able to access the site’s JSON REST API, but today it has become part of the WordPress platform and any developer can deal with this interface and use it directly without any additional settings.

The REST API started as a small project on GitHub, then the Rest API was added to the WordPress 4.4 core partially, and then it was fully added in WordPress 4.7, and to this day it still receives many developments and modifications.

The REST API is the easiest way to integrate the WordPress backend, i.e. all the data on your site, with different front-end technologies and with mobile application technologies. It enables developers to interact with sites and send and receive data in the form of JSON objects without the need to access the user interface or with a database. Application-specific data.

This allows WordPress to act as a storage and retrieval system for publishing content on the web and making use of this content through what are known as paths and endpoints , which we will learn about the concept of these two terms in the following paragraphs.

The presence of the REST API means that all the content of your WordPress site (posts, pages, comments, custom posts, etc.) has become directly accessible in the form of raw data, and changes can be made to this data from outside the admin control panel or the traditional dashboard that is used. usually.

The data for the WordPress site is no longer just rows in a database, but rather it is objects in the JSON format , which is an abbreviation of J ava S ript O bject N otation, that is, encoding objects using JavaScript. It is considered an alternative format to XML and displays data in a more understandable format, so it is used by programming interfaces. Applications to transfer their data.

JSON is simply a mechanism that allows us to easily transfer data by packaging it into a specific format which is a textual representation of a JavaScript object and it stores your data in an array of key and value pairs.

For example, a WordPress article is represented as a JSON object as follows:

{
“id”: 1,
“title”: {
“rendered” : “Hello world!”
},
“content”: {
“rendered” : “Welcome to WordPress. This is your first post. Edit or delete it, then start publishing!”
}
}

Of course, the complete JSON object of the article in WordPress includes many other additional information about the article such as (metadata, author name, article link, etc.) and all the data is easily collected in JSON format to interact with your WordPress content easily and flexibly.

How the REST API works in WordPress

In order to be able to use the REST API in WordPress, you must know what are the ways in which you can interact with this interface, as this interface is communicated primarily through the Hypertext Transfer Protocol (HTTP) methods to accomplish the operations of create, read, and update. and delete data (known as CRUD operations)

As is known, the HTTP protocol is the basis for most web interactions. If you type a URL into a browser, you make a request , and the remote server receives your request and provides a response . This transaction is the basis of almost everything we do online. This protocol provides several methods known as HTTP methods, which are as follows:

  • GET : This method is used to fetch information from the server.
  • POST : This method is used to send information to the server.
  • PUT : This method is used to make modifications to and update the data in the server.
  • DELETE : This method is used to delete information from the server.

In fact, you use the API in many aspects of your WordPress site. When you log in to a site, your browser will send the GET method to the server, and this server, in turn, processes the request using the API and loads the login page for you.

Then you enter your login information and send it again through the POST method. If you want to change your password, in this case you must use the PUT method, and if you want to permanently delete your account, you will use the DELETE method in this case.

Some WordPress sites can also provide you with the feature of logging in to the site through a social networking account. This service works on your site through external application programming interfaces, which plays a major role in improving the user experience. APIs are also used when linking email marketing services like MailChimp to WordPress.

As you can see, the REST API is used in many applications in WordPress. It mainly relies on the Hypertext Transfer Protocol (HTTP) language to communicate between these applications, and uses JSON code as a lightweight and efficient format for storing data and transferring data.

Basic terms in REST API

When using the API in WordPress, there are a set of basic terms that you must know and become familiar with. Here is an explanation of the most important of these concepts:

Path

It is the URL that you type in a certain way that you enter to make the request. You have to specify the appropriate path to what you want to get, load the content from it and ask your application to get it (currently we will use the browser to send the request).

The base path for the WordPress REST API is always /wp-json/wp/v2/.
And the full path to refund the items will be

http://yourdomain.com/wp-json/wp/v2/

If you type this path in the browser for our WordPress website in Arabic

https://www.wppr.net/wp-json/wp/v2/

You will see the following result:

This messy and incomprehensible result that will appear to you in the browser is nothing but all the contents of your WordPress site. Although the JSON format is originally easy to read, the APIs display it in a compressed form as one long string on one line to save resources, and this makes it difficult to read. As you see.

You can use tools to convert JSON to a more readable format by installing a browser extension that formats the JSON result better, or you can use command editor tools to submit requests to the site, or rely on one of the platforms that provide a readable JSON format service known as ( JSON Pretty Print) if you want to get formatted and understandable results as follows:

A platform that converts JSON to an easy-to-read format

If we want to get only published site articles, the path used to retrieve articles is as follows:

http://yourdomain.com/wp-json/wp/v2/posts

Access point or endpoint

Each path ends at an endpoint. An endpoint can be considered a combination of a URL and an HTTP method.

Knowing access points is an essential step to mastering the API and using it in WordPress to develop your own projects.

The access point may for example be:

/ wp-json / wp / v2 / posts / 10

Here we added the two paths / posts and / 10 in order to tell our site to pass through the interface and get the articles. Fetch the article that has ID number 10 and return it to us.

Each path can have a number of different endpoints depending on the HTTP method used. For example, an article can contain the path /posts/291, and this path has three endings:

  • GET to get the article
  • PUT: To update the article.
  • DELETE: To delete the article.

It is expressed as follows:

GET https://example.com/wp-json/wp/v2/posts/291
POST https://example.com/wp-json/wp/v2/posts/291 -d ‘{“title”:”My New Title”}’
DELETE https://example.com/wp-json/wp/v2/posts/291

As you can see, these links enable you to accomplish tasks easily and hide from you all the complications that you would otherwise need. If you are dealing with traditional databases, you will not need to care about matters such as communicating with the site’s database, verifying the validity of the request, processing it, or responding to it.

Request and response

When you submit an endpoint, you are submitting a request to the server. If your endpoint is written correctly, you will receive a response with the information you want in JSON format, or you will receive an error message if you send the wrong endpoint.

JSON schema

Schema is the metadata that defines how the data we receive in response to sent requests is organized, so that the result of the request is structured data that you receive that follows a specific hierarchical structure.

Controller Classes

You can use Controller Classes to build and register a new REST route and define your endpoints, but this is advanced and we won’t go into detail in this article.

In most cases, it is enough to use the basic paths and endpoints that already exist to send requests through the WordPress API.

Authentication REST API

Authentication is used to determine how users interact with your site’s content. WordPress does not allow access to some data unless you prove your identity.

For example, if you want to update an article on the site, you will need to include the appropriate authentication information to be able to do this, otherwise it will be rejected.

There are several REST API authentication methods that can be used. The sender can put the username and password in the request header, or authentication can be done through API keys.

Authentication in API

Steps to use WordPress REST API in external applications

To access the WordPress API, retrieve specific data from it, and add new information using an access or endpoint, you must follow three basic steps:

1. Access the REST API

To access the WordPress REST API from any application you must send HTTP endpoints.
For example, to get a list of articles published on a WordPress website in Arabic in JSON format, you must write the following request and replace the URL with the address of your website.

wppr.net/wp-json/wp/v2/posts

This command returns you a list of all articles on our WordPress site in Arabic

2.Fetch a specific article using the REST API

The WordPress REST API allows you to fetch all kinds of data from WordPress so its practical applications are very flexible. You can get a specific article using this article’s ID if you want to display a specific article within your external application.

For example, you can use an endpoint like the following to get the article that has id=535 on the WordPress Arabic site by writing the following.

wppr.net/wp-json/wp/v2/posts/535

3. Add data to a specific publication

Suppose you want to use the REST API to modify a specific article and add metadata to it, for example, instead of just displaying it in your external application. In this case, you must use the POST method instead of GET. Of course, in this case, you first need to authenticate your application in order to allow you to modify the articles. Use POST only when you have permission to do so.

To add data to a specific article, you can write your request as follows:

yourwebsiteurl.com/wp-json/wp/v2/posts/535/meta؟value=newmetadata

For example, if you want to add metadata for an article with ID 535 you can use the following request:

yourwebsiteurl.com/wp-json/wp/v2/posts/535/meta?worktime=25

Once you are familiar with the most common endpoints and how to use them, it opens up a large number of possibilities for working with the interface and accomplishing the tasks you want with ease.

For more, I recommend checking out the official REST API guide , which includes all the detailed data related to the REST API and all the endpoints that are served by the REST APIs.

FAQ about REST API

In this paragraph, we will present to you the most important questions about the API in WordPress and explain their answers

  • What is a REST API?

It is an API that adheres to the principles of the REST (or RESTful) Internet protocol and uses HTTP requests to access and use data.

  • Is a REST API the same as an API?

A REST API is a subset of an API that adheres to the constraints of the REST architecture and interacts only over the HTTP protocol. The primary goal of the API is to unify data exchange between web services, and it relies on a different protocol depending on the type of API. While REST API is a method for building web services that interact via the HTTP protocol.

  • What is JSON?

Short for JavaScript Object Notation, it is an open standard file format used by REST API-based web services.

  • Do I need to install a WordPress REST API plugin to run the REST API?

The REST API system in WordPress works completely without the need for any external REST API plugins, but you may need to install some interface-related plugins to expand the functions of the default plugin and improve its user interface.

  • Can I disable the REST API in WordPress?

Some website owners want to completely disable a feature of their site for fear of it being exploited to hack the site or steal their content as attackers could try to access important data through this connection and view it elsewhere.

But before taking this step, it should be noted that many WordPress plugins, many WordPress templates, and the Gutenberg plugin editor itself today rely on the REST API to work and interact with the content management system, so completely disabling this plugin may cause some of your site’s functions to malfunction.

If you want to completely disable the REST API on your site, prevent interaction with the website’s API, and block its contents from external applications without permission, you can do this easily by writing the following code in the template functions file functions.php

add_filter( ‘rest_authentication_errors’, ‘wpar_no_rest_api_4_7’ );
function wpar_no_rest_api_4_7( $access ) {
return new WP_Error( ‘rest_cannot_access’, ‘Sory WPAR API NOT ALLOWED!’, array(
‘status’ => 403
) );
}

This code works with WordPress 4.7 and later versions only and does not require any external plugin on the site.

After writing this code in the functions.php file and saving the changes, if you try to request any path from the interface, you will get an error like the following:

But as we mentioned at the beginning, completely disabling the WordPress REST API is not a good idea, so it is better to partially block access to certain resources on your site to protect it. The easiest way to do this is to use a custom WordPress plugin such as the Disable REST API , which enables you to fully control the paths that users can access. Access them depending on their roles on the site.

What are the most important sources for learning REST API?

 

Conclusion

In today’s article, we learned about the REST API and its use in WordPress. We explained this interface, which became part of WordPress from WordPress 4.4 and enabled developers to obtain WordPress content by writing external applications and programming languages ​​other than PHP.

Through this interface, you, as a developer, will be able to manage all your content in WordPress, display your site using applications, external libraries, or frameworks such as React, Vue, or even Gatsby, and interact with your WordPress site through it without you needing to visit it and access its control panel!

This interface will open for you, as an application and website developer, broad horizons in dealing with WordPress and enable you to develop your own advanced applications and deal with the concept of Headless WordPress and create single-page applications. You can also, as a developer of WordPress templates and plugins, start adding content. And your custom settings in the form of access points Endpoints and allow you to interact with them in new ways and many other interesting uses..

Avatar photo
I am a young man who has been working in WordPress and e-marketing for 10 years. I would like to share my experience with you so that we can become professional in WordPress I will be happy to share the experience with you.