automate-wordpress-publishing-rest-api-guide

Automate WordPress Publishing via REST API: Complete Guide

Learn how to automate WordPress publishing with the REST API. Covers Application Passwords, Python upsert scripts, media uploads, and LiteSpeed caching.

Are you tired of copying and pasting articles into the WordPress editor one by one?

Manual publishing slows down your team, introduces formatting mistakes, and makes bulk updates painful.

The good news is that WordPress includes a built-in REST API. You can use it to publish posts, upload images, and update pages automatically. In this guide, we will show you how we automate WordPress publishing at TeckScaler. We will cover everything from quick cURL tests to a full Python script.

Executive Summary

  • Zero Extra Plugins Required: Every modern WordPress site includes the /wp-json/wp/v2/ REST API out of the box.
  • Safe Authentication: WordPress Application Passwords let your scripts authenticate over HTTPS without exposing your main admin password.
  • Idempotent Upserts: Checking for an existing slug before posting prevents duplicate URLs and keeps updates clean.
  • End-to-End Media Support: You can upload featured images directly to /wp-json/wp/v2/media and attach the returned media ID to your post.

Table of Contents

Why Automate WordPress Publishing?

When you manage technical documentation, news updates, or product landing pages, the standard block editor quickly becomes a bottleneck. You end up spending more time fixing spacing and uploading images than writing useful content.

Automating your workflow with the WordPress REST API treats your website like a clean deployment target. You can write in Markdown, validate your HTML locally, and push updates to production with a single command.

At TeckScaler, we use this exact pipeline to publish developer tool pages and technical guides directly from local files. It keeps our formatting consistent and removes human copy-paste errors.

Core WordPress REST API Endpoints

Before writing any code, it helps to know which built-in endpoints handle your content and media. All routes sit under your domain’s /wp-json/wp/v2/ base path.

Resource TypeEndpoint PathPrimary HTTP MethodsCommon Use Case
Blog Posts/wp-json/wp/v2/postsGET, POSTCreate, list, or update standard articles by ID or slug.
Static Pages/wp-json/wp/v2/pagesGET, POSTDeploy landing pages, tool hubs, or documentation pages.
Media Library/wp-json/wp/v2/mediaGET, POSTUpload JPEG, PNG, or WebP images and get their attachment ID.
Categories/wp-json/wp/v2/categoriesGET, POSTLook up category IDs to assign clean site taxonomies.
Tags/wp-json/wp/v2/tagsGET, POSTMap or create topic tags before publishing a post.
Automate WordPress Publishing via REST API: Complete Guide Data Chart

Method 1: Test the REST API with cURL (Beginner-Friendly)

If you have never used the WordPress REST API before, start with a quick terminal test. This confirms your hosting firewall and authentication work properly before you write a full script.

Step 1: Generate a WordPress Application Password

First, log in to your WordPress admin dashboard and go to Users > Profile. Scroll down to the Application Passwords section near the bottom of the page.

Enter a clear name like TeckScaler-CLI in the text box, then click Add New Application Password. WordPress will show a 24-character password separated by spaces. Copy and save it right away because it will not appear again.

Pro Tip: Never use your main WordPress login password in scripts. You can revoke an Application Password at any time without locking yourself out of your admin account.

Step 2: Verify Public Read Access

Next, open your terminal and test a public GET request against your site. Replace example.com with your own domain name.

curl -s "https://example.com/wp-json/wp/v2/posts?per_page=1"

If your API is active, WordPress returns a JSON array containing your latest post. If you see a 403 Forbidden or HTML challenge page, a security plugin or CDN rule is blocking API traffic.

Step 3: Create a Draft Post via cURL

Now test an authenticated POST request to create a safe draft post. Replace YOUR_USER and YOUR_APP_PASSWORD with your WordPress username and the Application Password you generated earlier.

curl -X POST "https://example.com/wp-json/wp/v2/posts" \
  -u "YOUR_USER:YOUR_APP_PASSWORD" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "REST API Test Draft",
    "content": "<p>Published via cURL.</p>",
    "status": "draft"
  }'

Check your Posts list in WordPress. You should see REST API Test Draft waiting safely in your drafts folder.

Method 2: Automate Publishing with a Python Upsert Script

Once cURL works, you can build a reusable Python script. It will handle both creating new posts and updating old ones. Using an “upsert” pattern (update if the slug exists, otherwise insert) stops duplicate posts from appearing.

Step 1: Set Up Environment Variables and Auth Headers

Store your site URL, username, and Application Password in a local .env file. Never hardcode secrets in Python. WordPress Application Passwords include spaces to make them easy to read, so your script should strip spaces before Base64 encoding the token.

import base64
import os
import requests

WP_SITE_URL = os.environ["WP_SITE_URL"].rstrip("/")
WP_USERNAME = os.environ["WP_USERNAME"]
WP_APP_PASSWORD = os.environ["WP_APP_PASSWORD"]


def get_auth_headers(username: str, app_password: str) -> dict:
    clean_password = app_password.replace(" ", "")
    raw_token = f"{username}:{clean_password}".encode("utf-8")
    encoded_token = base64.b64encode(raw_token).decode("utf-8")
    return {
        "Authorization": f"Basic {encoded_token}",
        "User-Agent": "TeckScaler-Automation/1.0",
    }

Step 2: Upload a Featured Image to the Media Library

Most articles need a featured image before going live. You can send raw image bytes directly to /wp-json/wp/v2/media with Content-Disposition and Content-Type headers, then save the returned id.

def upload_featured_image(site_url: str, headers: dict, file_path: str, filename: str) -> int:
    with open(file_path, "rb") as image_file:
        binary_data = image_file.read()

    upload_headers = headers.copy()
    upload_headers["Content-Disposition"] = f'attachment; filename="{filename}"'
    upload_headers["Content-Type"] = "image/jpeg"

    response = requests.post(
        f"{site_url}/wp-json/wp/v2/media",
        headers=upload_headers,
        data=binary_data,
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["id"]

Step 3: Run an Idempotent Post Upsert

Before sending a POST request to /wp-json/wp/v2/posts, query the endpoint by slug to check if the article exists. If WordPress returns a matching post, send your update to /wp-json/wp/v2/posts/{id}. That way, you keep the same URL and search history.

def upsert_post(site_url: str, headers: dict, payload: dict) -> dict:
    slug = payload["slug"]
    lookup = requests.get(
        f"{site_url}/wp-json/wp/v2/posts",
        headers=headers,
        params={"slug": slug, "status": "any"},
        timeout=15,
    )
    lookup.raise_for_status()
    existing = lookup.json()

    if existing:
        post_id = existing[0]["id"]
        endpoint = f"{site_url}/wp-json/wp/v2/posts/{post_id}"
    else:
        endpoint = f"{site_url}/wp-json/wp/v2/posts"

    response = requests.post(endpoint, headers=headers, json=payload, timeout=30)
    response.raise_for_status()
    return response.json()

Note: Passing "status": "any" in the lookup query ensures your script also finds existing drafts and scheduled posts, not just published ones.

Common Pitfalls and Troubleshooting Tips

Even with clean Python code, server configurations can block automated requests. Watch out for these three common issues when deploying to production:

  • Missing Authorization Header on Apache or LiteSpeed: Some shared hosts strip the Authorization header before PHP receives it. Adding SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 to .htaccess usually fixes 401 Unauthorized errors.
  • WAF and Bot Protection Blocks: Default Python User-Agent strings often trigger Cloudflare or ModSecurity blocks. Always set a descriptive custom User-Agent header in your requests.
  • Plain Permalinks Enabled: The /wp-json/ route requires pretty permalinks. Go to Settings > Permalinks in WordPress and make sure Post name (or any non-plain option) is active.

Frequently Asked Questions

Do I need a plugin to use the WordPress REST API?

No, you do not need any extra plugins for standard posts, pages, and media. The REST API has been built into WordPress core since version 4.7.

Are WordPress Application Passwords safe for automation?

Yes, Application Passwords are safe when used over HTTPS. Each password is scoped to a specific app name and can be revoked in one click without changing your main account password.

Can I update SEO titles and meta descriptions via the REST API?

Yes, you can update SEO metadata in code if your SEO plugin supports REST routes. For example, Rank Math provides /wp-json/rankmath/v1/updateMeta for setting titles, descriptions, and focus keywords.

Why does my REST API request return a 401 error even with the right password?

A 401 error usually means your web server is stripping the Authorization header. It can also happen if your site runs over plain HTTP instead of HTTPS. Application Passwords require HTTPS by default on live domains.

You May Also Like

We hope this guide helped you learn how to automate WordPress publishing with the REST API. Written by the TeckScaler Editorial Engineering Team. Ready to go deeper into your automation workflow?

Primary Sources and References

Leave a Reply

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