Skip to content

Instantly share code, notes, and snippets.

@florian-glombik
Last active October 2, 2024 23:28
Show Gist options
  • Save florian-glombik/c2e71fa2128fa1a69bb39aa61fadf3bd to your computer and use it in GitHub Desktop.
Save florian-glombik/c2e71fa2128fa1a69bb39aa61fadf3bd to your computer and use it in GitHub Desktop.
Upload file to Wordpress using REST API (python)
import base64, requests, logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
# This solution was inspired by an existing script https://gist.github.com/openroomxyz/f32021d077d1be5235ceb1a716d1e37a
# This script includes further documentation and explanation than the solution by @openroomxyz
### -------- VALUES TO BE MODIFIED (start) -------- ###
URL = "https://mydomain.com"
USERNAME = "admin"
# Important: The application password is not the same as the login password (the username is)
# To create an application password, go to wp-admin -> Users -> Edit User
# See documentation on the application passwords:
# https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#basic-authentication-with-application-passwords
APPLICATION_PASSWORD = "XXXX XXXX XXXX XXXX XXXX XXXX"
path_to_file_to_be_uploaded = "C://Users//X//Desktop//X//X.pdf"
### -------- VALUES TO BE MODIFIED (end) -------- ###
def create_header(username, application_password):
credentials = username + ':' + application_password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
return header
def upload_file_to_wordpress(file_path):
logging.info(f"Uploading file to WordPress ({URL}): {file_path}")
media = {'file': open(file_path, "rb")}
# Documentation of the API: https://developer.wordpress.org/rest-api/reference/media/
response = requests.post(URL + "/wp-json/wp/v2/media", headers=create_header(USERNAME, APPLICATION_PASSWORD),
files=media)
if response.status_code == 201:
logging.info(f"File uploaded successfully: {response.json()['link']}")
else:
logging.error(f"Error uploading file (status: {response.status_code}): {response.text}")
if __name__ == '__main__':
upload_file_to_wordpress(path_to_file_to_be_uploaded)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment