API Testing using RestSharp | Code Example

RestSharp is a comprehensive, open-source HTTP client library that works with all kinds of DotNet technologies.  RestSharp is one of the ways to create a web service or web request in .NET; In today’s post, we’ll take a look how to do API Testing using RestSharp and few example of API testing using RestSharp in action.

Visual Studio has NuGet Package Called “RestSharp” which will make your task easier for testing Rest API using RestSharp. You may use “Newtonsoft.json” Package to DeserializeObject and chain multiple API requests.

You can use RestSharp to send Get, Post, PUT, Delete and Patch Request and can get the response back from the API. In the Response, you can verify Status Code, Status Message, Assertion for specific Json or XML Data .

Steps:
Step 1: Create a New Console Application in the Visual Studio (NUnit used in example)
Step 2: Add RestSharp, Newtonsoft.json and Nunit Reference from Nuget Package
Step 3: Write a Request (See example and comments of example for detail)
Step 4: Assert the API for the Status Code and Status Response .
Step 5: Deserialize the Response to passed into another API if needed.

Code Example 1 | POST

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using RestSharp;
using RestSharp.Authenticators;
using System;
using System.Net;

namespace MyNamespace
{
    [TestFixture]
    public class MyClass
    {
        [Test]  //This Test using NunitFramework
        public void RestApiTestingPOST()   //Sample Test Name of REST API POST Method
        {
            string URL = "http://myurl/URL";  //Rest API URL
            string RequestBody = "{'Key1': 'Value1', 'Key2': 'Value2'}";  //Rest API POST Body

            var client = new RestClient(URL);
            var request = new RestRequest(Method.POST);    //Selecting Rest API Method Type
            request.AddHeader("cache-control", "no-cache");   //Adding required Header
            request.AddHeader("content-type", "application/json");  
            request.AddParameter("application/json", RequestBody, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            string tokenresponse = response.Content;

            JToken user = JsonConvert.DeserializeObject(tokenresponse);
            Console.WriteLine(user);
            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); //Verifying Status Code
        } 

Code Example 2 | GET

  [Test]
        public void RestApiTestingGET()
        {
            string URL = "http://myurl/URL";  //Rest API URL
            string RequestBody = null;  //GET Method doesn't contain any request Body
            string Username = "myUname";  //Variables for Authenticaton Header
            string Password = "myPass";

            var client = new RestClient(URL);
            var request = new RestRequest(Method.GET);  //Selecting Rest API Method Type
            request.AddHeader("cache-control", "no-cache");    //Adding required Header
            request.AddHeader("content-type", "application/json");  //Adding Json Header as response type Json
            client.Authenticator = new HttpBasicAuthenticator(Username, Password);  //Adding Authenticaton Header
            request.AddParameter("application/json", RequestBody, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            string tokenresponse = response.Content;

            JToken user = JsonConvert.DeserializeObject(tokenresponse);
            Console.WriteLine(user);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);  //Verifying Status Code to make sure response is as expected
        } 

Code Example 3 | Git

var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);

var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

// add parameters for all properties on an object
request.AddObject(object);

// or just whitelisted properties
request.AddObject(object, "PersonId", "Name", ...);

// easily add HTTP Headers
request.AddHeader("header", "value");

// add files to upload (works with compatible verbs)
request.AddFile("file", path);

// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string

// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
IRestResponse response2 = client.Execute(request);
var name = response2.Data.Name;

// or download and save file to disk
client.DownloadData(request).SaveAs(path);

// easy async support
await client.ExecuteAsync(request);

// async with deserialization
var asyncHandle = client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Data.Name);
});

// abort the request on demand
asyncHandle.Abort(); 

This is a open-source international community to improve software testing practices, send your post here

Advertisements

Leave a Reply