When building web applications or content management tools, there are often situations where we need to post content to WordPress programmatically. By tapping into WordPress’s REST API, this process becomes highly efficient. In this guide, I’ll show you how to use axios
and TypeScript to post content to a WordPress site.
Thank me by sharing on Twitter 🙏
The approach here leverages WordPress’s Application Passwords, which are particularly handy for creating secure API requests. With a few TypeScript configurations and authentication setups, posting to WordPress will feel straightforward and manageable. This tutorial focuses on WordPress installations running on a local server (http://localhost:8080) but can easily be adapted for live environments.
Why Use Axios with WordPress REST API?
The WordPress REST API has become a powerful tool for developers, allowing interaction with WordPress content through external applications. Axios, a popular HTTP client, fits perfectly here for its simplicity and powerful features like automatic JSON transformations, easy error handling, and async support.
Combining TypeScript’s strict typing with Axios’s HTTP functionalities offers a great experience for building stable, predictable scripts.
Setting Up WordPress for API Access with Application Passwords
To interact securely with WordPress’s REST API, we need a form of authentication that WordPress accepts. Here, I’ll use Application Passwords, which allow secure API requests without exposing the main password for the WordPress account. Let’s go through how to set this up.
COLORCORAL Cleaning Gel Universal Dust Cleaner for PC Keyboard Car Detailing Office Electronics Laptop Dusting Kit Computer Dust Remover, Stocking Stuffers for Men Women Kids Teens 160g
$6.98 (as of December 21, 2024 08:38 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)The Art and Making of Arcane (Gaming)
$56.94 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Syntech USB C to USB Adapter Pack of 2 USB C Male to USB 3.0 Female Adapter Compatible with MacBook Pro Air 2024, Microsoft Surface, iPad,Samsung Notebook, Dell XPS and More Type C Devices,Space Grey
$9.99 (as of December 21, 2024 08:38 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)1. Enabling Application Passwords
To start, ensure that your WordPress setup has Application Passwords enabled. For WordPress versions 5.6 and above, this feature is generally available by default, though certain installations may require you to enable it.
Here’s how to generate an Application Password:
- Go to your WordPress dashboard, then navigate to Users > Your Profile.
- Scroll down to the Application Passwords section.
- Enter a unique name for your password (e.g., “API Client for Axios”).
- Click Add New Application Password. WordPress will generate a 24-character password.
Important: Copy this password immediately. WordPress won’t display it again, so keep it somewhere secure. This password, paired with your username, will allow us to authenticate our API requests.
2. Base64 Encoding for Secure Authentication
WordPress requires Basic Authentication to use the REST API with an Application Password. To achieve this in TypeScript, we’ll encode our username and Application Password as a Base64 token, which we’ll add to our Axios request headers.
This token is a combination of the username and the Application Password in this format: username:applicationPassword
. Encoding it with Base64 converts it into a secure token string that Axios can use in the Authorization
header of our requests.
Making a POST Request to WordPress with TypeScript
With authentication in place, we can move on to posting our data to WordPress using Axios in TypeScript. Here’s a breakdown of the necessary steps.
1. Setting Up Axios with TypeScript
First, ensure Axios is installed in your TypeScript project:
npm install axios
We’ll also use Node’s built-in Buffer
module to handle Base64 encoding for our credentials. Let’s start by importing Axios and setting up our TypeScript constants.
2. Defining Credentials and API Endpoint
The first part of our script will include the required imports, along with the API URL, credentials, and post content.
import axios from 'axios';
// WordPress credentials
const username = 'your_username'; // Replace with actual username
const applicationPassword = 'your_application_password'; // Replace with your generated App Password
// Encode credentials in Base64
const token = Buffer.from(`${username}:${applicationPassword}`, 'utf8').toString('base64');
// WordPress REST API URL for creating posts
const url = 'http://localhost:8080/wp-json/wp/v2/posts';
With this setup, token
now holds the encoded authentication string needed for our API requests.
3. Constructing the Blog Post Data
Next, let’s define the structure of the blog post data we want to send. In this case, we’ll include the title
, content
, and status
fields. The status
can be set to "publish"
to make the post live immediately or to "draft"
if you prefer to save it as a draft.
// Blog post data
const postData = {
title: 'My First Blog Post',
content: 'This is the content of my new blog post!',
status: 'publish', // Change to 'draft' if you want it unpublished
};
WordPress accepts many other optional fields, such as categories
, tags
, and excerpt
. Feel free to expand this object based on the fields your application requires.
4. Making the POST Request with Axios
Now that we have our API endpoint, credentials, and data ready, let’s make the POST request using Axios.
// Send POST request
axios
.post(url, postData, {
headers: {
'Authorization': `Basic ${token}`,
'Content-Type': 'application/json',
},
})
.then(response => {
console.log('Post created successfully:', response.data);
})
.catch(error => {
console.error('Error creating post:', error.response ? error.response.data : error.message);
});
In this request, we’re passing our postData
object as the body of the request and setting up two headers:
- Authorization: We include the Base64-encoded
token
asBasic {token}
. This tells WordPress that we’re using Basic Authentication with our Application Password. - Content-Type: We specify JSON, as WordPress expects JSON data in REST API requests.
Error Handling and Troubleshooting
No API call is complete without error handling, so I included a .catch()
block to handle any errors that arise during the request. Common issues you might encounter include:
- 401 Unauthorized: This error typically indicates an issue with authentication. Double-check that your username and Application Password are correct, and that the user role has the necessary permissions (such as Author or Administrator).
- 403 Forbidden: If the REST API isn’t accessible, this could be due to permissions or server settings.
- 404 Not Found: Ensure that the REST API endpoint is correctly configured, and that permalinks are enabled in WordPress (Settings > Permalinks).
These checks can help you quickly identify and resolve issues with API requests.
Conclusion
Posting to WordPress with Axios and TypeScript opens up new possibilities for content management and automation. By using Application Passwords and secure, authenticated requests, we gain safe access to WordPress’s REST API without exposing sensitive credentials.
This approach makes it easy to integrate WordPress content management into custom applications, bringing greater flexibility to projects requiring programmatic posting. With this setup in place, adding posts to WordPress programmatically becomes a straightforward task, allowing you to create, update, or delete posts from any JavaScript application.
This guide offers a robust foundation for further experimentation with WordPress’s REST API. With a little customization, you can extend this method to handle various content types, making WordPress a powerful tool in any content-driven web project.