Friday, May 21, 2021

API Automation Using RestSharp [ Multipart/Form Data ]

 


Multipart/Form Data

A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

Swagger Link : https://petstore.swagger.io/#/

Code :  

 [TestClass]
    public class DemoPostOperations
  {
    [Test]
        public void MultipartFormData()
        {
            var client = new RestClient("https://petstore.swagger.io/v2/");
            client.Authenticator = new HttpBasicAuthenticator("api_key", "****");
            var request = new RestRequest("pet/10/uploadImage", Method.POST);
            
            request.AddHeader("Content-Type", "multipart/form-data");
            request.AddHeader("Accept", "application/json");

            request.AddParameter("additionalMetadata", "abc123");
            request.AddFile("file", @"C:\Users\Admin\source\repos\WebserviceAutomation\WebserviceAutomation\Post Operations\Screenshot_1.jpg");

            IRestResponse response = client.Execute(request);
            var resonseContent = response.Content;

        }
 }


Response Body : 

{"code":200,"type":"unknown","message":"additionalMetadata: abc123\nFile uploaded to ./Screenshot_1.jpg, 18091 bytes"}

Sunday, May 2, 2021

API Automation Using HttpClient [GET Operation]

                  

 

HttpClient Class






Its a class for sending Http Request and receiving Http  Response from a resource identified by a URI 


Basic GET Operation using  httpclient 

[TestClass]
    public class Tests
    {
        private string getUrl = "https://reqres.in/api/users?page=2";
        [Test]
        public void TestMethod1()
        {

            // step 1. To  create http client 
            HttpClient httpClient = new HttpClient();

            //step for create the request and execute the request 
            Task<HttpResponseMessage> responseMessage = httpClient.GetAsync(getUrl);
            HttpResponseMessage httpResponseMessage = responseMessage.Result;
            Console.WriteLine(httpResponseMessage.ToString());

            //for printing the statusCode
            HttpStatusCode httpStatusCode = httpResponseMessage.StatusCode;
            Console.WriteLine("StatusCode=>{0}", httpStatusCode);
            Console.WriteLine("StatusCode=>{0}", (int)httpStatusCode);

            //for printing the content
            HttpContent httpContent = httpResponseMessage.Content;
            Task<string> ResponseContentData = httpContent.ReadAsStringAsync();
            string responseData = ResponseContentData.Result;

            Console.WriteLine(responseData);
            // step for closing the connection
            httpClient.Dispose();

        }
}