0

I have this script in python to try to upload an image. But First I added one ‘Application Password’ in my profile of wordpress. I have the key and all the user name is ‘admin’

However, the script gives me this error:

‘Error uploading image: 401 - {"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}
Image upload failed.’

What could be wrong or I miss to configure?

This is the script:

import requests
from requests.auth import HTTPBasicAuth
import os
import base64

# WordPress API credentials
WP_USER = 'admin'  # Your WordPress username
WP_APPLICATION_PASSWORD = 'xxx'  # Your WordPress application password
WP_URL = "https://xxx.xxx.com"  # Your WordPress site URL

def upload_image_to_wp(imgPath):
    """
    Upload an image to WordPress via the REST API using application password authentication.
    
    :param imgPath: Local path to the image to upload.
    :return: The image ID and URL if successful, else None.
    """
    url = f'{WP_URL}/wp-json/wp/v2/media'

    # Create the Authorization header manually
    auth = HTTPBasicAuth(WP_USER, WP_APPLICATION_PASSWORD)
    auth_header = {
        'Authorization': 'Basic ' + WP_USER + ':' + WP_APPLICATION_PASSWORD,
        'Content-Type': 'image/jpeg' if imgPath.endswith('.jpg') or imgPath.endswith('.jpeg') else 'image/png',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
        'Content-Disposition': f'attachment; filename={os.path.basename(imgPath)}',
        'Cache-Control': 'no-cache',
    }

    with open(imgPath, 'rb') as file:
        file_data = {
            'file': (os.path.basename(imgPath), file, 'image/jpeg' if imgPath.endswith('.jpg') or imgPath.endswith('.jpeg') else 'image/png')
        }

        # Adding Content-Disposition header
        headers = {
            'Content-Disposition': 'attachment; filename="image.jpg"'  # Adjust filename as needed
        }

        try:
            response = requests.post(url, files=file_data, headers={**auth_header, **headers})

            if response.status_code == 201:
                new_dict = response.json()
                image_id = new_dict.get('id')
                image_url = new_dict.get('guid', {}).get('rendered')
                return image_id, image_url
            else:
                print(f"Error uploading image: {response.status_code} - {response.text}")
                return None
        except requests.exceptions.RequestException as e:
            print(f"Request error: {e}")
            return None

# Example usage
image_path = r"C:/jpg.jpg"  # Replace with the actual path to the image
upload_response = upload_image_to_wp(image_path)

if upload_response:
    image_id, image_url = upload_response
    print(f"Image uploaded successfully! ID: {image_id}, URL: {image_url}")
else:
    print("Image upload failed.")

1 Answer 1

0

When you're using Basic Authentication, you can't just pass the {username}:{password} string; you need to base64-encode it.

libcurl docs on Basic Auth

So your line

'Authorization': 'Basic ' + WP_USER + ':' + WP_APPLICATION_PASSWORD

should be more like

'Authorization': 'Basic ' + base64( WP_USER + ':' + WP_APPLICATION_PASSWORD )

(I don't know how Python does base64, but it looks like you're already importing a related library in your Python snippet.)

7
  • Apparently is something to configure in the wordpress site. As I skipped the script and I made the Curl:” >curl -X POST my.website.com/wp-json/wp/v2/media -H "Authorization: Basic $(echo -n 'admin: xxx' | base64)" -F "file=@C:/jpg.jpg" {"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}} C:\asg\woo\pluginsmios\python>” What could be the issue. Thank you Commented Jan 2 at 18:21
  • Here, it could be the space in echo -n 'admin: xxx' (try echo -n 'admin:xxx' instead, maybe). Commented Jan 2 at 18:42
  • I entered ‘ curl -X POST xxx.xxx.com/wp-json/wp/v2/media -H "Authorization: Basic admin:xxx" -F "file=@C:/python/jpg.jpg"’ and the same 401 error Commented Jan 2 at 19:17
  • You've removed the base64 encoding in this most recent one. curl -X POST my.website.com/wp-json/wp/v2/media -H "Authorization: Basic $(echo -n 'admin:xxx' | base64)" -F "file=@C:/jpg.jpg" Commented Jan 2 at 19:27
  • 1
    This was a problem with the VPS. I had a shared server and now a VPS more stronger and works. It was the root access banned in the shared server. Thank you Commented Jan 21 at 3:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.