Thursday, September 9, 2021

Wordpress Rest API and C#

Wordpress has introduced it's rest API for developers to create posts and many more... you can visit their documentation from here.

https://developer.wordpress.org/rest-api/

Today let's see how we can work with it. We use postman to do the work. 

First we need to install the JSON Basic Authentication plugin. (https://github.com/WP-API/Basic-Auth)

And then we can call the API normally. The authentication has to be provided with the format of username:password and it has to be base64 encrypted.

Lets see how we can list posts.


 var client = new RestClient("https://wordpress-ASDASD90809.com/wp-json/wp/v2/posts");  
 client.Timeout = -1;  
 var request = new RestRequest(Method.GET);  
 request.AddHeader("Authorization", "Basic BASE64ENC(UNAME:PASSWORD)");  
 request.AddHeader("Content-Type", "application/x-www-form-urlencoded");  
 request.AddParameter("page", "1");  
 request.AddParameter("per_page", "100");  
 IRestResponse response = client.Execute(request);  
 Console.WriteLine(response.Content);  

You can get the results as follows.


Also you can create categories, create posts list posts and do many more things with the API.

Let's see a bit more details in next post. 

Until that, happy coding...