# \[REST API]  Create, Update or Delete posts using Basic Auth and HTTP API

REST API – Create, Update or Delete posts using Basic Auth and HTTP API

1. [Blog](https://rudrastyh.com/)&#x20;
2. [WordPress](https://rudrastyh.com/wordpress)

### About Basic Authentication <a href="#basic_auth" id="basic_auth"></a>

First of all, basic authentication won’t work until you install a special plugin, what plugin – depends on a way you choose. I will show you two of them.

#### Using username and password

This method isn’t recommended in WordPress Codex, because in each API call you have to send actual usernames and passwords, but you can use this method for test purposes.

To begin using it, you have to download a special plugin from [github](https://github.com/WP-API/Basic-Auth) (I use the link from the official WordPress documentation page).

<figure><img src="https://rudrastyh.com/wp-content/uploads/2017/09/json-basic-auth-plugin.png" alt=""><figcaption></figcaption></figure>

There is no way to perform Basic Auth in WordPress Rest API without this plugin installed. Once the plugin is activated on your website (I mean the website you want to interact with API), we can try examples below.

#### Using application passwords

Ok, this method is much better. You have to install Application Passwords plugin, it is available from WordPress plugins repository, so you can find it in your website admin area on the Plugins > Add New page.

<figure><img src="https://rudrastyh.com/wp-content/uploads/2017/09/application-passwords-plugin.png" alt=""><figcaption></figcaption></figure>

Once you installed this plugin, make sure, that your REST API is not turned off, then go to the very bottom of a user profile page and generate an app password there.

<figure><img src="https://rudrastyh.com/wp-content/uploads/2017/09/rest-api-tokens-with-application-passwords.png" alt=""><figcaption></figcaption></figure>

No needs to use user’s actual passwords anymore.

### Create a Post <a href="#create_post" id="create_post"></a>

Where to insert all the code from this post? I hope you know this but just in case.

First of all I want to remind you that we have 2 websites.

* The first website – is the website where the post should be created, the first website also should have [any of the mentioned above plugins](https://rudrastyh.com/wordpress/rest-api-create-delete-posts.html#basic_auth) installed.
* The second website – is the website that will interact with the first one. It will have all the code.

You can see `wp_remote_post()` function in the code – it is a WordPress function, so you have to insert in somewhere inside WP environment. For my test purposes I just created a randomly named PHP file just in WordPress root directory and added at the beginning of the file `require('wp-load.php');`. When I try to access this file in browser, it does the work.

`LOGIN:PASSWORD` on line 3 is the pair of username and password of a website user (the first website, and if you’ve installed Application Passwords, you have to use the generated token instead), that have the capabilities to create, update and delete posts.

```
$api_response = wp_remote_post( 'https://WEBSITE/wp-json/wp/v2/posts', array(
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'LOGIN:PASSWORD' )
	),
	'body' => array(
    		'title'   => 'My test',
		'status'  => 'draft', // ok, we do not want to publish it immediately
		'content' => 'lalala',
		'categories' => 5, // category ID
		'tags' => '1,4,23' // string, comma separated
		'date' => '2015-05-05T10:00:00', // YYYY-MM-DDTHH:MM:SS
		'excerpt' => 'Read this awesome post',
		'password' => '12$45',
		'slug' => 'new-test-post' // part of the URL usually
		// more body params are here:
		// developer.wordpress.org/rest-api/reference/posts/#create-a-post
	)
) );
 
$body = json_decode( $api_response['body'] );
 
// you can always print_r to look what is inside
// print_r( $body ); // or print_r( $api_response );
 
if( wp_remote_retrieve_response_message( $api_response ) === 'Created' ) {
	echo 'The post ' . $body->title->rendered . ' has been created successfully';
}
```

### How to Update a WordPress Post with REST API <a href="#update_post" id="update_post"></a>

Let’s just update the title of the created post. Replace {POST\_ID} with the ID of the post you would like to update. If you still not sure where to get it, read [this tutorial](https://rudrastyh.com/wordpress/get-post-id.html).

```typescript
$api_response = wp_remote_post( 'https://WEBSITE/wp-json/wp/v2/posts/{POST_ID}/', array(
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'LOGIN:PASSWORD' )
	),
	'body' => array(
    		'title' => 'My test 1'
	)
) );
 
$body = json_decode( $api_response['body'] );
 
 
if( wp_remote_retrieve_response_message( $api_response ) === 'OK' ) {
	echo 'The post ' . $body->title->rendered . ' has been updated successfully';
}
```

### Delete a Post <a href="#delete_post" id="delete_post"></a>

If you add `?force=true` at the end of the request URI, the post will be removed permanently without moving to trash.

```
$api_response = wp_remote_request( 'https://WEBSITE/wp-json/wp/v2/posts/{POST_ID}', array(  // ?force=true to skip trash
	'method'    => 'DELETE',
	'headers'   => array(
	    'Authorization' => 'Basic ' . base64_encode( 'LOGIN:PASSWORD' )
	)
));
 
$body = json_decode( $api_response['body'] );
 
 
if( wp_remote_retrieve_response_message( $api_response ) === 'OK' ) {
	if( $body->deleted == true ) {
		echo 'The post ' . $body->previous->title->rendered . ' has been completely deleted';
	} else {
		echo 'The post ' . $body->title->rendered . ' has been moved to trash';
	}
}
```

This was small introduction into Basic Authentication in WordPress REST API.

#### Related Posts

* [My Experience as a Lead Organizer of WordCamp Saint Petersburg](https://rudrastyh.com/journal/wordcamp-saint-petersburg-recap.html)
* [Begin with REST API – Display others blogs latest posts](https://rudrastyh.com/wordpress/rest-api-get-posts.html)
* [MailChimp API 3.0 and WordPress HTTP API](https://rudrastyh.com/wordpress/using-mailchimp-api.html)

![Misha Rudrastyh](https://secure.gravatar.com/avatar/cbc2c695ec067908b54236e7b04fc98f?s=70\&r=g)

#### Misha Rudrastyh

I love WordPress, WooCommerce and Gutenberg so much. 12 yrs of experience.

Need some custom developer help? [Get in touch](https://rudrastyh.com/contact)

#### Comments — 15

* ![](https://secure.gravatar.com/avatar/d3ade68f980978cb04d6ca96194843fa?s=70\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)Aleksam

  Awesome! Thanks for this quite nice tutorial. I have a question:

  Why do I need “2 websites”? Can’t I run this script on the same WordPress installation that I want to automatize?

  Regards.

  * ![](https://secure.gravatar.com/avatar/cbc2c695ec067908b54236e7b04fc98f?s=36\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)Misha

    Hi Aleksam,

    Yes, as an example – Gutenberg works on REST API.
  * ![](https://secure.gravatar.com/avatar/d3ade68f980978cb04d6ca96194843fa?s=36\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)Aleksam

    Hello again, Misha.

    is there a way to get media files from a remote blog, using this authetication plugin?

    I can get my own images doing this:

    ```
     
    $images= new WP_Query( // Start a new query for our videos
    		array(
    			'post_type' => 'attachment', // Only bring back attachments
    			'post_mime_type' => 'image', // Only bring back attachments that are images
    			'orderby' => 'rand', // Order the attachments randomly  
    			'post_status' => 'any'
    		)
    	);
    ```

    But I don’t know how to get the same from another blog :-(

    Could you help me, please?

    Regards!
  * ![](https://secure.gravatar.com/avatar/cbc2c695ec067908b54236e7b04fc98f?s=36\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)Misha

    Hi,

    Sure, here is [the tutorial](https://rudrastyh.com/wordpress/rest-api-get-posts.html). Just do not forget to pass `type` parameter which should be `attachment`.

    * ![](https://secure.gravatar.com/avatar/d3ade68f980978cb04d6ca96194843fa?s=36\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)Aleksam

      Sweet! Thanks.
* ![](https://secure.gravatar.com/avatar/b0b5911a1498eb4b61b729841e77be8e?s=70\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)Ricky Harerri

  How can i add posts to a Custom Post Type via API?

  * ![](https://secure.gravatar.com/avatar/cbc2c695ec067908b54236e7b04fc98f?s=36\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)Misha

    Just pass `type` parameter in the first example [here](https://rudrastyh.com/wordpress/rest-api-create-delete-posts.html#create_post).
* ![](https://secure.gravatar.com/avatar/3d37a974372c4d262aedb3144c888917?s=70\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)moses

  Hello Misha,

  Thanks for this post. I was wondering how can I do this using JS?

  Thanks

  * ![](https://secure.gravatar.com/avatar/cbc2c695ec067908b54236e7b04fc98f?s=36\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)Misha

    Hey Moses,

    Sorry, usually I remove comments with unformatted code, but at this time I just decided to remove the code only, because you’re asking a good question.

    I didn’t have a chance to do this with JS yet, but maybe somebody from my website readers kindly answers your question.
  * ![](https://secure.gravatar.com/avatar/94c04e2a3dc2424acf6ee305c8ece448?s=36\&d=https://rudrastyh.com/wp-content/themes/misha/assets/avatar.png\&r=g)cikal

    Maybe this, late in party..

    ```
    // post data
    const dataset = [
      title: 'My test',
      status: 'draft', // ok, we do not want to publish it immediately
      content: 'lalala',
      categories: 5, // category ID
      tags: '1,4,23' // string, comma separated
      date: '2015-05-05T10:00:00', // YYYY-MM-DDTHH:MM:SS
      excerpt: 'Read this awesome post',
      password: '12$45',
      slug: 'new-test-post'
    ];
    fetch("YOUR_END_POINT_URL", {
        method: 'POST', // anything you want
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic YOUR_AUTH_KEY'
        },
        body: JSON.stringify(dataset)
      })
      .then( (response) => response.json() )
      .then( (data) => { console.log(data) })
      .catch( (err) => { console.log(err) });
    ```

    Btw, thank’s Misha for your article..

    Future readers, you can read more variants way of using Fetch API at <https://developer.mozilla.org/en-US/docs/Web/API/Fetch\\_API/Using\\_Fetch>
