How to Automate REST API using RestSharp?



How to Automate REST API using RestSharp?

Manual Testing, Selenium with C#/Java automation, Appium,.NET. Angular, Sales force training/Interview support/Job support provided. Please call @ +91 888 588 5855 /Training@Techtutorialz.com

In order automate the API using RestSharp, we need to follow the steps below:

  1. Create a test class clsTourist and test method VerifyStatusCode() in solution project.
  2. Use the RestSharpclass to generate a RestClient for the URL: http://restapi.adequateshop.com/api/Tourist?page=1
  3. Create request from client and specify the HTTP Method type.
  4. Send the Request to the Server.
  5. Get the Response back from the server.
  6. Validate returned Response’s Body.

Below is the code to hit the above end point. Let’s have a look at the code first and then at the explanation of the each line of code in the bottom.

The above code will produce the same response which was received when opened the same URL on browser.

[Test]
public void VerifyStatusCode()
{
var restClient = new RestClient(“http://restapi.adequateshop.com”);

var request = new RestRequest(“/api/Tourist?page=1”,Method.GET);

request.AddHeader(“Content-Type”, “application/json”);

var fullUrl = restClient.BuildUri(request);
Console.WriteLine(“url:” + fullUrl);

var response = restClient.ExecuteGetAsync(request);

while (response.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine(“Thread ID: {0}, Status: {1}”, Thread.CurrentThread.ManagedThreadId, response.Status);
Task.Delay(100).Wait();
}
Console.WriteLine(“Status code is:” + response.Result.StatusCode.ToString());
Console.WriteLine(“Response body:” + response.Result.Content.ToString());
Assert.IsTrue(response.Result.StatusCode.ToString()==”OK”,”Status code is not OK”);
}

private static async Task<string> Foo(int seconds)
{
return await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine(“Thread ID: {0}, second {1}.”, Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}

return “Foo Completed.”;
});
}

Understanding the Code

To perform any API call we require to open a browser and provide URL in address bar. Creation of RestClient in RestSharp is similar to that of opening a browser and setting it ready to call any server using URLRestClient initializes a client with the specified Base URI to send requests. In our case the Base URI is  http://restapi.adequateshop.com This is called the Base URI because it is root address of the resource. Adding /api/Tourist?page=1 at the end appends the exact resource name in the URI that we are trying to access.

Creating Request from Client to Server

1 RestRequest restRequest = new RestRequest(“/api/Tourist?page=1”,Method.GET);

As client is created, it is ready to send any request to server. So, request has to be create as specified. RestRequest class creates HTTP Requests against specified URL with type of Protocol. The above request specifies that it needs to get the information from the URL(Base URL+ “/api/Tourist?page=1”)

RestRequest supports creating Request of different HTTP method types (GET, POST, PUT, PATH, DELETE, UPDATE, HEAD and OPTIONS)

Execute Request on Server

var response = restClient.ExecuteGetAsync(request);

string response = response.Result.Content.ToString();

Now that RestRequest object is there, we execute our request to get the resource response from the server. Execute method of RestRequest object actually sends the request to the remote server and gets a response back. This is why the return type of the request.Execute() is specified as var response.

Verifying Response

Assert.IsTrue(response.Result.StatusCode.ToString()==”OK”,”Status code is not OK”);

Assert class is from Unit Framework is used to verify various assertions.

In our example we are checking that weather information is provided as response from the server for given city. So if response status code is “OK” which confirms proper response is received from server else error message will be displayed.

Tags:
1 Comment

I am actually thankful to the owner of this website who has shared this great post at at this time.| Bobine Stirling Laurette

Reply
Leave a comment

Your email address will not be published. Required fields are marked *

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!

https://bridgejunks.com/ https://crownmakesense.com/ https://brithaniabookjudges.com/ https://hughesroyality.com/ https://rhythmholic.com/ https://bandar89.simnasfikpunhas.com/ https://www.100calshop.co.il/products/thailand/ https://myasociados.com/ https://solyser.com/ http://konfidence.cz/ https://muscadinepdx.com/ https://bandar89.parajesandinos.com.ve/ https://goremekoop.com/ https://oncoswisscenter.com/ https://www.turunclifehotel.com/bandar89/ https://www.houseofproducts.biz/ https://taimoormphotography.com/
BIJI18 BIJI18 BIJI18