WordPress events

The WordPress API-REST, what you should know.

Full throttle app: WordPress is not just for the web

As we commented on Saturday 7 in the WordCamp Seville 2018 in the presentation Full throttle app: WordPress is not just for the web Here we leave you the post that we promised. We are going to collect all the information we share in our presentation. You can see our presentation at video from WordPress.tv.

What is an API-Rest.

According to the Wikipedia definition:

Application Programming Interface, abbreviated as API, is a set of subroutines, functions, and procedures (or methods, in object-oriented programming) offered by a certain library for use by other software such as an abstraction layer.

An API represents the communication capability between software components. 

What is an End Point.

When we talk about API-Rest a «end point» is that URL that receives or returns information.

For example: "https://2018.sevilla.wordcamp.org/wp-json/wp/v2/posts«

Basic End-Points provided by WordPress.

Get types:

./wp-json/wp/v2/types

It returns all the type post types in WordPress that are visible to the API.

Get states:

./wp-json/wp/v2/statuses

Returns the states of the inputs.

Get comments:

./wp-json/wp/v2/comments

Returns the comments.

Get taxonomy:

./wp-json/wp/v2/taxonomies

Returns all taxonomies up to and including custom post types.

Get category:

./wp-json/wp/v2/categories

Returns the categories.

Get tickets:

./wp-json/wp/v2/posts

Returns the last 10 WordPress articles. In order to bring more posts we add ./wp-json/wp/v2/posts/?per_page=50 (the maximum we can get this way is 100).

Get input:

./wp-json/wp/v2/post/

Returns the entry with the ID that we have indicated.

An APP with WordPress as API.

To illustrate an example we will use the web of the WordCamp Seville 2018. We will build an APP that extracts the entries from a website developed with WordPress and shows them as shown in the following image.

Appearance of the APP WordCamp Seville 2018

To start we have to find a way to get the blog posts, for this we will use the methods that WordPress gives us by default. Later we will see how to do it with a custom endpoint created by us.

Json format of WordPress posts.

First we'll pull out the posts they've created on their blog and analyze the data they're giving us. Through this url you will access the inputs in Json format. We will find a data structure that begins as follows,

// 20180720124038
// https://2018.sevilla.wordcamp.org/wp-json/wp/v2/posts

[
  {
    "id": 1410,
    "date": "2018-07-13T11:12:33",
    "date_gmt": "2018-07-13T09:12:33",
    "guid": {
      "rendered": "https://2018.sevilla.wordcamp.org/?p=1410"
    },
    "modified": "2018-07-13T11:12:33",
    "modified_gmt": "2018-07-13T09:12:33",
    "slug": "fotografias-realizadas-durante-la-wordcamp-sevilla-2018-by-ruben-sutilo",
    "status": "publish",
    "type": "post",
    "link": "https://2018.sevilla.wordcamp.org/2018/07/13/fotografias-realizadas-durante-la-wordcamp-sevilla-2018-by-ruben-sutilo/",
    "title": {
      "rendered": "Fotografías realizadas durante la WordCamp Sevilla 2018 by Ruben Sutilo"
    },
    "content": {
      "rendered"
    ....

Key elements of the data structure.

Now that we have this data open, we are going to see what are the key elements that we have to take into account.

...
"id": 1410,
...

The id of the post to which the data below belongs, this data is quite important when operating with our APP since we will need it if we want to consult this entry exclusively.

...
"link": "https://2018.sevilla.wordcamp.org/2018/07/13/fotografias-realizadas-durante-la-wordcamp-sevilla-2018-by-ruben-sutilo/",
...
    "content": {
      "rendered":
Fotos del fotógrafo Ruben Sutilo para la WordCamp...
...

Here we find the link of the entry in question and its content, in html format, important to remember since we will have to format it if we use this data in an APP.


"author": 7425830,
...

Finally, highlight the author data that is provided to us in this case, which is only the ID. We will need to save this ID to be able to query slightly more descriptive data, such as the name of the author, the avatar or the url to his website.

Json format of WordPress user data.

In order to show the username in the letters (Excerpt from the news of the first, part of the APP) that we had designed, we will need to make a call exclusively to obtain your name.


// 20180720134205
// https://2018.sevilla.wordcamp.org/wp-json/wp/v2/users/7425830

{
  "id": 7425830,
  "name": "Mariano Perez",
  "url": "http://industriasi.com",
  "description": "¡Qué decir!",
  "link": "https://2018.sevilla.wordcamp.org/author/mpcdigital/",
  "slug": "mpcdigital",
  "avatar_urls": {
    "24": "https://secure.gravatar.com/avatar/f961e62fc3f0c33193893a78929201cd?s=24&d=mm&r=g",
    "48": "https://secure.gravatar.com/avatar/f961e62fc3f0c33193893a78929201cd?s=48&d=mm&r=g",
    "96": "https://secure.gravatar.com/avatar/f961e62fc3f0c33193893a78929201cd?s=96&d=mm&r=g"
  },
  "meta": [
...

Key elements of the data structure

...
"name": "Mariano Perez",
...

The username that we will need to display it in the letter.

...
"url": "http://industriasi.com",
...

The URL to the author page.

...
  "avatar_urls": {
    "24": "https://secure.gravatar.com/avatar/f961e62fc3f0c33193893a78929201cd?s=24&d=mm&r=g",
    "48": "https://secure.gravatar.com/avatar/f961e62fc3f0c33193893a78929201cd?s=48&d=mm&r=g",
    "96": "https://secure.gravatar.com/avatar/f961e62fc3f0c33193893a78929201cd?s=96&d=mm&r=g"
  },
...

These are the URLs that will give us the cutouts of different sizes of the author's avatar.

Do I mount my API using only the methods provided by WordPress or with custom endpoints?

As you have seen previously, we had to make two calls, one to get post and the other to get author to be able to build each of the cards, that means that if we have 10 entries in our blog we will have to do:

For the first screen -> 11 calls, 1 for the posts + 10 for the author names and on the other hand for the second screen we would need 2 calls.

Using some custom endpoints like the ones we will program below, we summarize the calls to 1 for the first screen and 1 for the second.

A total saving of 11 calls to the API when we open the APP and click on a news item.

Create a plugin for your custom WordPress endpoints

All the functionalities that you program for your WordPress must be in a plugin. In the following link you can find the plugin that we program below so that you can gut it and see how it is done. Link to GitHub.

Register the necessary own routes.

...
  register_rest_route( 'wordapp/v1', '/noticias', array(
    'methods' => 'GET',
    'callback' => 'listar_noticias',
  ) );

  register_rest_route( 'WordAPP/v1', '/noticia/(?P\d+)', array(
    'methods' => 'GET',
    'callback' => 'noticia_por_id',
  ) );

...

With these snippets we define the 'news' and 'news' routes, with the GET method and when these URLs are consulted, the 'listar_noticias' and 'news_by_id' methods will be executed, which we will define in the following snippets.

Define the callback function

...
 function listar_noticias(){
  $listado_noticias = array();
  $args = array(
    			'numberposts' => 10
  );
  $posts_array = get_posts( $args );
//Recorremos los ultimos 10 post y generamos unos objetos con la información que necesitamos
  foreach ($posts_array as $entrada){
		array_push($listado_noticias,[
    	'ID'		     		     => $entrada -> ID,
    	'fechaEntrada'       => $entrada ->post_date,
    	'tituloEntrada'      => $entrada ->post_title,
    	'ExtractoEntrada'    => $entrada ->post_excerpt,
    	'nombreAutor'        => get_author_name( $entrada -> post_author),
      'urlImagenDestacada' => get_the_post_thumbnail_url($entrada -> ID),
    ]);
  }
 	return $listado_noticias;
}
...

Once this function is defined, what we do is generate an array with exactly the data we need for the first screen of the APP, therefore we do not need more calls to generate the summary "letters" of these.

For the second screen we'll use the 'news' route and define a function that gives us exactly the data we need.

...
function noticia_por_id($data){
	$datosNoticia=array();
	$noticia=get_post($data['id']);
//Generamos la noticia con la información que necesitamos concretamente
  $datosNoticia=[
		'fechaEntrada'        => $noticia ->post_date,
    'tituloEntrada'       => $noticia ->post_title,
	  'contenidoEntrada'    => $noticia ->post_content,
	  'nombreAutor'         => get_author_name( $noticia -> post_author),
		'avatarURL'	          => get_avatar_url( $noticia -> post_author ),
    'urlImagenDestacada'  => get_the_post_thumbnail_url($noticia -> ID),
  ];
	return $datosNoticia;
}
...

Conclusions about the WordPress API

It is a brutal feature that WordPress brings us by itself and that is not the most used. The ease of being able to create your own functions and endpoints makes the WordPress API a great option when developing the API for your project.

¡Subscribe to our newsletter and receive our offers, news and discounts directly to your email!