Rest API Testing using C#

Rest API Testing using C#

Rest API has become very popular and it’s nowadays, it is kind of must-have skill set to have for any developer or tester. Every other job description, you can see having experience with API with always preferred. REST API is the 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 to 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 indicate 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 a new resource

PUT:

Update a specific resource or collection of resources.

DELETE:

Remove specific resource based on the identifier.

 

Resource:

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

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

Response:


Response with status code is part of the HTTP specification. There are tons of status code you can find on the 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 to 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 the server is down.

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

Usage:

 

Writing Rest Client in C#:

Let’s 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 the different type of resources via URL because all resources are mapped to 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 the resource via URL then you call the URL as ‘EndPoint’. Type of resources is 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 by using API client as a 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 your chrome browser. Open PostMan and supply endpoint to get Calling Code as given in http://restcountries.eu/https://restcountries.eu/rest/v1/callingcode/65

 

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

based on above screenshot you let design the client via code. You need to create the 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.

[gist id=2d987f7d25d8650358d488db9373cd92]

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

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

[gist id=39c65cecd11322892c6955b579acdf17]

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

[gist id=ab08f069ad5f52ed0fb854784ae9d044]

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

 

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

[gist id=56af368beb77a038448e8c48f8a1927c]

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

You can find complete code here.

[gist id=ae4fbebcf2d949e8aaa3d402741fe571]

Hope you like it. In case, if you are interested in deep dive in for API testing in detail, please go through:

Step By Step Guide to Write API Tests

19 Comments

  1. Nishant

    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 ==========

  2. Kavitha

    Hi,

    I’m trying to use this code for a GET request, but looks like the methods GetResponse() and ContentLength() are no longer present in HttpWebRequest class. I’m unable to type cast other methods to type HttpWebResponse if I try to. Can you help me please?

  3. Nikhil

    Hello, can you please let us know the difference between writing tests like above and testing directly from tool like postman or soapui? What are the advantages of each?

    1. Aditya

      I know it is very late to reply here. Your question was in trash automatically. I do not know why but still I would like to answer.
      There are tools available in the market like postman and soapui(readyTest) and those tools are for someone who does not know to program and do not have many tests. These tools will help you to get started especially developer. Whenever I am writing new code to add route and whenever I am not following TDD approach. I use postman to do quick testing. But for the long term, these tools are not much help unless you buy a licensed version for cicd. When you use code to write your test, you have given yourself enough room to experiment with your code to extend or reuse by another project. I am not against these tools but I always prefer to be writing code and leveraging established CICD pipeline.

Leave a Reply

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