Rest API Testing using C#

Rest API has become very popular and its nowadays, it is kind of must have skill set to have for any developer or tester. In Every other job description, you can see having experience with API with always preferred. REST API is most popular and you can see Facebook, Twitter, Flickr etc. are coming with APIs and you can build your own application based on that. All major products are providing API interface so developers can utilize and build own product based on the data provided by API services. In this article I will explain you how to use REST web services using C#. Along with explanations, I would keep writing different part of code There.




Rest stands for Representational State Transfer (ReST). It relies on stateless, client-server, cacheable communication protocol mainly running over HTTP protocol. Thus RESTful services are url based https://api.product.com/categories/machines/id/123

Consumers are capable of sending GET, POST, PUT and DELETE verbs and these verbs indicates you what the purpose of the request. There are many other verbs can be used with rest but these are being used heavily across the products.

Verbs:

GET:

To read specific resource or collection of resources.

POST:

create new resource

PUT:

Update a specific resource or collection of resources.

DELETE:

Remove specific resource based on identifier.

 

Resource:

You resource is in URL. Resources are viewed via their URI names, offering consumers a friendly name, easily understandable hierarchy of resource into that. There are some standard but restrict rule to have into resources structures.

  • a. identifier should be in url instead of into query. It’s good to have /serialnumbers/1234 instaed of /api?rnum=1234.
  • b. Resource name should be noun instead of verb else it may confuse with our request verbs.
  • c. Keep url as short as possible.
  • d. avoid hyphans(-) or underscores(_).

Response:


Response with status code is part of the HTTP specification. There are tons of status code you can find on internet. Refer w3.org or RestAPITutorial. I will list my Top 5 which you should memorize and this can be part of your interview too.

  1. 200 OK: Success code.
  2. 201  CREATED: Successfully created happened using POST/PUT.
  3. 401 UNAUTHORIZED:  In response of missing token or invalid authentication.
  4. 404 NOT FOUND: This error occurred when resource not found.
  5. 500 INTERNAL SERVER ERROR: Usually this happens when server is down.

Moreover, RESTful services also support JSON and XML. You can get output in either format.

Usage:

 

Writing Rest Client in C#:

Lets start with C#. First we need to think what we want. It’s simple, we want to create a client at our end where we can use REST api to access or manipulate different type of resources via url because all resources are mapped with url only. Now you solved many things. Read again previous lines and you will find some special words, ‘access or manipulate resource’, ‘url’ and ‘different type of resource’. Since REST is url based and you access resource via url then you call the url as ‘EndPoint’. Type of resources are termed as ‘Content Type’ and access are termed as ‘httpVerb(get/post/put/delete/….)’  and if you need some data to manipulate then this will be termed as ‘Post Data’.

first we will try to access some api via browser or using API client as chrome extension and see the output and later we will write code to replicate the same. One the Rest API service I found is http://restcountries.eu/ this is one of the most simplest REST API I have seen where you do not need to register or use app id to access resources.  We will use these API to learn how to access via client and try to write code which can accommodate both simple and complex type of APIs.

Install PostMan Rest Client in you chrome browser. Open PostMan and supply end point to get Calling Code as given in http://restcountries.eu/https://restcountries.eu/rest/v1/callingcode/65

 

image

you can notice above that you are using verb GET from end point “” and once you click on send button you are getting response in JSON. You can change the format from that drop down and see the response.

based on above screenshot you lets design the client via code. You need to create first client class and this client class should have above attributes.

httpVerb –> GET/POST/PUT/DELETE

endpoint –> some url

ContentType –> json/xml/html

since we need multiple verbs so we can have enum of httpVerb.


public enum httpVerb
{
GET,
POST,
PUT,
DELETE
}

Now create client class  and have all properties into that class that required for accessing resources.

to for and have multiple constructor using method overloading just in case if you like to


public class Client
    {
        public string EndPoint { get; set; }
        public Verb Method { get; set; }
        public string ContentType { get; set; }
        public string PostData { get; set; }

        public Client()
        {
            EndPoint = "";
            Method = Verb.GET;
            ContentType = "application/JSON";
            PostData = "";
        }

        public Client(string endpoint, Verb method, string postData)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "text/json";
            PostData = postData;
        }

}

Once you have object you need methods to perform the the actions on the object. You need to write a method MakeRequest which should perform real action utilizing all variable in that object. Lets work on GET/POST request first.

public string Request(string parameters)
        {
            var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
            request.Method = Method.ToString();
            request.ContentLength = 0;
            request.ContentType = ContentType;
            
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Faile: Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                }

                return responseValue;
            }
        }

Now its time to call the class and create rest client object and call method to access to your object.

 

In your main method, create client object and supply required info and call appropriate method.


var client = new Client();
client.EndPoint = @"<a href="https://restcountries.eu&quot;;">https://restcountries.eu";</a>
client.Method = Verb.GET;
var pdata = client.PostData;
var response = client.Request("/rest/v1/currency/eur");

You can see parse response and get your desired output in JSON.

You can find complete code here.

 


using System;
using System.IO;
using System.Net;
using System.Text;

public enum Verb
{
    GET,
    POST,
    PUT,
    DELETE
}

namespace RestAPITesting
{
    class Program
    {
        static void Main(string[] args)
        {
           
            var client = new Client();
            client.EndPoint = @"https://restcountries.eu";
            client.Method = Verb.GET;
            var pdata = client.PostData;
            var response = client.Request("/rest/v1/currency/eur");
        }
    }
    public class Client
    {
        public string EndPoint { get; set; }
        public Verb Method { get; set; }
        public string ContentType { get; set; }
        public string PostData { get; set; }

        public Client()
        {
            EndPoint = "";
            Method = Verb.GET;
            ContentType = "application/JSON";
            PostData = "";
        }

        public Client(string endpoint, Verb method, string postData)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "text/json";
            PostData = postData;
        }


        public string Request()
        {
            return Request("");
        }

        public string Request(string parameters)
        {
            var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
            request.Method = Method.ToString();
            request.ContentLength = 0;
            request.ContentType = ContentType;
            
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Faile: Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                }

                return responseValue;
            }
        }

    }
}

11 Comments

  • Matthew

    February 16, 2016

    Neatly documented!

    Reply
    • Aditya

      May 13, 2016

      Thanks Matthew!

      Reply
  • ashish

    May 12, 2016

    where to create first client class???

    Reply
    • Aditya

      May 13, 2016

      Create new console project and add code into given .cs and you are done!

      Reply
  • P

    June 21, 2016

    Rest API Automation

    Reply
  • T

    August 22, 2016

    This is great! Thanks!!! Can you please show me the example code for “POST” with json as well?

    Reply
  • Mrudula Vidwans

    March 15, 2017

    This code does not work :(

    Reply
  • Annamalai Viswanathan

    June 30, 2017

    Awesome example. Thank you.

    Reply
  • Nishant

    October 10, 2017

    I have pasted the same code in the Cs File but i am not getting Output. Below is the message which is appearing : ========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========

    Reply
  • Sumit

    November 17, 2017

    How to handle Bearer token authentication, please suggest

    Reply

Leave a Reply