Categories
Python

Raspberry Pi – Access to WordPress with Python wordpress-api

Would not it be nice if the Raspberry Pi could create articles on my website, modify them and become an editor?
If you use WordPress on your website, it’s relatively easy, since WordPress from version 4.8 includes the REST interface as standard and there is a corresponding plugin for older versions.

Whether the interface is available, can be easily detected by attaching ‘wp-json’ to the URL for each WordPress web page. For example, http://www.henrykoch.de/wp-json should display a Json string in the browser:

"name":"www.HenryKoch.de","description":"","url":"http:\/\/www.henrykoch.de","home":"http:\/\/www.henrykoch.de\/de","gmt_offset":2,"timezone_string":"Europe\/Berlin"

Installation python wordpress-api

For the installation of the WordPress Api for python, I am followed this guide https://pypi.python.org/pypi/wordpress-api/1.2.2, which did not work immediately.
To get the API running, additional packages had to be installed.

So I came to the result (On the Raspberry Pi)

sudo apt-get update
sudo apt-get install libxml2-dev
sudo apt-get build-dep python3-lxml
pip install wordpress-api

Libxml and lxml were missing from me.

Authentication

I spent a lot of time here.
I really wanted an OAuth authentication and I failed with the described REST oauth1 plugin.
After a long back and forth I installed this plugin: WP OAuth Server

As seen on the pictures, there is an OAuth server entry after installation on the dashboard on the left side. There I created a user. If this is done, the user is listed and a client ID is specified. Consumer_key in the phthon script
In addition, the Secret Key can now be displayed -> consumer_secret in the python script.

first test script

#!/usr/bin/python
# -*- coding: utf-8 -*-
from wordpress import api as wpapi
from wordpress import API
 
wpapi = API(
    url="http://ai.henrykoch.de/", #your URL
    consumer_key="xxxxxxxxxxxxx", #your key
    consumer_secret="xxxxxxxxxxxxx", #your secret key
    api="wp-json",
    version="wp/v2",
    wp_user="xxx",    #your wp User
    wp_pass="xxx"     #wp users password
)
r = wpapi.get("posts")
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
print r.json()

The result

pi@raspberrypi:~/python/Wordpress $ python myscript.py
200
application/json; charset=UTF-8
UTF-8
[{"id":1,"date":"2017-08-08T15:25:58","date_gmt":"2017-08-08T13:25:58","guid":{"rendered":"http:\/\/ai.henrykoch.de\/?p=1"},"modified":"2017-08-08T15:38:46","modified_gmt":"2017-08-08T13:38:46","slug":
...