C#, Wordpress

Retrieving blog posts using C# and the WordPress REST API

As part of my new professional website that I hope to release later this year, I thought it would be a good idea to dedicate a part of my site to this blog. Instead of choosing the rather traditional  way of integrating blogs (e.g. embedded HTML snippets), I have chosen to take a look at its Web API. In this article, I will focus on one scenario: working with blog posts.

Before digging into the code, this is the final result (I have chosen ASP.NET MVC as the front end but there’s no special requirement for the WordPress API):

blog

Unlike the other Web APIs that I have discussed previously, this one is less complex. One of the reasons is that there’s less private information. A lot of useful information is meant to be shared which is convenient for development as there’s no process of authentication and authorization for some endpoints.

The documentation of the API is fairly good so in general you shouldn’t have a lot of problems working with it. For my business case, I was interested in this endpoint:

https://public-api.wordpress.com/rest/v1.1/sites/$site/posts/

As you can see (and as documentation suggests clearly), you need to configure the $site variable. This variable can either be the blog ID or the site domain. In my case, this will be the following:

https://public-api.wordpress.com/rest/v1.1/sites/hendrikbulens.wordpress.com/posts/"

If you didn’t want to automate a part of this process, you would be done already. Go ahead, the URL mentioned above is a valid one and ready for use! The data you see are all my posts formatted in JSON.

The next step is to programatically retrieve the data from this endpoint. Once we have the raw data we’ll have to convert it into .NET – friendly types. Using Visual Studio’s SPECIAL PASTE utility we can easily transform JSON objects to .NET. With the JSON.NET NuGet package, it only takes one line of code to deserialize JSON to .NET. The following piece of code handles all of this.

Note: in case you didn’t have it installed yet, please get the very useful JSON.NET package fro NuGet. Run the following command in the package manager console:

PM> Install-Package Newtonsoft.Json

The following piece of code handles all of the work that needs to be done:

public IEnumerable GetWordPressPosts()
 {
 using (WebClient webClient = new WebClient())
 {
 string blogUrl = @"https://public-api.wordpress.com/rest/v1.1/sites/hendrikbulens.wordpress.com/posts/";
 string response = webClient.DownloadString(blogUrl);

 WordPressBlog blogPosts = JsonConvert.DeserializeObject(response);

 IEnumerable posts = blogPosts.posts.OrderByDescending(x => x.date).Take(3).Select(x => new BlogPost()
 {
 Title = x.title,
 Message = x.excerpt.CharacterLimit(150),
 PublishedOn = x.date,
 Comments = x.discussion.comment_count,
 Link = x.URL
 });

 return posts;
 }
 }

First thing that we have to do is to download the output from the HTTP Request, which will return a string. Knowing that this is actually JSON, we can deserialize this raw text in custom types that I have generated earlier. By copying the JSON string text on the clipboard and using the paste special feature in VS, it will automatically create all necessary types for you:

2015_05_05_23_51_16_

Ultimately, I have added an extra layer of abstraction to hide the JSON.NET types from the rest of the business and UI layer. This is not necessary of course but I like to hide as much information as possible. In this case, I just need the URL of the post, the title, the publishing date and the number of comments.

However, there is much more information you can retrieve from this endpoint. I suggest you read the REST API or you can try for yourself of course.

One utility that I finally would like to share is the CharacterLimit extension method, which comes in handy for when you want to limit the amount of characters in a string and indicate there’s more by using an ellipsis. The result is also visible in the screenshot above.

public static string CharacterLimit(this string text, int length)
 {
 if (text.Length <= length) return text;  int pos = text.IndexOf(" ", length);  if (pos >= 0)
 return text.Substring(0, pos) + "...";
 return text;
 }

As soon as the counter hits the length variable, it will trim all characters beyond this point in the string and will replace it by “…”. It will also keep in mind that it will only cut off words and not just characters. Useful utility for web development I’d say!

Happy coding!

Advertisements

2 thoughts on “Retrieving blog posts using C# and the WordPress REST API

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s