REST API’s are everywhere these days. As a developer you will certainly be required to interface with one sooner than later. Thankfully, when working in the .NET Framework, there are tools which can make interfacing with these APIs fairly easily compared to the past. Let’s take a look at RestSharp and NewtonSoft.
RestSharp is a library that encapsulates the work of creating web clients and initiating HTTP requests. You may already be familiar with working with the WebClient class in .NET,however, RestSharp gives you some added simplicity by allowing you to streamline your code.
The famous Newtonsoft framework is a must-have in almost any project these days. It is generally used to serialize/deserialize JSON objects.
This article will walk you through how to create strongly typed objects from a REST API using RestSharp and NewtonSoft.
01- First create a new .NET web project and add references to both of these libraries using Nuget. Right click on References and Manage Nuget Packages. Select JSON.Net by Newtonsoft and click Install.
02- Let’s do the same for the RestSharp framework.
03- Create a HomeController and a view for the controller.
04- Create a new class that we will use to let RestSharp know how to serialize the data from the REST API
05- In this example we will utilize a test API endpoint from http://echo.jsontest.com/firstname/kevin/lastname/doig which returns one object with a firstname and a lastname parameter. If you open the link you will see a JSON response with one object that contains both of these properties. Let’s create a strongly typed object to map this object to.
06- In your Models namespace, create a Post class that has all of the properties being returned from the API.
07- Now, in order to map each property from the class to the properties returned in the API we will use the JsonProperty attribute from within the Newtonsoft framework.
08- In our home controller we will create a new RestSharp client, a RestSharp request, and pass in the Post model as our generic class parameter to be mapped to.
09- We can run this project and set a breakpoint and look at the result object, and within the Data property we will have a strongly mapped object that is populated from the result of the API call.
10- You can now pass that model in to your view or complete any processing you wish to do before sending it into your view. Note that in this example you will likely want to create your RestSharp request outside of your controller in another class, and call that class from the controllerThe complete project has been zipped up for you to reference as well.
We hope you have found this week’s edition of “To The Point” by Kevin Doig to be helpful and informative. Look out for our next week instalment as we continue to explore unique topics from business to the latest technology.
We want to hear your point! If you have any ideas, suggestions or any questions about our weekly blog, please contact us at: email@example.com.
Point Alliance Team