Publishing to WordPress via the REST API from R (with httr and JWT)

The WordPress REST API is awesome.

For a project I was working on this week I needed to be able to publish pages to WordPress via the API from R. Needless to say, there aren’t a ton of resources available online about how to do this (read: none). After fighting a losing battle between httr’s implementation of OAuth and the WordPress implementation of OAuth in Jetpack, I decided to try using JSON Web Tokens for authentication. That finally got things moving.

Here are the steps I took to get things up and working.

1. Create a throw away WordPress instance to work against. You don’t want to be experimenting with publishing and deleting posts on a blog you actually care about. Once you’ve figured everything out and have all the content published you want to publish, you can use Tools => Export to move the finished product to the blog you actually want the content to live on. (You should probably be doing this on Reclaim Hosting.)

2. Install the JWT Authentication for WP REST API plugin. As you follow the installation steps, make sure that the two lines you add to your .htaccess file come immediately below the RewriteEngine on directive. If you put them further down (e.g., below the WordPress directives) it will not work. Your .htaccess file will look like:


# BEGIN WordPress
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) – [E=HTTP_AUTHORIZATION:%1]
RewriteEngine On
RewriteBase /throwaway/

view raw

.htaccess

hosted with ❤ by GitHub

3. Install the httr library for R if you don’t already have it.

install.packages("httr")

4. You’re ready to go! Here’s the code I’m using to publish from within RStudio (you’ll need to change the URL and credentials to match your own):


library(httr)
# Get the JWT
get_jwt <- POST("https://example.com/throwaway/wp-json/jwt-auth/v1/token",
query = list(username = "your_username", password = "your_password"))
token <- content(get_jwt)$token
# Confirm auth is working
test <- POST("https://example.com/throwaway/wp-json/jwt-auth/v1/token/validate",
add_headers('Authorization' = paste("Bearer", token, sep = " ")), encode = "json")
content(test)
# Publish page
create_page <- POST("https://example.com/throwaway//wp-json/wp/v2/pages",
add_headers('Authorization' = paste("Bearer", token, sep = " ")),
body = list(title = page_title, content = payload, status = "published"), encode = "json")

Comments are closed.