Auto post using python REST API

An example script to create a new post using the REST API:

import requests
from requests.auth import HTTPBasicAuth

# WordPress site and credentials
wp_url = 'https://your-wordpress-site.com/wp-json/wp/v2/posts'
username = 'your_username'
app_password = 'your_application_password'

# Post data
post_data = {
    'title': 'My New Post from Python',
    'content': 'This is the content of the post created using Python and HTTPS!',
    'status': 'publish'  # Use 'draft' to save as a draft instead
}

# Make the POST request to create a new post
response = requests.post(wp_url, json=post_data, auth=HTTPBasicAuth(username, app_password))

# Check if the request was successful
if response.status_code == 201:
    print("Post published successfully!")
    print("Post ID:", response.json().get('id'))
else:
    print("Failed to publish post")
    print("Response:", response.text)

If you encounter an errors, try directly excess to REST API end point using curl or browser. For my case, ‘https://bhinvestment.net/wp-json/wp/v2/posts’ works perfectly fine in browser, while it doesn’t work with curl.

$ curl https://bhinvestment.net/wp-json/wp/v2/posts
curl: (6) Could not resolve host: bhinvestment.net

The solution for me is adding ‘www’.

$ curl https://www.bhinvestment.net/wp-json/wp/v2/posts

Why? The three possible reasons provided by GPT was:

  1. DNS Configuration: The DNS settings may only have records for www.bhinvestment.net and not for bhinvestment.net. You can check and add an A or CNAME record for the root domain (bhinvestment.net) in your DNS provider’s settings, pointing it to the same IP as www.bhinvestment.net.

2. Web Server Configuration: Your server might be configured to respond to requests only for the www subdomain. To resolve this, ensure both www.bhinvestment.net and bhinvestment.net are set up as server aliases in your web server configuration file (e.g., Apache or Nginx).

3. Redirection: Often, websites redirect traffic from bhinvestment.net to www.bhinvestment.net (or vice versa). You can set up a redirection rule in your server configuration or at the DNS level to redirect all requests from bhinvestment.net to www.bhinvestment.net.

Leave a Comment