Uploading images via API
-
Hi there,
I’m attempting to build a site that takes semi-automated content via API.
I have had no difficulty stringing together code to make text posts work, but I cannot find a way to upload images. Following multiple guides, I assembled a python function that send the image via the “media” endpoint.
When I do, I get the following error: {“code”:”rest_upload_sideload_error”,”message”:”Sorry, you are not allowed to upload this file type.”,”data”:{“status”:500}}
This is what the function looks like at present:def upload_image_to_wordpress(file_object, file_name): Parameters: file_object (BytesIO): The image file as a BytesIO object. file_name (str): The name of the image file (e.g., 'plot.png'). Returns: dict: JSON response from the WordPress API. """ # Define the API endpoint for media uploads media_endpoint = f"https://public-api.wordpress.com/wp/v2/sites/{os.environ['WP_SITE_URL']}/media" headers = handle_oauth() headers['Content-type'] = 'image/jpeg' headers['Content-disposition'] = 'attachment; filename=%s'% file_name # Make the POST request to upload the image response = requests.post(media_endpoint, headers=headers, data=file_object) # Check for success if response.status_code == 201: # HTTP 201 Created print("Image uploaded successfully!") return response.json() else: print(f"Failed to upload image: {response.status_code}") print(response.text) return None
I have investigated the site backend, the settings for the app, and exhaustively queried support forums and ChatGPT. I cannot find an answer.
How do I get past this?The blog I need help with is: (visible only to logged in users)
- The topic ‘Uploading images via API’ is closed to new replies.