Upload Media to WP via REST API

Issue: How to upload a featured image to Wordpress using the REST API

I’m trying to create a new post in Wordpress with a featured image, using the REST API. I have been unsuccessful due to an error saying “No data supplied”.

Screenshot of the error

I have two ideas on how to accomplish this:

  1. Upload the media file to the Wordpress site and get the media ID.
  2. Create the new post with the media ID.

Answer:

To upload a featured image to WordPress using the REST API, you can follow these steps:

  1. First, upload the image to WordPress using the media endpoint. This can be done using a POST request to https://example.com/wp-json/wp/v2/media. You will need to include the image data in the request body, as well as the appropriate headers. Here is an example:
POST /wp-json/wp/v2/media HTTP/1.1
Host: example.com
Content-Disposition: attachment; filename="my-image.png"
Content-Type: image/png

<binary data>
  1. Once the image has been uploaded, you will receive a JSON response containing the media ID. You can use this ID when creating the new post.

  2. To create the new post, make a POST request to https://example.com/wp-json/wp/v2/posts. In the request body, include the post data, including the media ID for the featured image. Here is an example:

POST /wp-json/wp/v2/posts HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "title": "My New Post",
  "content": "This is my new post.",
  "featured_media": 123
}

Replace example.com with your WordPress site’s domain name, and 123 with the media ID you received from the previous step.

That’s it! Your new post should now have a featured image.