Writing REST API tests using RestSharp

To conclude our recent REST API testing series for beginners, I want to finish off by showing you how you can make REST API calls and validate the responses coming back directly without the use of any Tool but rather directly from code.

RESTAssured can be used in the Java world but as I am a .Net guy I will show you through Visual Studio. Firstly install Visual Studio if you haven’t already from https://visualstudio.microsoft.com/downloads/. Visual Studio Community edition can be downloaded for free and it offers pretty much all the functionality you need which is brilliant so download the Visual Studio 2017 Community version (Note that if you are reading this some time after it was written, you may be downloading Visual Studio 2019 Community).

Create a basic Test Project inside Visual Studio

Install RESTSHARP as a NuGet Package and import the following libraries at the top of your Test File:

using NUnit.Framework;
using RestSharp;
using RestSharp.Deserializers;
using RestSharp.Serialization.Json;
using System.Collections.Generic;

Give your test method a meaningful name and then let us get right into really cool RESTSHARP world!

First we want to create the client connection so create a RestClient object using the same endpoint as we used in Postman

RestClient client = new RestClient(“https://jsonplaceholder.typicode.com/users”);

The RestClient initializes a client with the specified Base URI to send requests. In addition to the base URI, we want to add the first id value of 1 and also do a GET Request to fetch the data

RestRequest request = new RestRequest(“1”, Method.GET);

We now want to execute the request and we can so with the interface IRESTResponse

IRestResponse response = client.Execute(request);

So now we have sent off the request, the last thing for us to do is to validate the response back
One of the most basic checks we want to is to check the status code returned back is OK and we can do that by

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));

Run that from the test runner in visual studio and there you have it, we have managed to create the same test we used Postman for directly using C# code.

We can create further tests as we have the response. We can deseralize the data which is basically converting the JSON Response back into a C# object, serializing is the opposite.

var deserialize = new JsonDeserializer();
var output = deserialize.Deserialize>(response);

We can then assert the various data items e.g. in this case if we want to assert the name of our response, we can do that

var result = output[“name”];
Assert.That(result, Is.EqualTo(“john”), “author not correct”);

Now you are familiar with RESTSHARP, start writing some more tests!