Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,181,531 members, 7,914,416 topics. Date: Thursday, 08 August 2024 at 03:44 AM

How To Consume Restful API In C# - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / How To Consume Restful API In C# (1449 Views)

How To Consume Restful Apis - Xutini / How To Retrieve Data From An Api Using Fetch Api In Javascript / Consuming Laravel Api In Android (2) (3) (4)

(1) (Reply)

How To Consume Restful API In C# by raymod170(m): 4:13pm On Feb 13, 2018
By taking a path of Web development, you find yourself in the need of dealing with external APIs (Application Programming Interface) sooner or later. In this article, my goal will be to make the most comprehensive list of ways to consume RESTful APIs in your C# projects and show you how to do that on some simple examples. After reading the article, you will hopefully have more insight into which options are available to you and how to choose the right one next time you need to consume a RESTful API.

What is RESTful API?

So, before we start, you might be wondering what API stands for, and what is the RESTful part all about?

To put things simply, APIs are the layers between software applications. You can send the request to the API, and in return, you get the response from it. APIs hide all the nitty-gritty details of the concrete implementation of a software application and expose the interface you should use to communicate with that application.

The whole internet is the one big spider web made of APIs. They are used to communicate and relate information between applications. You have an API for pretty much anything out there. Most of the services you use daily have their own APIs (GoogleMaps, Facebook, Twitter, Instagram, weather portals…)

RESTful part means that API is implemented in accordance with the principles and rules of the REST (Representational State Transfer) which is the underlying architectural principle of the web. RESTful APIs in most cases return the plain text, JSON or XML response. Explaining REST in more detail is out of the scope of this article, but you can read more about REST in our article Top REST API best practices.

How to Consume RESTful APIs

Ok, let’s go to the meaty part of this whole story.

There are several ways to consume a RESTful API in C#:

HttpWebRequest/Response class

WebClient class

HttpClient class

RestSharp NuGet package

ServiceStack Http Utils

Every one of these has pros and cons, so let us go through them and see what they offer.

As an example, I will be collecting information about RestSharp repo releases and their publish dates via GitHub API. This information is available publicly and you can see how raw JSON response looks here: RestSharp releases

I will be utilizing the help of the phenomenal Json.NET library to deserialize the response we get.

What I expect to get as a result of the next few examples is a deserialized dynamic object (for simplicity) that contains RestSharp release information.



HttpWebRequest/Response Class

It is the HTTP-specific implementation of WebRequest class. It was originally used to deal with HTTP requests, but it was made obsolete and replaced by WebClient class.

It offers fine-grained control over every aspect of the request making. As you can imagine, this can be the double-edged sword and you can easily end up losing enormous amounts of time fine-tuning your requests. On the other hand, this might just be what you need for your specific case.

HttpWebRequest class does not block the user interface, which is, I am sure you will agree with this one, pretty important.

HttpWebResponse class provides a container for the incoming responses.

This is a simple example of how to consume an API using these classes.

Hide   Copy Code

HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("https://api.github.com/repos/restsharp/restsharp/releases"); request.Method = "GET"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string content = string.Empty; using (Stream stream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(stream)) { content = sr.ReadToEnd(); } } var releases = JArray.Parse(content);

Although a simple example, it becomes much more complicated when you need to deal with more sophisticated scenarios like posting form information, authorizing, etc.

WebClient Class

This class is a wrapper around HttpWebRequest. It simplifies the process by abstracting the details of the HttpWebRequest from the developer. The code is easier to write and you are less likely to make mistakes this way. If you want to write less code, not worry about all the details, and the execution speed is a non-factor, consider using WebClient class.

This example should give you a rough idea how much easier it is to use WebClient compared to the HttpWebRequest/Response approach.

Hide   Copy Code

var client = new WebClient(); client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"wink; var response = client.DownloadString("https://api.github.com/repos/restsharp/restsharp/releases"); var releases = JArray.Parse(response);

Much easier, right?

Other than DownloadString method, WebClientclass offers a host of other useful methods to make your life easier. You can easily manipulate strings, files or byte arrays using it, and for a price of just a few milliseconds slower than HttpWebRequest/Response approach.

Both the HttpWebRequest/Response and WebClient classes are available in the older versions of .NET. Be sure to check out the MSDN if you are interested in what else WebClient has to offer.

HttpClient Class

HttpClient is the “new kid on the block”, and offers some of the modern .NET functionalities that older libraries lack. For example, you can send multiple requests with the single instance of HttpClient, it is not tied to the particular HTTP server or host, makes use of async/await mechanism.

You can find out about the five good reasons to use HttpClient in this video:

Strongly typed headers

Shared Caches, cookies, and credentials

Access to cookies and shared cookies

Control over caching and shared cache

Inject your code module into the ASP.NET pipeline. Cleaner and modular code

Here is HttpClient in action on our example:

Hide   Copy Code

using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"wink; var response = httpClient.GetStringAsync(new Uri(url)).Result; var releases = JArray.Parse(response); }

For the sake of simplicity, I implemented it synchronously. Every HttpClient method is meant to be used asynchronously and SHOULD be used that way.

Also, I need to mention one more thing. There is a debate whether HttpClient should be wrapped in using block or statically on the app level. Although it implements IDisposable, it seems that by wrapping it in the using block, you can make your app malfunction and get the SocketException. And as Ankit blogs, the performance test results are much in favor of static initialization of the HttpClient. Be sure to read these blog posts as they can help you be more informed about the correct usage of the HttpClient.

And don’t forget, being modern, HttpClient is exclusive to the .NET 4.5, so you might have trouble using it on some legacy projects.

RestSharp

RestSharp is the OpenSource alternative to standard .NET libraries and one of the coolest .NET libraries out there. It is available as a NuGet package, and there are a few reasons why you should consider trying it out.

Like HttpClient, RestSharp is a modern and comprehensive library, easy and pleasant to use, while still having support for older versions of .NET Framework. It has inbuilt Authentication and Serialization/Deserialization mechanisms but allows you to override them with your custom ones. It is available across platforms and supports OAuth1, OAuth2, Basic, NTLM and Parameter-based Authentication. It can also work synchronously or asynchronously. There is a lot more to this library, but these are some of the great benefits it offers. For detailed information on usage and capabilities of RestSharp, you can visit the RestSharp page on GitHub.

Now let’s try to get a list of RestSharp releases using RestSharp.

Hide   Copy Code

var client = new RestClient(url); IRestResponse response = client.Execute(new RestRequest()); var releases = JArray.Parse(response.Content);

Simple enough. But do not be fooled, RestSharp is very flexible and has all the tools you need to achieve almost anything while working with RESTful API.

One thing to note in this example is that I didn’t use RestSharp’s deserialization mechanism due to the example consistency, which is a bit of a waste, but I encourage you to use it as it is really easy and convenient. So you can easily make a container like this:

Hide   Copy Code

public class Release { [DeserializeAs(Name = "name"wink] public string Name { get; set; } [DeserializeAs(Name = "published_at"wink] public string PublishedAt { get; set; } }

And after that, use Execute method to directly deserialize the response to that container. You can add just the properties you need and use Attribute DeserializeAs to map them to C# properties (nice touch). Since we get the list of releases in our response, we use the List<Release> as a containing type.

Hide   Copy Code

var client = new RestClient(url); var response = client.Execute<List<Release>>(new RestRequest()); var releases = response.Data;

Pretty straightforward and elegant way to get our data.

There is a lot more to RestSharp than sending GETrequests, so explore and see for yourself how cool it can be.

One final note to add to the RestSharp case is that its repository is in need of maintainers. If you want to learn more about this cool library, I urge you to head over to RestSharp repo and help this project stay alive and be even better. You can also help porting RestSharp to .NET Core.

ServiceStack Http Utils

Another library, but unlike RestSharp, ServiceStack seems to be properly maintained and keeping pace with modern API trends. List of ServiceStackfeatures is impressive and it certainly has various applications.

What is most useful to us here is to demonstrate how to consume an external RESTful API. ServiceStackhas a specialized way of dealing with 3rd Party HTTP APIs called Http Utils.

Let us see how fetching RestSharp releases looks like using ServiceStack Http Utils first using the Json.NET parser.

Hide   Copy Code

var response = url.GetJsonFromUrl(requestFilter: webReq => { webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"; }); var releases = JArray.Parse(response);

You can also choose to leave it to the ServiceStackparser. We can reuse the Release class defined earlier in the post.

Hide   Copy Code

List<Release> releases = url.GetJsonFromUrl(requestFilter: webReq => { webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"; }).FromJson<List<Release>>();

As you can see, either way is fine, and you can choose whether you get the string response or deserialize it immediately.

Although ServiceStack is the last library I stumbled upon, I was pleasantly surprised how easy it was for me to use it, and I think it may become my go-to tool for dealing with APIs and services in the future.

Other Options

There are a lot of other options available for your specific problems. These libraries are meant to be used for consuming a single REST service. For example, octokit.net is used to work with GitHub API specifically, Facebook SDK is used for consuming Facebook API and there are many others for almost anything.

While these libraries are made specifically for those APIs and may be great at doing what they are meant for, their usefulness is limited because you often need to connect with more than one API in your applications. This may result in having different implementations for each one, and more dependencies which potentially leads to repetitiveness and is error prone. The more specific the library, the less flexibility it has.

Conclusion

So, to summarize, we talked about different tools you can use to consume a RESTful API. I mentioned some .NET libraries that can do that like HttpWebRequest, WebClient, and HttpClient, as well as some of the amazing third party tools like RestSharp and ServiceStack. I gave you very short introductions to those tools and made some very simple examples to show you how you can start using them. I consider you now at least 95% ready to consume some REST. Go forth and spread your wings, explore and find even more fancy and interesting ways to consume and connect different APIs. Sleep restfully now, you know the way.

Also, I want to know what is your favorite way to consume a RESTful API? Are there any missing on this list I should be aware of? Be sure to leave me a comment and let me know.

1 Like

Re: How To Consume Restful API In C# by raymod170(m): 8:38am On Jun 30, 2018
raymod170:
By taking a path of Web development, you find yourself in the need of dealing with external APIs (Application Programming Interface) sooner or later. In this article, my goal will be to make the most comprehensive list of ways to consume RESTful APIs in your C# projects and show you how to do that on some simple examples. After reading the article, you will hopefully have more insight into which options are available to you and how to choose the right one next time you need to consume a RESTful API.

What is RESTful API?

So, before we start, you might be wondering what API stands for, and what is the RESTful part all about?

To put things simply, APIs are the layers between software applications. You can send the request to the API, and in return, you get the response from it. APIs hide all the nitty-gritty details of the concrete implementation of a software application and expose the interface you should use to communicate with that application.

The whole internet is the one big spider web made of APIs. They are used to communicate and relate information between applications. You have an API for pretty much anything out there. Most of the services you use daily have their own APIs (GoogleMaps, Facebook, Twitter, Instagram, weather portals…)

RESTful part means that API is implemented in accordance with the principles and rules of the REST (Representational State Transfer) which is the underlying architectural principle of the web. RESTful APIs in most cases return the plain text, JSON or XML response. Explaining REST in more detail is out of the scope of this article, but you can read more about REST in our article Top REST API best practices.

How to Consume RESTful APIs

Ok, let’s go to the meaty part of this whole story.

There are several ways to consume a RESTful API in C#:

HttpWebRequest/Response class

WebClient class

HttpClient class

RestSharp NuGet package

ServiceStack Http Utils

Every one of these has pros and cons, so let us go through them and see what they offer.

As an example, I will be collecting information about RestSharp repo releases and their publish dates via GitHub API. This information is available publicly and you can see how raw JSON response looks here: RestSharp releases

I will be utilizing the help of the phenomenal Json.NET library to deserialize the response we get.

What I expect to get as a result of the next few examples is a deserialized dynamic object (for simplicity) that contains RestSharp release information.



HttpWebRequest/Response Class

It is the HTTP-specific implementation of WebRequest class. It was originally used to deal with HTTP requests, but it was made obsolete and replaced by WebClient class.

It offers fine-grained control over every aspect of the request making. As you can imagine, this can be the double-edged sword and you can easily end up losing enormous amounts of time fine-tuning your requests. On the other hand, this might just be what you need for your specific case.

HttpWebRequest class does not block the user interface, which is, I am sure you will agree with this one, pretty important.

HttpWebResponse class provides a container for the incoming responses.

This is a simple example of how to consume an API using these classes.

Hide   Copy Code

HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("https://api.github.com/repos/restsharp/restsharp/releases"); request.Method = "GET"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string content = string.Empty; using (Stream stream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(stream)) { content = sr.ReadToEnd(); } } var releases = JArray.Parse(content);

Although a simple example, it becomes much more complicated when you need to deal with more sophisticated scenarios like posting form information, authorizing, etc.

WebClient Class

This class is a wrapper around HttpWebRequest. It simplifies the process by abstracting the details of the HttpWebRequest from the developer. The code is easier to write and you are less likely to make mistakes this way. If you want to write less code, not worry about all the details, and the execution speed is a non-factor, consider using WebClient class.

This example should give you a rough idea how much easier it is to use WebClient compared to the HttpWebRequest/Response approach.

Hide   Copy Code

var client = new WebClient(); client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"wink; var response = client.DownloadString("https://api.github.com/repos/restsharp/restsharp/releases"); var releases = JArray.Parse(response);

Much easier, right?

Other than DownloadString method, WebClientclass offers a host of other useful methods to make your life easier. You can easily manipulate strings, files or byte arrays using it, and for a price of just a few milliseconds slower than HttpWebRequest/Response approach.

Both the HttpWebRequest/Response and WebClient classes are available in the older versions of .NET. Be sure to check out the MSDN if you are interested in what else WebClient has to offer.

HttpClient Class

HttpClient is the “new kid on the block”, and offers some of the modern .NET functionalities that older libraries lack. For example, you can send multiple requests with the single instance of HttpClient, it is not tied to the particular HTTP server or host, makes use of async/await mechanism.

You can find out about the five good reasons to use HttpClient in this video:

Strongly typed headers

Shared Caches, cookies, and credentials

Access to cookies and shared cookies

Control over caching and shared cache

Inject your code module into the ASP.NET pipeline. Cleaner and modular code

Here is HttpClient in action on our example:

Hide   Copy Code

using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"wink; var response = httpClient.GetStringAsync(new Uri(url)).Result; var releases = JArray.Parse(response); }

For the sake of simplicity, I implemented it synchronously. Every HttpClient method is meant to be used asynchronously and SHOULD be used that way.

Also, I need to mention one more thing. There is a debate whether HttpClient should be wrapped in using block or statically on the app level. Although it implements IDisposable, it seems that by wrapping it in the using block, you can make your app malfunction and get the SocketException. And as Ankit blogs, the performance test results are much in favor of static initialization of the HttpClient. Be sure to read these blog posts as they can help you be more informed about the correct usage of the HttpClient.

And don’t forget, being modern, HttpClient is exclusive to the .NET 4.5, so you might have trouble using it on some legacy projects.

RestSharp

RestSharp is the OpenSource alternative to standard .NET libraries and one of the coolest .NET libraries out there. It is available as a NuGet package, and there are a few reasons why you should consider trying it out.

Like HttpClient, RestSharp is a modern and comprehensive library, easy and pleasant to use, while still having support for older versions of .NET Framework. It has inbuilt Authentication and Serialization/Deserialization mechanisms but allows you to override them with your custom ones. It is available across platforms and supports OAuth1, OAuth2, Basic, NTLM and Parameter-based Authentication. It can also work synchronously or asynchronously. There is a lot more to this library, but these are some of the great benefits it offers. For detailed information on usage and capabilities of RestSharp, you can visit the RestSharp page on GitHub.

Now let’s try to get a list of RestSharp releases using RestSharp.

Hide   Copy Code

var client = new RestClient(url); IRestResponse response = client.Execute(new RestRequest()); var releases = JArray.Parse(response.Content);

Simple enough. But do not be fooled, RestSharp is very flexible and has all the tools you need to achieve almost anything while working with RESTful API.

One thing to note in this example is that I didn’t use RestSharp’s deserialization mechanism due to the example consistency, which is a bit of a waste, but I encourage you to use it as it is really easy and convenient. So you can easily make a container like this:

Hide   Copy Code

public class Release { [DeserializeAs(Name = "name"wink] public string Name { get; set; } [DeserializeAs(Name = "published_at"wink] public string PublishedAt { get; set; } }

And after that, use Execute method to directly deserialize the response to that container. You can add just the properties you need and use Attribute DeserializeAs to map them to C# properties (nice touch). Since we get the list of releases in our response, we use the List<Release> as a containing type.

Hide   Copy Code

var client = new RestClient(url); var response = client.Execute<List<Release>>(new RestRequest()); var releases = response.Data;

Pretty straightforward and elegant way to get our data.

There is a lot more to RestSharp than sending GETrequests, so explore and see for yourself how cool it can be.

One final note to add to the RestSharp case is that its repository is in need of maintainers. If you want to learn more about this cool library, I urge you to head over to RestSharp repo and help this project stay alive and be even better. You can also help porting RestSharp to .NET Core.

ServiceStack Http Utils

Another library, but unlike RestSharp, ServiceStack seems to be properly maintained and keeping pace with modern API trends. List of ServiceStackfeatures is impressive and it certainly has various applications.

What is most useful to us here is to demonstrate how to consume an external RESTful API. ServiceStackhas a specialized way of dealing with 3rd Party HTTP APIs called Http Utils.

Let us see how fetching RestSharp releases looks like using ServiceStack Http Utils first using the Json.NET parser.

Hide   Copy Code

var response = url.GetJsonFromUrl(requestFilter: webReq => { webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"; }); var releases = JArray.Parse(response);

You can also choose to leave it to the ServiceStackparser. We can reuse the Release class defined earlier in the post.

Hide   Copy Code

List<Release> releases = url.GetJsonFromUrl(requestFilter: webReq => { webReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"; }).FromJson<List<Release>>();

As you can see, either way is fine, and you can choose whether you get the string response or deserialize it immediately.

Although ServiceStack is the last library I stumbled upon, I was pleasantly surprised how easy it was for me to use it, and I think it may become my go-to tool for dealing with APIs and services in the future.

Other Options

There are a lot of other options available for your specific problems. These libraries are meant to be used for consuming a single REST service. For example, octokit.net is used to work with GitHub API specifically, Facebook SDK is used for consuming Facebook API and there are many others for almost anything.

While these libraries are made specifically for those APIs and may be great at doing what they are meant for, their usefulness is limited because you often need to connect with more than one API in your applications. This may result in having different implementations for each one, and more dependencies which potentially leads to repetitiveness and is error prone. The more specific the library, the less flexibility it has.

Conclusion

So, to summarize, we talked about different tools you can use to consume a RESTful API. I mentioned some .NET libraries that can do that like HttpWebRequest, WebClient, and HttpClient, as well as some of the amazing third party tools like RestSharp and ServiceStack. I gave you very short introductions to those tools and made some very simple examples to show you how you can start using them. I consider you now at least 95% ready to consume some REST. Go forth and spread your wings, explore and find even more fancy and interesting ways to consume and connect different APIs. Sleep restfully now, you know the way.

Also, I want to know what is your favorite way to consume a RESTful API? Are there any missing on this list I should be aware of? Be sure to leave me a comment and let me know.

(1) (Reply)

Best Payment Gateway To Use For Android App? / How Possible Is A Certification In Oracle11g Or Java In 3month Wif Little Experience. Pls Help: / Candycrush-cheats.com Is Down

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 60
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.