WordPress rest API – CRUD example with a post

 

This tutorial is a brief introduction on how to do requests to a WordPress site using the REST API of WordPress. I will explain how to do the basic configurations and steps to make requests in the WordPress backend from any frontend (React, jQuery) or backend (PHP, Python, Node.js).

 

For this article, we are creating a CRUD for a post and we are going to use Javascript in order to do the different requests (POST, DELETE, GET, PUT) to our WordPress backend. The REST API has been included in WordPress 4.7 so that you can ask some requests to API.

 

For example:

 

With Javascript, we are going to do a GET request in order to get all posts on the site: http://wordpress.dev/wp-json/wp/v2/posts

 

fetch('http://wordpress.dev/wp-json/wp/v2/posts').then(function(response){
   return response.json();
}).then(function(posts){
   console.log(posts);
});

 

And this should return something like this json:

 

[
    {
        "id": 1,
        "date": "2018-04-24T19:37:02",
        "date_gmt": "2018-04-24T19:37:02",
        "guid": {
            "rendered": "http://wordpress.dev/?p=1"
        },
        "modified": "2018-04-24T21:46:13",
        "modified_gmt": "2018-04-24T21:46:13",
        "slug": "lorem-ipsum-dolor-sit-amet",
        "status": "publish",
        "type": "post",
        "link": "http://wordpress.dev/lorem-ipsum-dolor-sit-amet/",
        "title": {
            "rendered": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
        },
        "content": {
            "rendered": "

 

Did you try it? Ok,

 

with this example there shouldn’t be any problems because it is public data so it doesn’t need permissions for the administrator to see it.

 

Now let’s try something different, we will create a new post using the WP Rest API and it goes like this:

 

Before creating the CRUD for a post, we have to know that WP Rest API uses cookies for authentication, so we need to add alternative modes to support authentication that will work from remote applications. For this WordPress recommends installing and setting up JWT Authentication for WP REST API in order to use a token that will allow us to request permissions for the WordPress site:

 

Authentication

 

fetch('http://wordpress.dev/wp-json/jwt-auth/v1/token',{
    method: "POST",
    headers:{
        'Content-Type': 'application/json',
        'accept': 'application/json',
    },
    body:JSON.stringify({
        username: 'admin',
        password: '123456'
    })
}).then(function(response){
    return response.json();
}).then(function(user){
    console.log(user.token);
});

 

It will return a token, so save it in a cookie or localstorage in order to use it in all requests that require permissions.

 

Don’t forget to save it!

 

CREATE A POST

 

To do so you’ll have to do the following, in the Headers parameters, send a parameter called ‘Authorization’, it should have the ‘Bearer’ string followed by the token just how it’s shown below:

 

 

/*
 * The token that was returned by authentication request
 * user.token
 */
var token = user.token;

fetch('http://wordpress.dev/wp-json/wp/v2/posts',{
    method: "POST",
    headers:{
        'Content-Type': 'application/json',
        'accept': 'application/json',
        'Authorization': 'Bearer '+user.token
    },
    body:JSON.stringify({
        title: 'Lorem ipsum dolor sit amet',
        content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
        status: 'publish'
    })
}).then(function(response){
    return response.json();
}).then(function(post){
    console.log(post);
});

 

READ THE POST

 

For this one, we just have to send the ID of  the post we want to consult at the end of the URL. Check it out:

 

fetch('http://wordpress.dev/wp-json/wp/v2/posts/',{
    method: "GET",
    headers:{
        'Content-Type': 'application/json',
        'accept': 'application/json',
        'Authorization': 'Bearer '+user.token
    }
}).then(function(response){
    return response.json();
}).then(function(post){
    console.log(post);
});

 

UPDATE THE POST

 

Equally important, so we’ll have to send the ID of the post we want to consult at the end of the URL and additionally, we have to send the parameters that will be updated (title, content, status, etc).

 

fetch('http://wordpress.dev/wp-json/wp/v2/posts/',{
    method: "POST",
    headers:{
        'Content-Type': 'application/json',
        'accept': 'application/json',
        'Authorization': 'Bearer '+user.token
    },
    body:JSON.stringify({
        title: 'Lorem ipsum dolor sit amet - updated',
        content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. - updated',
        status: 'draft'
    })
}).then(function(response){
    return response.json();
}).then(function(post){
    console.log(post);
});

 

DELETE THE POST

 

And in case you need to delete the post, just send the ID of the post you want to consult at the end of the URL.

 

fetch('http://wordpress.dev/wp-json/wp/v2/posts/8',{
    method: "DELETE",
    headers:{
        'Content-Type': 'application/json',
        'accept': 'application/json',
        'Authorization': 'Bearer '+token
    }
}).then(function(response){
    return response.json();
}).then(function(post){
    console.log(post);
});

 

Sources

 

https://developer.wordpress.org/rest-api/reference/

https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

https://en.wikipedia.org/wiki/Create,_read,_update_and_delete

 

As you can see it’s not that hard… See you on the next one!