REST API for Beginners : Adding a New Post

REST API for Beginners : Adding a New Post

According to wordpress.org, ‘WordPress REST API provides API endpoints for WordPress data types that allow developers to interact with sites remotely by sending and receiving JSON (JavaScript Object Notation) objects.’

Talking about WordPress REST API, we generally talk about the end points as well as routes. If we just use http://sitedomain.com/wp-json/, we get to know what Endpoints are available and also the routes for those Endpoints.

Scenario

If we are playing around with posts, we can use the endpoint /wp/v2/posts/ with route http://sitedomain.com/wp-json/.
Further, adding post id at the end like this http://sitedomain.com/wp-json/wp/v2/posts/{postid} will make that post available to use.

One of the advantage of REST API I found on WordPress is you don’t have to use admin.ajax. The WordPress REST API can also be seen as replacement for the built-in admin.ajax.

OAuth

It is one of the common protocol for authorization to use/access the protected data on the Internet. Lets say, we are adding a post to any other website, we have to use OAuth authorization. The basic OAuth plugin can be found at github. This plugin provides authorization for the correct/valid request and should be installed and activated on the server site (where post is being added).

Now, the functional part where request is made to the server site from the client to add post with given title and content.

var data = {
            title: title,
            content: content
        };

        $.ajax({
            method: 'POST',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            url: 'http://sitedomain.com/wp-json/wp/v2/posts/',//rest route of server site
            data: data,
            beforeSend: function ( xhr ) {
                xhr.setRequestHeader( 'Authorization', 'Basic ' + btoa( 'abc:xyz' ) );//username:password
            },
            success : function( response ) {
                alert('Post Added Successfully!');
            },
            fail : function( response ) {
                alert('Post Addition Failed!');
            }
        });

This should add a new post with the given title and content on the server site. Please use browser’s console to make sure no errors or notice is seen there.

Cross-Origin Resource Sharing (CORS)

“Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.”

CORS can be dug deep and there are various resources available. However, if the cross origin requests are blocked, then it can be hacked by pasting the below function to the activated theme’s functions.php file in the server site.

function wp_rest_allow_all_cors() {
	// Remove the default filter.
	remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );

	// Add a Custom filter.
	add_filter( 'rest_pre_serve_request', function( $value ) {
		header( 'Access-Control-Allow-Origin: *' ); //allows all the cross origins
		header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
		header( 'Access-Control-Allow-Credentials: true' );
		header( 'Access-Control-Allow-Authorization: true' );
		return $value;
	});
}

This is just a beginner as well as a brief explanation regarding WordPress REST API to get going. REST API is huge and so is the scope of it. More can be found at codex. I have just tried to clear how powerful REST API really is with a simple example and explanation.

Leave comment

Your email address will not be published. Required fields are marked with *.