Use Python & WP’s REST API To Create a Post On WordPress

WordPress has a flexible and well-documented REST API for managing WordPress programmatically. This post includes an example of just one feature of that API: creating posts. I’m using the Python-WordPress-XMLRPC library, documented here.

Requirements

You must enable XML-RPC on your WordPress installation. If you are running WordPress 3.5 or higher, the setting is on by default. Otherwise, you can find it in Settings Writing > Remote Publishing.

You must be running Python 2.6+ or Python 3.x.

You need to install the library. If you use Pip, this is easy:

sudo pip install python-wordpress-xmlrpc
Code Example: Create A Post

Once you have the library installed, you can automate the creation of posts immediately. The following code

 


from wordpress_xmlrpc import WordPressPost
from wordpress_xmlrpc import Client
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc.methods.posts import NewPost

#For security, consider creating a user just for your script.
username = 'wordpress_username_here'
password = 'wordpress_password_here'
wp = Client('http://sandbox.nextfridayit.com/xmlrpc.php', username, password)
post = WordPressPost()

post.title = 'Automating WordPress'
post.content = 'This is the body of my new post.\n\n Here is a new line. <strong>HTML works fine!</strong>'
post.post_status = 'publish'

wp.call(NewPost(post))

Code Example: List WordPress Users

You can do a lot more than create posts with this library, and you should read up on all methods available to you here.  Here’s one fun example — List of users with logins to the blog:

 


from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.users import GetAuthors

#For security, consider creating a user just for your script.
username = 'wordpress_username_here'
password = 'wordpress_password_here'

wp = Client('http://sandbox.nextfridayit.com/xmlrpc.php', username, password)
print wp.call(GetAuthors())

I’m using a sandbox WordPress install for the above code. That sandbox has three users: andrew, sandbox_user_1, and sandbox_user_2. Running the code produces that output:

$ python list_users.py
[<WordPressAuthor: andrew>, <WordPressAuthor: sandbox_user_1>, <WordPressAuthor: sandbox_user_2>]
Related Resources