Objective
Post comment on a WordPress installation from an external application and via the WP REST API.
Problem
To create, POST, to WordPress there must be some type of authenticated user. Most of the time the user posting is the user who is logged in. WordPress allows unauthenticated users to submit comments, but in most cases if not all, the comments will be held in moderation. Moderation allows for sufficient time and inspection to keep comment quality high. If not, then any spammer could take advantage.
In this context, I want to allow an application to post to a specific post. So let’s get ourselves in order and discuss what we know and what we don’t.
What we know
To post you must be authenticated as a user. This will let an application post, but you will see how that application is authenticated and associated with an actual user. To post to this particular WP installation I need a user’s email, name, and the comment from the user. I also need the post ID to which I want to post a comment to.
There are a few different types of authentication to use here. The most popular form is by cookie, that is what we use to log in and move from page to page on any WP instance. To allow applications to post, I need to authenticate with oAuth1.0a.
oAuth 1.0a in WordPress
This form of authentication requires a server to generate keys and secret tokens. There is a few back and forth steps that the oAuth server, the posting application, and the signed in user.
Dependencies
Three main things will be needed to accomplish this process. First is a local installation of WordPress. I prefer MAMP Pro as my local server. There are free versions of MAMP as well as a plethora free and paid options. There are also many open-source options some of which are preferred by the WordPress core team. I have always used MAMP so if you don’t already have a preference or a strong preference, just use it too.
Next, you’ll need to get Postman. Postman is an API Development application. It will do a few things for users to test out proofs-of-concept like adding nonces and timestamps. While the application that will eventually be doing the posting will have to code these for themselves, Postman does it for us now so we don’t have to mess around with it. We’ll get the connection setup and then backfill for security, validation, and verification. To this end, we’re not doing any form sanitation either so we can keep our concept as simple as possible. The cost of simplicity is security. But we’re posting to a throwaway version of WP and it’s all happening on our own computers.
Finally, the authentication server. This sounds fancy but it’s just a plugin that can be found in the WordPress repository. There are several flavors of this as well, but I went with the one recommended by the WP REST API Team, WordPress REST API – OAuth 1.0a Server
Now that we know what we’re going to do and why let’s step through this process and post a comment or two to our WordPress installation on our local machines.
Process
Set Up a scratchpad
You’ll be doing a fair amount of copy and pasting. Some of the things you’ll be working with will have different names depending on what application you happen to be copying or pasting to or from. I’ve done this a few times already so my advice is for you to create a scratch pad. I’ll add a table here so you can copy and paste this into a plain text file or something similar. There are subtle differences, but working in a profession where a single misplaced period can break your application, semantics matter.
Client Key (Consumer Key, oauth_consumer_key) | |
Client Secret (Consumer Secret) | |
Access Token (oauth_token)1st | |
Access Token (oauth_token)2nd | |
Token Secret (oauth_token_secret)1st | |
Token Secret (oauth_token_secret) 2nd | |
Verification Token(oauth_verifier) |
Set Up OAuth Server
Install the OAuth 1.0a server. It’s a plugin so, install it and activate it. Now you need to create an “application” to associate with your account. Navigate to Users> Applications, it’s a new user type in the Users admin menu. All three fields here are required despite the notification as such. I used Postman, A local version, and ‘oob’, respectively.
For the callback, I use ‘oob’. This will return the verifier token to the user to copy and paste into their applications; Postman. Read more about Out of Band here on the official documentation website.
Click the Add Consumer button to save the Application and for it to generate the OAuth Credentials. These will comprise of a Client Key and a Client Secret.
Setup Postman
Open a new tab. Under the Authorization tab, click Type and select OAuth 1.0.
Take your two new credentials generated from WP to Postman. Client Key -> Consumer Key, Client Secret -> Consumer Secret. Also, under the ‘Add authorization data to’ selection, you choose ‘Request Headers’. Add the URL that you want to post to use to generate the next steps; the next verification step. The slug will be /oauth1/request so URL to my installation of WordPress is http://wordpress/oauth1/request. Once you make the GET request Postman will return to you a response that you’ll use later. This last step can be weird. While making this tutorial, I had to click the button several times to get it to work.
Copy and paste that new response to your scratch sheet. We’re going to use it shortly.
Authorize time
Now you’re going to set up to authorize your application with these newly generated credentials.
Use this URL with parameters to authorize the app to WordPress:
http://wordpress/oauth1/authorize
In a Browser make a request to this URL. Add parameters to the URL of oauth_consumer_key, oauth_token, oauth_secret_token. Remember the scratch sheet and the different names for everything? This is where it gets handy. My URL looks like this:
http://wordpress/wp-login.php?action=oauth1_authorize&oauth_consumer_key=OeuqGqfNQk4H&oauth_token=LVMe9a8YQ6oGlapTNYPAwF0T&oauth_token_secret=nwDBzX446H10a0tTGVSaP1clphTxuvFtZWdErHgrwJsWNegT
I built the URL in Postman but called in Chrome. Regardless, you’ll get a page that looks like this:
Click Authorize on the new page and you’ll get a Verification Token back. Copy it to your scratch pad. The Verification Token screen that you get back should look like this.
In my case, I want to post to: http://wordpress/wp-json/wp/v2/comments
. I will also add a specific URL parameter with the specific post ID to which I want to comment to. My URL will look like this.http://wordpress/wp-json/wp/v2/comments?post=295
You can add URL parameters in Postman’s interface which is one of the reasons why it is so handy to use.
Next, Build the Access URL
Open up Postman and get yourself a new tab. Save it as Access. Add your Consumer Key, Consumer Secret, Access Token, and Token Secret. Add Params to the URL of http://wordpress/oauth1/access of oauth_verfier and the value of your Verification Token that you just received. Click Preview Request and then click Send. Here is an image of my Postman instance.
You should get a response back that looks like this. It has new oauth_token and a new oauth_token_secret. These will replace the original ones. Add these to your scratch pad.
Now you’ll replace the first versions of these tokens with the new ones.
We are going to make a POST to our WordPress installation. To do that you need to know what WP post you want to POST to (careful of the different posts(POST)s). We will identify that WP post by its ID. So looking at the WP REST API docs if we want to POST to post we add that post ID to the URL as a parameter. If you don’t know the post ID you can find it by installing a Post ID plugin or viewing that post’s edit screen URL. The post ID will be at the URL. Here’s a post with no comments and we can see the post ID in the URL.
We build our URL according to the WP REST API docs like this. http://wordpress/wp-json/wp/v2/comments, but we want to post to a specific post so we append that post ID to the end of the URL as a parameter like so: http://wordpress/wp-json/wp/v2/comments?post=309 Build this URL in Postman or just append the ID to the URL it doesn’t matter. I like Postman because you can save it and share it with your team. You will also have to add some Headers as well.
Add a Header equal to Content-Type
and a Value equal to application/x-www-form-urlencoded
. You will also need to add the value of the comment. Some application requires you to have a name and an email associated with the comment so that is what I’ll demonstrate. Here are the official WP REST API docs on what you can send and how you should format it.
If you’re following along then this is what your Postman instance should look like. I already showed you the empty comment area of the post to which I’m posting to. Now, just click Send in Postman and refresh your WordPress installation to see your comment create on a 3rd party application appear!
Here’s the response from Postman and here is the comment attached to the specific post. You’re done.
Congratulations, you’ve successfully set up Postman to begin testing you WP REST API. There is a lot of other value in this process as well. For instance, you can see just how may HTTP methods there are for working with data. There is likely an appreciation for the other types of authentication services out there. You could use Username and password, but it’s not secure. At this time, I don’t think that using OAuth2.0 is available for this out of the box because OAuth 2.0 requires HTTPS, something that WordPress does not require. Backwards compatibility right?
Bear in mind, that Postman did a lot of work for us. When you add this to your application you’ll have to secure your tokens. You’ll have to create nonces and time stamps. You have to add parameters to URL and set headers. So remember that this is for testing and proof of concept only. But it’s a big first step in working with this really powerful WP REST API.