Till now we have learnt about how to make a GET Request using Rest-Sharp.We have also learnt how to read different components of a HTTP Response(Headers, Body and Status). If you have not already read previous tutorials, please take a look at the list of tutorials here:
- Rest API testing using Rest-Sharp
POST Request using Rest Sharp
During this tutorial we will learn about
- Basics of Post Verb/Method/Request
- POST Request using Rest Sharp
- Creating JSON data using Simple JSON library
- Sending JSON content in the body of Request
- Validating the Response.
Now let us make a POST request using Rest-Sharp and before that we need to understand the basics of POST Request.
What is POST verb of HTTP protocol?
HTTP POST method is used to send data to the Server. Common places where you can find a POST request is when you submit Form Data (HTML forms) on a web page. For e.g. submission of registration form of gmail. POST request usually result in changes on the Server like addition of new data or may be update to existing data.
The data that is sent to the server in a POST request is sent in the body of HTTP request. The type of body, XML, Json or some other format is defined by the Content-Type header. If a POST request contains Json data then the Content-Type header will have a value of application/json. Similarly, for a POST request containing XML the Content-Type header value will be application/xml.
Let us understand testing a POST web service using a live example. We will take a look at a registration web service. Web service details are
Endpoint | http://restapi.demoqa.com/customer/register |
HTTP method type: | POST |
Body: | {
“FirstName” : “value” “LastName” : “value”, “UserName” : “value”, “Password” : “value”, “Email” : “Value” } |
Success Response: | { “SuccessCode”: “OPERATION_SUCCESS”, “Message”: “Operation completed successfully” } |
Failure Response: | { “FaultId”: “User already exists”, “fault”: “FAULT_USER_ALREADY_EXISTS” } |
How to make a POST Request using Rest Sharp?
Let us now try to test the above web service. During this tutorial we will learn about
- POST request using Rest Sharp
- Creating Json data using Simple Json library
- Sending JSON content in the body of Request
- Validating the Response.
In order to create JSON objects in the code we will add Newtonsoft.Json.Linq library in the class path. You can download Newtonsoft.Json.Linq from NuGet using
Let us begin step by step with the code
Step 1: Create a Request pointing to the Service Endpoint
1 |
RestClient restClient = new RestClient("http://restapi.demoqa.com/customer"); |
This code is self explanatory. If you are not able to understand it you have missed the earlier tutorials in this series, please go through them first.
Step 2: Create a JSON request which contains all the fields
1 2 3 4 5 6 |
JObject jObjectbody = new JObject(); jObjectbody.Add("FirstName", "Narayn"); jObjectbody.Add("LastName", "Kaluri"); jObjectbody.Add("UserName", "NaraynKaluri"); jObjectbody.Add("Password", "Password@123"); jObjectbody.Add("Email", "abc@hotmail.com"); |
JObject is a class that is present in Newtonsoft.Json.Linq. namespace. This class is a programmatic representation of a JSON string. Take a look at the Request JSON above for our test web service, you will notice that there are multiple nodes in the Json. Each node can be added using the JObject.Add(String, String) method. First parameter is json propertyName and second is propertyValue.
Step 3: Add JSON body in the request and send the Request
1 2 3 |
RestRequest restRequest = new RestRequest("Guntur", Method.POST); restRequest.AddParameter("application/json",jObjectbody,ParameterType.RequestBody); |
This web service accepts a JSON body. By this step we have created our JSONbody that needs to be sent. In this step we will simply add the JSON object to the body of the HTTP Request and make sure that the Content-Type header field has a value of application/json.
You can put the JSON object in the body using the method called restRequest.AddParameter(content type, object, parameter type). This method lets you updated the content of HTTP Request Body. However, if you call this method multiple times the body will be updated to the latest Json object.
Alternative to the above two steps you can combine into a single and use as shown below.
1 2 3 4 5 6 |
//Specifies request content type as Json restRequest.RequestFormat =DataFormat.Json; //Create a body with specifies parameters as json restRequest.AddBody(new { FirstName = "Narayn", LastName= "Kaluri", UserName= "NarsaynKaluri" , Password= "Passwvvord@123" , Email= "avbc@hotmail.com" }); |
Step 4: Validate the Response
Once we get the response back, all we have to do is validate parts of the response. Let us validate Success Code text in the Response, we will be using JObject.
Now that we have sent the Request and received a Response, let us validate Status Code and Response Body content. This is similar to validation techniques that we discussed in previous tutorials. I would strongly suggest that you read those tutorials. The above code does the validation, it is self-explanatory.
Complete code
Here is the complete code for the above example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using RestSharp namespace RestSharpExample { [TestClass] public class UnitTest1 { [TestMethod] public void PostMethod() { RestClient restClient = new RestClient("http://restapi.demoqa.com/customer"); //Creating Json object JObject jObjectbody = new JObject(); jObjectbody.Add("FirstName", "Narayn"); jObjectbody.Add("LastName", "Kaluri"); jObjectbody.Add("UserName", "NaraynKasdfsdfluri"); jObjectbody.Add("Password", "Passwovasdfsdaf23"); jObjectbody.Add("Email", "abcdafsad@hotmail.com"); RestRequest restRequest = new RestRequest("/register" ,Method.POST); //Adding Json body as parameter to the post request restRequest.AddParameter("application/json",jObjectbody,ParameterType.RequestBody); IRestResponse restResponse = restClient.Execute(restRequest); Assert.Contains("OPERATION_SUCCESS ", restRequest.Content," Post failed "); } } } |
Changing the HTTP Verb on a POST request
One of the key aspect of Web service testing is to verify negative scenarios on the Endpoint. There could be many negative scenarios, some of them are
- Sending incomplete POST Data
- Sending Json data with incorrect syntax
- Sending incorrect Verb in the Request.
Let us see what the impact will be if we send a GET request to an Endpoint that expects POST. Below code tries to do that, we will just print out the Response status code and the Response body to see if we get any error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using RestSharp namespace RestSharpExample { [TestClass] public class UnitTest1 { [TestMethod] public void PostMethod() { RestClient restClient = new RestClient("http://restapi.demoqa.com/customer"); //Creating Json object JObject jObjectbody = new JObject(); jObjectbody.Add("FirstName", "Narayn"); jObjectbody.Add("LastName", "Kaluri"); jObjectbody.Add("UserName", "NaraynKasdfsdfluri"); jObjectbody.Add("Password", "Passwovasdfsdaf23"); jObjectbody.Add("Email", "abcdafsad@hotmail.com"); RestRequest restRequest = new RestRequest("/register" ,Method.GET); //Adding Json body as parameter to the post request restRequest.AddParameter("application/json",jObjectbody,ParameterType.RequestBody); IRestResponse restResponse = restClient.Execute(restRequest); Assert.Contains("OPERATION_SUCCESS ", restRequest.Content," Post failed "); } } } |
If you run this test following output is generated. In the output we can clearly see that the Response body tells us about the incorrect usage of HTTP Verb. HTTP verb are also know as the Method types, given we actually make a remote method call and specify the type of the method call.