Posting from the Mac using the REST API

# As mentioned before, in lieu of Drafts on the Mac, I wanted to create some kind of simple method to post to the blog using the REST API without having to install any others apps. My idea was to create something in PHP that emulates the action I use on the phone.

Yesterday I set about creating a simple page with the absolute minimum of options. When running the Drafts action I am presented with this:

Drafts prompt

So, I started with a normal HTML form using the post method but without an action meaning the field values get passed back to the same page. I added a little JavaScript to show/hide the title field based on whether I'm creating a status or full post and a 'key' field to act as a security check.

Each of the form fields is assigned to a variable using the standard $title = $_POST['title']; ready for submitting to the API. Then, just like the Drafts action, I build the post data array:

$post = [
    'title' => $title,
    'content' => $body,
    'status' => $status,
    'format' => $format,

$headers = [
    'Authorization: Basic /* base64 encoded auth string here */ ',

Then, if the security key is correct (a complex password that I can retrieve from Keychain) I use curl to do the actual posting:

$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);

before getting the new post id from the response so I can redirect to the post:

$json = json_decode($response, true);
$id = $json['id'];
$newurl = ''.$id.'&preview=true';
header("Location: $newurl");

The final form looks like this:

PHP post

The whole thing was considerably easier than I expected, it was really just a case of translating JavaScript to PHP and ensuring I had the curl stuff right. The final step was to make a WordPress page template out of it so it is truly self hosted.

As pointed out in previous comments I could look at creating something in AppleScript to save having to copy/paste but that's for another time and this is perfectly serviceable.

(This was posted from the Mac via the new method.)