TESTING Wordpress REST API with POSTMAN #2
Creating new posts
Let's try to add new post to our website using POSTMAN and POST request.
Request header Content-Type must be set to application/json and Body raw data json.
And response ...error 401 (unauthorized). We have to sent login authentication credentials to be able to create new posts.
I'm going to use JSON Web Token authentication method which allows to login through an endpoint and grab the given token and attach it to the request Headers. This isn't something which is included in wordpress by default. It can be added as a plugin from wp-admin page. I'm using JWT Authentication for WP REST API plugin by Enrique Chavez
Installing the JWT Auth plugin
Adding extra functionality to wordpress sites is very easy thanks to plethora of available plugins. To be able to install it we need to open wp-admin dashboard and in plugin section search for required extension, install and activate it. Simple as that.
Then we need to edit .htaccess file in website's directory and add following lines of code to enable HTTP Authorization Header which is disabled by most shared hosting servers.
Next Step is to edit wp-config.php file, where we must create secret JWT key and enable CORS support (Cross Origin Resource Sharing)
Activation of the plugin will create two endpoints
- /wp-json/jwt-auth/v1/token - this will validate username and password and return token to use in the future requestes to the API
- /wp-json/jwt-auth/v1/token/validate - simple endpoint to validate a token
Testing new endpoints with POSTMAN
Now let's try to obtain a token by loging to the website using POST request, and sending our admin credentials in the Body of the request as json. When sucessfull respopnse shoud have generated token which later can be send in the Headers for validating user.
To Create new post using Postman we need to add this token to Header as key value pair. Key Authorization, Value: Bearer <<GENERATED TOKEN>>
In Body of the request we can put json data of the new post with title, content and status. Status need to be set to publish, if not it will be in draft mode and won't display on the page.
And the final result in the browser. New post has been added to the website using Wordpress REST API, POST request with JSON web token authentication..
Comments
Post a Comment