Inserting A Post Using The WordPress Rest API With Basic Authentication – Lightsail Bitnami Stack

Inserting A Post Using The WordPress Rest API With Basic Authentication – Lightsail Bitnami Stack

Very quick post here mainly so I don’t forget myself.

I am using postman and I want to insert a post into my website using the Wp REST API.

First things first install this plugin in the plugins directory.

https://github.com/WP-API/Basic-Auth

Bitnami stacks seem to work a bit differently to say your local host setup you actually edit most of the .htaccess functionality via the config file.

I have a WordPress stack setup in /apps/wordpress you can access your conf files in.

~/apps/wordpress/conf

In this folder you want to edit the file httpd-app.conf

sudo vim httpd-app.conf

The right above the other RewriteEngine rules add this.

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

Make sure you restart Apache.

sudo /opt/bitnami/ctlscript.sh restart apache

Now you can use postman to insert your new post.

https://example.com/wp-json/wp/v2/posts/

I am also doing this in a AWS Lambda function like this using the https module.

var wp_data = querystring.stringify({
    title: 'Title',
    content: 'Hello',
    post_status: 'publish'
});

var auth = 'Basic ' + Buffer.from('user:password').toString('base64');

var req = https.request({
    hostname: 'example.com',
    port: 443,
    path: '/wp-json/wp/v2/posts',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': wp_data.length,
        'Authorization': auth
    }
}, function(res) {

    res.setEncoding('utf8');

    res.on('data', function(response) {

        var resp = JSON.parse(response);

        console.log(resp);

    });

});

req.on('error', function(err) {

    console.log(JSON.stringify(err));
});

req.write(wp_data);

req.end();

Leave a comment

Your email address will not be published. Required fields are marked *