I am trying to use the wordpress API to make posts to my website. I get a 404 error. I asked a colleague to do the same, with the same credentials in PHP and that worked.
This is my Python code:
##IMPORT LIBRARIES
import requests
import base64
import json
url = "https://www.mywebsite.com/wp-json/wp/v2/posts"
username = "username"
password = "**** **** **** **** **** ****" #This is the application password, set within wordpress
creds = username + ':' + password
cred_token = base64.b64encode(creds.encode())
header = {'Authorization': 'Basic ' + cred_token.decode('utf-8')}
def do_post():
post = {
'title': 'I will scream if this does not work',
'content': 'Hello, this content is published using WordPress Python Integration',
'status': 'publish',
'categories': '3',
'tags': '',
'date': '1999-12-05T11:00:00'
}
blog = requests.put(urlforpost + '/posts' , headers=header , json=post)
print(blog)
def main():
print(creds)
print(cred_token)
print(header)
do_post()
if __name__ == '__main__':
main()
This is his PHP code:
<?php
require_once("wp-load.php");
$auth = 'username:**** **** **** **** **** ****';
echo base64_encode( $auth );
$api_response = wp_remote_post( https://www.mywebsite.com/wp-json/wp/v2/posts, array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $auth ),
),
'body' => array(
'title' => 'This is WordPress Python Integration Testing, but through php I guess',
'status' => 'publish',
'content' => 'Hello, this content is published using WordPress Python Integration only its through php this time',
'categories' => '1',
'tags' => '',
'date' => "2021-12-05T11:00:00"
)
) );
$body = json_decode( $api_response['body'] );
if( wp_remote_retrieve_response_message( $api_response ) === 'Created' ) {
echo "<div class='notice'>";
echo 'The post ' . $body->title->rendered . ' has been created successfully';
echo "</div>";
}else{
echo "<div class='notice'>";
echo wp_remote_retrieve_response_message( $api_response );
echo "</div>";
}
?>
For then life of me, I cannot figure out why his works and mine doesn't.
Any suggestions