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 is 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 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 a RESTful API?

So, before we start, you might be wondering what does 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 a 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.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

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

public string GetReleases(string url)
{
    var client = new RestClient(url);

    var response = client.Execute(new RestRequest());

    return response.Content;
}

Simple enough. But don’t let that fool you, 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:

public class GitHubRelease
{
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }
    [JsonProperty(PropertyName = "published_at")]
    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 the JsonProperty attribute 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.

public List<GitHubRelease> GetDeserializedReleases(string url)
{
    var client = new RestClient(url);

    var response = client.Execute<List<GitHubRelease>>(new RestRequest());

    return response.Data;
}

A pretty straightforward and elegant way to get our data.

There is a lot more to RestSharp than sending GET requests, 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 the RestSharp repo and help this project stay alive and be even better.

ServiceStack Http Utils

Another library, but unlike RestSharp, ServiceStack seems to be properly maintained and keeping pace with modern API trends. The list of ServiceStack features 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. ServiceStack has 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.

public string GetReleases(string url)
{
    var response = url.GetJsonFromUrl(webReq =>
    {
        webReq.UserAgent = RequestConstants.UserAgentValue;
    });

    return response;
}

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

public List<GitHubRelease> GetDeserializedReleases(string url)
{
    var releases = url.GetJsonFromUrl(webReq =>
    {
        webReq.UserAgent = RequestConstants.UserAgentValue;
    }).FromJson<List<GitHubRelease>>();

    return releases;
}

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

Although ServiceStack is the last library we stumbled upon, we were pleasantly surprised by 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.

Flurl

One of the libraries requested by many people in the comments section, and loved by many all over the internet but still gaining traction.

Flurl stands for Fluent Url Builder, which is the way the library builds its queries. For those of you not familiar with the fluent way of doing stuff, fluent simply means that the library is built in such a way that methods are chained to achieve greater readability, similar to that of human language.

To make things even easier to understand, let’s give some examples (this one is from official docs):

// Flurl will use 1 HttpClient instance per host
var person = await "https://api.com"
    .AppendPathSegment("person")
    .SetQueryParams(new { a = 1, b = 2 })
    .WithOAuthBearerToken("my_oauth_token")
    .PostJsonAsync(new
    {
        first_name = "Claire",
        last_name = "Underwood"
    })
    .ReceiveJson<Person>();

You can see how the methods chain together to complete the “sentence”.

In the background, Flurl is using HttpClient or rather enhancing the HttpClient library with its own syntactic sugar. So that means Flurl is an async library and it’s good to have that in mind.

As with other advanced libraries, we can do this in two different ways:

public string GetReleases(string url)
{
    var result = url
        .WithHeader(RequestConstants.UserAgent, RequestConstants.UserAgentValue)
        .GetJsonAsync<List<GitHubRelease>>()
        .Result;

    return JsonConvert.SerializeObject(result);
}

This way is rather terrible since we are serializing a result only to deserialize it a little bit later. If you are using a library such as Flurl, you shouldn’t be doing things this way.

A better way of doing things would be:

public List<GitHubRelease> GetDeserializedReleases(string url)
{
    var result = url
        .WithHeader(RequestConstants.UserAgent, RequestConstants.UserAgentValue)
        .GetJsonAsync<List<GitHubRelease>>()
        .Result;

    return result;
}

With .Result we are forcing the synchronous behavior of the code. The real and intended way to use Flurl would look like this:

public async Task<List<GitHubRelease>> GetDeserializedReleases(string url)
{
    var result = await url
        .WithHeader(RequestConstants.UserAgent, RequestConstants.UserAgentValue)
        .GetJsonAsync<List<GitHubRelease>>();

    return result;
}

Which shows off the full potential of the Flurl library.

If you want to learn more about how to use Flurl in different real-life scenarios, check out our Consuming GitHub API (REST) With Flurl article

In summary, it’s like advertised: easy to use, modern, readable and testable. What more can you expect of a library? To be open source? Check out: Flurl repo and contribute if you like it!

DalSoft.RestClient

Now this one is a bit different than anything on this list so far. But this one does it a bit differently.

Let’s see how we can use DalSoft.RestClient to consume the GitHub API and then talk about what we’ve done.

First things first, you can download DalSoft.RestClient either via NuGet Package Manager by typing : Install-Package DalSoft.RestClient

or via .NET Core CLI: dotnet add package DalSoft.RestClient

Either way is fine.

Once we have our library, we can do something like this:

public string GetReleases(string url)
{
    dynamic client = new RestClient(RequestConstants.BaseUrl,
        new Headers { { RequestConstants.UserAgent, RequestConstants.UserAgentValue } });

    var response = client.repos.restsharp.restsharp.releases.Get().Result.ToString();

    return response;
}

or preferably by using DalSoft.RestClient to deserialize the response immediately while utilizing its full power:

public async Task<List<GitHubRelease>> GetDeserializedReleases(string url)
{
    dynamic client = new RestClient(RequestConstants.BaseUrl,
        new Headers { { RequestConstants.UserAgent, RequestConstants.UserAgentValue } });

    var response = await client.repos.restsharp.restsharp.releases.Get();

    return response;
}

So, let’s talk about these examples a bit.

At first glance, it doesn’t seem much simpler than some other modern libraries that we’ve used.

But it comes down to the way form our requests and that’s by utilizing the dynamic nature of our RestClient. For example, our BaseUrl is https://api.github.com and we need to get to the https://api.github.com/repos/restsharp/restsharp/releases. We can do that by creating our client dynamically and then forming the Url by chaining “parts” of the Url:

await client.repos.restsharp.restsharp.releases.Get();

A pretty unique way to form a request. And a very flexible one too!

So, once we have our base Url set, we can play with different endpoints easily.

It’s also worth mentioning that the JSON response we get is being automatically type-casted. As you can see in the second example, the return value of our method is Task<List<GitHubReleases>>. So the library is smart enough to cast the response to our type (relying on Json.NET). That makes our life much easier.

Besides being easy to understand and use, DalSoft.RestClient has everything a modern library should have. It is configurable, asynchronous, extensible, testable and it supports multiple platforms.

We’ve demonstrated just a small portion of the DalSoft.RestClient features. If this got you interested in using DalSoft.RestClient, head over to our article about it to learn how to use it in different scenarios or refer to the official GitHub repo and documentation.

Other Options

There are a lot of other options available for your specific problems. You can use any of these libraries to consume a specific RESTful API. 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.

Source Code on GitHub

Source Code on GitHub

Conclusion

So, to summarize, we’ve talked about different tools you can use to consume a RESTful API. We’ve 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. We’ve also given you very short introductions to those tools and made some very simple examples to show you how you can start using them.

We 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 🙂

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!