WordPress
Article

The WordPress JSON REST API

By Aleksander Koko

WordPress has a big market share of the web. REST APIs are a growing technique and a big opportunity for developers. Knowing how to create APIs and how to consume them gives you a great advantage. A REST API can be consumed everywhere. On mobile applications, on front-end (web apps) or any other devices that have access on the net.

Maybe your customer already has a site that is running on WordPress and also wants a mobile application. You can create the API using custom code and relying on the database but that can cause a lot of frustration. Maybe they’re in a hurry and want the API as soon as possible. In WordPress, it is as simple as installing a plugin.

In this article, we will give a general overview of the JSON REST API plugin. We will cover how this plugin works and the basic philosophy of the REST architecture.

Preparation

Grab the latest version of JSON REST API on WordPress plugin directory. Install and activate it. Now you have a REST API ready to use. You need a REST Client to test and explore it. There are many tools for that job. Don’t limit yourself to just these four tools. There are many other REST Clients.

The first one is cURL. It is a command line tool that can send different requests to the given endpoint. It is not only REST API related but it is a general HTTP Request tool. Many test examples on other articles are made using this tool. It’s the universal HTTP tool that can be translated to any programming language.

One of the tools I usually use is the PHPStorm REST Client. As I mainly work with this IDE when developing, it is easier for me using a tool that I can access faster. Many other IDE-s come with REST Client integrated to make REST API developing easier and faster.

The third one and the one that I highly recommend is Postman. It is the easiest and more intuitive REST client I have ever worked with. Unfortunately, is only available as a Chrome extension. If you are using Firefox there is a nice extension called RESTClient.

Postman and WordPress

Exploring the REST Architecture

The first thing you have to do is to check if this plugin works, where is its endpoint, the base URL that holds all the information about the schema, all the Resources (Collections) and the routes. The plugin adds a new field called “`Link`” on the header so check for that in the header of the Response. If you use Postman or any other GUI clients just inspect the header. If you use cURL execute this command to your homepage:

curl -I http://yoursite.com/

The header option grabs only the header. In my case the endpoint is local.wordpress.dev/wp-json. If you left the permalink to it’s default value on the settings, then you may have the link value something like this: http://local.wordpress.dev/?json_route=/.

It changes only the rewrite rules but not any other essential changes. Everything is the same in the two cases.

The index endpoint (or API endpoint) is the starting point. You can explore the whole API from there. It gives you all the information about the API. It gives information about the Collections, Entities and how they are mapped to routes. Make a GET request to your endpoint and see what it returns. On REST Clients it’s easy because you are dealing with GUI interface. Let’s see how is done using cURL.

curl http://local.wordpress.dev/wp-json/

In my case it returns a big JSON file that looks like this.

{
    "name": "Local WordPress Dev",
    "description": "Just another WordPress site",
    "URL": "http://local.wordpress.dev",
    "routes": {
        "/": {
            "supports": [
                "HEAD",
                "GET"
            ],
            "meta": {
                "self": "http://local.wordpress.dev/wp-json/"
            }
        },
        "/posts": {
            "supports": [
                "HEAD",
                "GET",
                "POST"
            ],
            "meta": {
                "self": "http://local.wordpress.dev/wp-json/posts"
            },
            "accepts_json": true
        },
        "/posts/<id>": {
            "supports": [
                "HEAD",
                "GET",
                "POST",
                "PUT",
                "PATCH",
                "DELETE"
            ],
            "accepts_json": true
        },
        "/posts/<id>/revisions": {
            "supports": [
                "HEAD",
                "GET"
            ]
        }
    },
    "authentication": [],
    "meta": {
        "links": {
            "help": "https://github.com/WP-API/WP-API",
            "profile": "https://raw.github.com/WP-API/WP-API/master/docs/schema.json"
        }
    }
}

Actually the response is too long so I removed most of it. The index route (endpoint) gives gives information about the title of the site, the description and it’s URL. All the Routes that you can find on the API are also mapped in the ‘routes’ field. posts, users, media, pages are Collections. Collections are a group of Entities. An Entity is a single post or a single page with its ID.

Let’s say we want to see the latest posts. The endpoint for the Collection is api_endpoint/posts. This returns the latest posts. The Entity is api_endpoint/posts/ID with the given ID as an argument. Using cURL, the command would be:

curl http://local.wordpress.dev/wp-json/posts

And:

curl http://local.wordpress.dev/wp-json/1

Retrieving data is a good thing but there are times when we want to post data.

POST, UPDATE, DELETE

I want to share some problems that I got when tried to post or delete data. First, you need to authenticate yourself. There are three ways you can authenticate.

The first one is using the cookies. This is one method not widely used when working with APIs. When a user navigates on the web, pages tend to store data on users side. The cookie method here is a bit different by using the nonces method.

The second one is the OAuth method. This plugin implements the version 1.0a of OAuth. This method is widely used. Google, Facebook, Twitter and Flickr use OAuth for third party authentication. OAuth is in version two but they have chosen to use version 1.0a. There is a big debate for the version two. Some big companies didn’t shift in version two for different reasons but mainly concerned about security.

The third one is the Basic Authentication. Using this method you have to send your username and password each time you make a request. Client tools for REST testing usually have this method implemented themselves. This method is mainly used when developing. Is rarely used on production. On production consider using OAuth.

Unfortunately, the Basic Authentication plugin is not updated to often. They concentrated all their efforts on the OAuth plugin. This plugin can’t be found on wordpress.org but only on it’s GitHub repository. You have to manually install it. On the plugin directory execute this command:

git clone https://github.com/WP-API/Basic-Auth basicAuth

Alternatively visit the GitHub page and download the plugin and install it manually via FTP.

Then go to the dashboard and activate it. This plugin has some problems with non-Apache servers. As I mainly use WordPress VVV which is a Vagrant installation, it has problems because VVV comes with nginx. Change the permalink configuration if yours is default. That worked for me.

Permalink configuration for REST API

Now that we have the authentication set up is time to create some posts. Postman has the basic authentication implemented. Insert the username and password if you use Postman and it will remember base 64 encoding each time it makes a request. To see if it works make a request in ‘index_endpoint/users/me’. It returns the information about you.

If you try to access this URL without using basic auth or any other authentication methods, the API will return:

[
    {
        "code": "json_not_logged_in",
        "message": "You are not currently logged in."
    }
]

Let’s try to make a request via cURL and also include the Basic Auth method:

curl --user admin:password http://local.wordpress.dev/wp-json/users/me

The --user option makes the admin:password argument which is basically just 64 encoding of that plain text. cURL builds itself the Request headers for the Basic Auth by adding an additional field. This is what it adds in my case:

Authorization: Basic YWRtaW46cGFzc3dvcmQ=

This is what is returned when I try to access my profile using the given credentials.

{
    "ID": 1,
    "username": "admin",
    "name": "admin",
    "first_name": "",
    "last_name": "",
    "nickname": "admin",
    "slug": "admin",
    "URL": "",
    "avatar": "http://0.gravatar.com/avatar/06e92fdf4a9a63441dff65945114b47f?s=96",
    "description": "",
    "registered": "2014-07-17T22:59:59+00:00",
    "roles": [
        "administrator"
    ],
    "capabilities": {
        "switch_themes": true,
        "edit_themes": true,
        "activate_plugins": true,
        "edit_plugins": true,
        "edit_users": true,
        "edit_files": true,
        "manage_options": true,
        "moderate_comments": true,
        "manage_categories": true,
        "manage_links": true,
        "upload_files": true,
        "import": true,
        "administrator": true
    },
    "email": false,
    "meta": {
        "links": {
            "self": "http://local.wordpress.dev/wp-json/users/1",
            "archives": "http://local.wordpress.dev/wp-json/users/1/posts"
        }
    }
}

Let’s try to delete one post. To delete one post we must know it’s URL. It’s URL is api_endpoint/posts/ID. Replace the ID with 1 or any other post ID that you want. Don’t forget that you should use authentication to delete something.

curl --user admin:password -X DELETE http://local.wordpress.dev/wp-json/posts/4

If using Postman or similar send the URL above (http://local.wordpress.dev/wp-json/posts/4) and select the ‘Delete’ request method from the dropdown list next to the URL field.

And this is what I get back:

{
    "message":"Deleted post"
}

Posting a new record (post for example) is easy too. Create a new JSON file with two fields. One for the title and one for the content.

{
    "title": "This is a post",
    "content_raw": "This is some content"
}

Send that new data to the Collection of that Entity that we want to create. Remember that when posting new Entity, you should post it in the Collection endpoint. Here we used Basic Auth again. -X POST makes this request a POST Request. --data captures a file that is in that folder and sends it as raw data.

curl --user admin:password -X POST  http://local.wordpress.dev/wp-json/posts --data @data.json

Further Exploration

Don’t limit yourself. WordPress REST API team has also some other tools that are tightly integrated with this plugin. They have a Client Cli, Client JS and a Client PHP to work with your API right out of the box. Also head over their documentation for deeper technical information.

Knowing how to use this plugin is one thing but the best advice I can give in this case is: ‘don’t limit yourself’. There is so much information out there about REST. Here on SitePoint we have a nice series about building a REST API from scratch by Vito Tardia.

Conclusion

Creating a REST API on WordPress is easy. You don’t have to create one from scratch if you’re using WordPress. As a matter of fact, the index end-point tells you everything about this plugin and how to use it. We covered Collections, Entities and how to manipulate some data using different verbs (GET, POST, PUT, DELETE).

An important aspect when developing is also authentication so we covered this as well. Consider OAuth 1.0a when developing for production. You can also use Basic Auth but OAuth is already tested and backed by a number of big companies.

What do you think about REST APIs on WordPress? Does it compete with the hand crafted APIs? Do you know any other WordPress plugins about REST? Please let us know in the comments below.

More:
  • http://space-rocket.com/ Michael Chavez

    Wow this is perfect timing for what I am working on right now. I was wondering what do you think of JSON API (https://wordpress.org/plugins/json-api/) VS JSON REST API https://wordpress.org/plugins/json-rest-api/)? Thanks for the awesome article.

  • http://danemorgan.com/ Dane Morgan

    Would this allow you to build a posting app that included access to fields added by plugins like WPSEO and or custom fields?

    • Keith Penderis

      https://developer.wordpress.com/docs/api/1/post/sites/%24site/posts/%24post_ID/ I think it is possible as you can post meta data when updating. meta_custom_name => value sort of situation.

      • mindctrl

        You linked to the JSON API on wordpress.com, which is a different API than the one linked in this article. For documentation on the API discussed here, see the documentation here. http://wp-api.org/

    • Aleksander Koko

      I haven’t tried how extendable it really is but I think that it will allow.

  • amitasthana

    Hey, that is a great article thank you for that. I was wondering can we also search in all the blog posts using the API?

    • Aleksander Koko

      Searching inside the content?

      • amitasthana

        Yeah, inside the content, or may be just in the title(heading) of the article.

      • amitasthana

        yes

  • Maruti Mohanty

    Nice article. Got some nice insights on how to use the wp rest api.

    I tried it on a ‘Nginx’ server and the authentication fails all the time, the call which doesn’t require authentication works fine though. Where as I tried the same in my local setup which is an apache server (ubuntu) and it works. Do you have any idea how to make this work for Nginx.

    Whenever I try “curl –user admin:password http://www.example.com/wp-json/users/me” I get

    {

    “code”: “json_not_logged_in”,

    “message”: “You are not currently logged in.”

    }

    for Nginx server

    Thanks in Advance

    • vloo

      Hey, Maruti, did you manage to cope with your problem? I’m trying really hard with OAuth1a and getting the same result. After that I tried with basic authentication like the example in this post and the result is the same…

  • http://ericnjanga.com Eric Njanga

    Great article. I was precisely looking for a way to use a REST API with a WordPress theme I am working on.

    Thanks.

  • Craig Harwood

    Very good article breaking down the ins and outs or the api. As an aside, have you come across any similarly detailed articles on implementing wp-api via oauth?

    • Aleksander Koko

      Actually I havent. This was just a quick experimentation I did some time ago :)

  • Rafael Gama
  • Иван Шшш

    Hello, guys! Is any one resolve the problem with working of basic authentication and OAuth1a on Nginx server ?

  • Sustainable House Day

    How is the speed in terms of sending back responses? Do the api endpoints load all the same code? I love wordpress but find initial response time to be slow, is this API plugin a way around this?

  • Abdul

    Hy Aleksander Koko! thanks for this great guide on WP REST API, i’m working on Rapid Application development and i want add an opetion into my applicatin for wordpress Dashboard, Actually i want user selects option on front end through checkboxes OR other selecters to creat it’s own customized dashboard for WP, how can i create a Custom WordPress Dashboard through API calls?
    help me Plz! Thanks in Advanced!

  • Ashu Sharma

    Very good article

    • Aleksander Koko

      Thanks :)

    • Aleksander Koko

      Thanks :)

  • Isuru Nanayakkara

    Very good article to get started on WP API. Thanks!

  • http://www.cygnet-infotech.com/ Hemang Rindani

    Thanks for the insights. WordPress has certainly grown to a stature where a developer can bank on it blindly for implementing any business requirement. With powerful back-end technology support and effortless front-end development console, WordPress is rightfully one of the best enterprise content management systems available. Advancement of technology has given freedom to developers for designing websites using painless Application program Interfaces (API) Automattic (CMS development company for WP CMS) has ensured to provide API support with WP platforms. Latest version of WP is moving towards becoming a fully-fledged application framework by implementing first half of REST API. The plugin allows to display content from various WordPress sites and also to save content from other sites, not necessarily WP sites. Previously this type of integration was only available through XML-RPC However, the new REST API uses JSON, which is basically a universal connector for data on the internet. Most of the programming languages has easy way to convert their data structures to JSON and PHP, the base language of WP, have json_encode() and json_decode() to translate from PHP arrays or objects into JSON or the other way around. Features as such surely attract developers and thus has alreadly been used by lakhs of WP users.

  • Judy Wong

    Nice article it took me a long time wondering what happened to the authentication and your article helps! :)

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Instant Website Review

Use Woorank to analyze and optimize your website to improve your website to improve your ranking!

Run a review to see how your site can improve across 70+ metrics!

Get the latest in WordPress, once a week, for free.