A REST Client in .net standard

One of my libraries on GitHub is the DewRestClient, a simple library that can help you to make REST request in .net. The library is writte in .net standard  so you will be able to use it in a .net core, xamarin, uwp, etc. project.

Lets see how it works.

A good explanation of the library and its types is in the readme. What we are doing here is to see a good example of use.

We have the current scenario.

We need to make a POST request for a login and GET request to get a list of cities that starts with a name.

RESTRequest request = new RESTRequest(myUrl);
RESTClient client = new RESTClient(HeadersValidation.No);

What we need to do in first time is to set our request object with the correct arguments (headers, data, etc.)

In the block above, we have instantiated the rest request object with the api url, after that we have setted the method and added a querystring argument.

After the Request setup, we have instantiated a RESTClient object (that is who will make the request).

The request will be performed this way.

using (RESTResponse response = (RESTResponse)await client.PerformRequest(request))
    if (response.IsSuccesStatusCode())
        System.Diagnostics.Debug.WriteLine("Request OK!");
    //read the response directly as a string
    string json = await response.ReadResponseAsStringAsync();

NOTE: Request is done into a using directive because the response is an IDisposable object and need to be disposed after the use. If you don’t want to use the using directive, remember to dispose it!

The RESTResponse object has some useful function like IsSuccessStatusCode that tell you if the request has a successful status code (200=> & <300), also for Fault, Errors, etc.

Another useful function is the ReadResponseAsStringAsync that let you read the response directly as string.

However, this is for the scenario with GET request, now lets see the scenario with POST request.

RESTRequest request = new RESTRequest(myUrl);
RESTClient client = new RESTClient(HeadersValidation.No);

How you can see, it is very similar to the previous block of code. We will make the request in the same way.

NOTE:  AddMultipartFormData function is a helper, you can always construct your content with a files, string contents, byte contents, etc. and add it to the request with AddContent function. However, you can’t use both in the same time, because the last will overwrite the content of the previous.