SoFunction
Updated on 2025-04-13

A detailed explanation of how to use RESTful API in C#

Through the path to web development, you find that you need to deal with external APIs (application programming interfaces). In this article, my goal is to list the most comprehensive list of methods that use RESTful API in a C# project and show you how to do this with some simple examples.

After reading this article, you will have a deeper look at what options you can use and how to choose the right option next time you need to use the RESTful API.

What is the RESTful API?

So before you start, you might be wondering what the API stands for and what is the full meaning of RESTful?

In short, APIs are layers between software applications. You can send the request to the API and get a response from it. The API hides all the details of the specific implementation of the software application and exposes the interface you use to communicate with the application.

The entire Internet is a large spider web composed of APIs. We use APIs to communicate and associate information between applications. We have an API that handles almost everything. Most of the services you use every day have their own APIs (GoogleMaps, Facebook, Twitter, Instagram, Weather Portal…)

The RESTful part means that the API is implemented according to the principles and rules of REST (representing state transmission), which is the infrastructure principle of the network. The RESTful API returns plain text, JSON or XML responses in most cases. Explaining REST in more detail is beyond the scope of this article, but you can read more about REST in our article REST API Best Practices [6].

How to use RESTful API

Well, let's get to the most important part of the whole story.

There are several ways to use the RESTful API in C#:

HttpWebRequest/Response Class

WebClient Class

HttpClient Class

RestSharp NuGet Package

ServiceStack Http Utils

Flurl

DalSoft

.RestClient

Each of these has pros and cons, so let's take a closer look at them and see what they offer.

For example, we will collect information about the RestSharp repo version and its release date through the GitHub API. This information is publicly available, you can see the appearance of the original JSON response here: RestSharp Version

We will use the library's help to deserialize the obtained response. Again, for some examples, we will use the library's built-in deserialization mechanism. Which way to choose depends on you, because there is no right way. (You can see implementations of both mechanisms in the source code).

I'm expecting to get a deserialization with the next few examplesJArray(For simplicity), which contains RestSharp release information. After that, we can iterate over it to get the following results.

HttpWebRequest/Response class

This isWebRequestThe HTTP-specific implementation of the class, which was originally used to handle HTTP requests, was outdated andWebClientThis class replaces .

ShouldHttpWebRequestProvide every step of the requirement formulation process of fine-grained control. As you can imagine, this could be a double-edged sword, and it's easy for you to waste a lot of time fine-tuning your requests. On the other hand, this may be exactly what you need for a specific case.

HttpWebRequestClasses won't block the user interface, that is, I'm sure you'll agree with this, which is very important.

HttpWebResponseThe class provides a container for the incoming response.

Here is a simple example of how to use the API using these classes.

public class HttpWebRequestHandler : IRequestHandler
{
    public string GetReleases(string url)
    {
        var request = (HttpWebRequest)(url);

         = "GET";
         = ;
         =  | ;

        var content = ;

        using (var response = (HttpWebResponse)())
        {
            using (var stream = ())
            {
                using (var sr = new StreamReader(stream))
                {
                    content = ();
                }
            }
        }

        return content;
    }
}

Although it is a simple example, it becomes more complex when you need to deal with more complex scenarios (e.g., publish form information, authorization, etc.).

WebClient Category

This classHttpWebRequestpackaging. It passesHttpWebRequestSimplify the process by extracting details from developers. The code is easier to write, and you are less likely to make mistakes in this way. If you want to write less code without worrying about all the details and the execution speed is not important, consider usingWebClientclass。

This example should give you a general understandingWebClientandHttpWebRequestHttpWebResponseThe method is much easier to use than it is.

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

    var response = (url);

    return response;
}

Much easier, right?

In addition to otherDownloadStringmethod,WebClientClasses also provide many other useful ways to make our lives easier. We can easily use it to manipulate strings, files, or byte arrays, and the price is higher thanHttpWebRequestHttpWebResponseThe method is several milliseconds slower.

Whether it isHttpWebRequestHttpWebResponseandWebClientClasses are available in older versions of .NET. If you are interested in other products, be sure to check out MSDN[16]WebClient

HttpClient class

HttpClientis "newcomer", which provides some modern .NET features lacking in the old library. For example, you can use a single instance to send multiple requestsHttpClient, it does not bind to a specific HTTP server or host, but uses the async/await mechanism.

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

• Strongly typed title.

•Shared cache, cookies and credentials

• Access cookies and share cookies

•Control cache and share cache.

•Inject your code module into the pipeline.

Clean and modular code.

HttpClientIn our example, this is the actual:

public string GetReleases(string url)
{
    using (var httpClient = new HttpClient())
    {
        (, );

        var response = (new Uri(url)).Result;

        return response;
    }
}

For simplicity, I implemented it synchronously. EachHttpClientAll methods should be used asynchronously and should be used in this way.

In addition, I want to mention one more thing. whetherHttpClientShould it be wrapped in the using block or static discussion at the application level. Although it has been implementedIDisposable, but it seems that by wrapping it in a using block, the application fails and gets a SocketException. In the ANKIT blog, it provides a lot of benefits for static initializationHttpClientThe performance test results are.Be sure to read these blog posts,Because they can help you understand thisHttpClientCorrect usage of the library.

And don't forget that because it's new,HttpClientIt is only available in .NET 4.5 or above, so using it in some older projects may be troublesome.

RestSharp

RestSharp is an OpenSource alternative to the standard .NET library and one of the coolest .NET libraries available today. It is available in the form of NuGet packages and for some reason you should consider giving it a try.

Just likeHttpClientLike RestSharp, it is a modern and comprehensive library that is easy to use and pleasing while still supporting older versions of the .NET Framework. It has built-in authentication and serialization/deserialization mechanisms, but allows you to override them with a custom mechanism [24]. It is available across platforms and supports OAuth1, OAuth2, basic, NTLM and parameter-based authentication. You can choose to work synchronously or asynchronously. There are many other features in the library, and these are just some of the many benefits it offers. For more information on the usage and features of RestSharp, you can visit the RestSharp page on GitHub.

Now let's try to get a list of RestSharp versions using RestSharp get.

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

    var response = (new RestRequest());

    return ;
}

Very simple. RestSharp is very flexible and has all the tools you need to implement almost all your functions when using the RESTful API.

One thing to note in this example is that I don't use RestSharp's deserialization mechanism due to the consistency of the examples, which is a bit of a waste, but I encourage you to use it because 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; }
}

Then use thisExecuteThe method deserializes the response to the container directly. You can add only the required properties and use the propertiesJsonPropertyMap them to C# properties (good touch). Since we got the publish list in the response, we willListUsed as the inclusion type.

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

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

    return ;
}

A very direct and elegant way to get our data.

RestSharp not only has sendGETThe requested function can also be explored and observed by yourself.

The last point to be added in the RestSharp case is that its repository needs a maintainer. If you want to learn more about this great library, I urge you to head to the RestSharp repository to help the project continue to grow and get better.

ServiceStack Http Utility

Another library, but unlike RestSharp, ServiceStack seems to be properly maintained and keeps in sync with modern API [29] trends. The ServiceStack feature list is impressive and certainly has a variety of applications.

What is most useful for us here is demonstrating how to use the external RESTful API. ServiceStack has a specialized way to handle [30] third-party HTTP API called Http Utils.

Let's see how to use the parser first to get the RestSharp version using ServiceStack Http Utils.

public string GetReleases(string url)
{
    var response = (webReq =>
    {
         = ;
    });

    return response;
}

You can also choose to leave it to the ServiceStack parser. We can reuse the previously definedReleasekind .

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

    return releases;
}

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

Although ServiceStack is the last library we stumbled upon, I was surprised that it is so easy to use, and I think it might become my go-to tool for dealing with APIs and services in the future.

Flurl

One of the libraries that many people ask for in the comment library and is loved by many on the Internet, but still attracts people.

Flurl stands for Fluent Url Builder, which is how libraries build their queries. For those who are not familiar with how flurl does things, flurl just means that the way libraries are built is to link methods together for higher readability, similar to human languages.

To make things easier to understand, let's give some examples (this example comes from the official documentation):

// Flurl will use 1 HttpClient instance per host
var person = await ""
    .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 methods are linked together to complete the "sentence".

In the background, Flurl enhances the HttpClient library using HttpClient or through its own syntax sugar. So, this means Flurl is an asynchronous library, so keep this in mind.

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

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

    return (result);
}

This approach is pretty bad because we just serialize the result so that we can deserialize it later. If you are using a library like Flurl, you should not do it this way.

A better way to do things is:

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

    return result;
}

along with.ResultWe force the synchronous behavior of the code. The actual and expected way to use Flurl is as follows:

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

    return result;
}

This demonstrates the full potential of the Flurl library.

Now, this list is a little different from anything in that list. But this is different.

Let's see how to use the GitHub API using it and then talk about what we've done.

First, you can download it through the NuGet package manager by typing the following:Install-Package

Or through the .NET Core CLI:dotnet add package

Both methods are OK.

Once we have a library, we can do the following:

public string GetReleases(string url)
{
    dynamic client = new RestClient(,
        new Headers { { ,  } });

    var response = ().();

    return response;
}

Or preferably use deserializing the response immediately while taking full advantage of its functionality:

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

    var response = await ();

    return response;
}

So let's discuss these examples a little bit.

At first glance, it doesn't seem much simpler than some of the other modern libraries we use.

But this boils down to the way to form the request, which is to take advantage of the dynamic characteristics of RestClient. For example, our BaseUrl is, we need to enter/repos/restsharp/restsharp/releases. We can do this by creating a client dynamically and then forming a Url by linking the "parts" of the Url:

await ();

A very unique way to form a request. There is also a very flexible one!

So once we set up the basic URL, we can easily use different endpoints.

It is also worth mentioning that the JSON response we get will automatically convert type. As you can see in the second example, the return value of our method isTask>.So, the library is smart enough to convert responses to our type (dependent on). This makes our lives easier.

Besides being easy to understand and use, there are all the features that modern libraries should have. It is possibleConfigurable, asynchronous, extensible, testable, and supports multiple platforms

Other options

There are many other options available for your specific question. You can use any of these libraries to use a specific RESTful API. For example, dedicated to the GitHub API, the Facebook SDK is used to use the Facebook API, and there are many other features available for any purpose.

While these libraries are designed specifically for these APIs and may be good at their uses, their uses are limited because you often need to connect multiple APIs in your application. This can result in different implementations of each implementation, as well as more dependencies, which can lead to duplication and error-prone. The more specific the library is, the less flexible it is.

in conclusion

So, all in all, we have discussed different tools that can be used to use the RESTful API. We've mentioned some .NET libraries that can do thisHttpWebRequestWebClientandHttpClient, and some amazing third-party tools like RestSharp and ServiceStack. You also gave a brief introduction to these tools and gave some very simple examples to show you how to get started with them.

I think you are at least 95% ready to use some REST right now. Keep spreading your wings, exploring and finding more fun and fun ways to use and connect different APIs.

This is the end of this article about how to use RESTful API in C#. For more related content on C# using RESTful API, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!