Cosuming JSON Rest API in C#

There is a lof of good libraries to consume JSON API in C#, we can search for rest client in nuger.org. First item on the search result is RestSharp,  a simple REST and Http API client. You can also use System.Net.Http.HttpClient as it is a base for sending http requests and receiving http responses provided by default on .net framework and .net core. In this post, i’ll show both ways how to cosume JSON Rest API.

System.Net.Http.HttpClient

Make an instance of HttpClient, set the baseAddress and set appropriate headers as required by the Rest API that we’re consuming. We expect the returned response in JSON Format but since the response was escaped string with backslashes so we need to clear he escaped string content then parse it into proper JSON Object.


static void SerializeHttpClient(string resourceUrl)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://www.idx.co.id");
client.DefaultRequestHeaders.Add(HttpRequestHeader.ContentType.ToString(), "application/json");
var task = client.GetAsync(resourceUrl);
task.Wait();
var response = task.Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var reader = response.Content.ReadAsStringAsync();
string result = reader.Result;
reader.Wait();
// parse the escaped string json response to proper JSON Object
JToken obj = JToken.Parse(result);
System.Console.WriteLine(obj.ToString());
var listingdata = JsonConvert.DeserializeObject<ListingData>((string)obj);
System.Console.WriteLine("{0}-{1}", listingdata.Activities[0].KodeEmiten, listingdata.Activities[0].NamaEmiten);
}
else
System.Console.WriteLine(response.StatusCode);
}

RestSharp

If you use Visual Studio then open nuget package manager console type install-package RestSharp or use the gui by right-click on the project and select manage Nuget Package and click install. But if you use dotnet cli, type dotnet add package RestSharp in the terminal.


static void SerializeRestSharp(string resourceUrl)
{
var client = new RestClient("https://www.idx.co.id");
client.AddDefaultHeader(HttpRequestHeader.ContentType.ToString(), "application/json");
var req = new RestRequest(resourceUrl, Method.GET);
var res = client.ExecuteAsGet(req, Method.GET.ToString());//, res =>
if (res.IsSuccessful)
{
var listingdata = JsonConvert.DeserializeObject<ListingData>((string)JToken.Parse(res.Content));
System.Console.WriteLine("{0}-{1}", listingdata.Activities[0].KodeEmiten, listingdata.Activities[0].NamaEmiten);
}
else
System.Console.WriteLine(res.StatusCode);
}

In my opinion RestSharp provide the most simple mechanism in making Http Request and receiving the Response with easy async support. It also has builtin Json serializer, therefore no need to rely on other Json serializer to parse the Http Response.
Full source code is here.

Published by Gadael Sedubun

Developer

One thought on “Cosuming JSON Rest API in C#

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: