Friday, July 19, 2019

Setup Swagger for ASP.Net Web API

this blog demonstrates step by step to add swagger in web api project and will submit  http request GET/POST/PUT via swagger UI.

Swagger is API developer tools for the Open API Specification(OAS), enabling development across the entire API life cycle, from design and documentation, to test and deployment.

Definition -
Swagger is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment. With a Swagger-enabled API, you get interactive documentation, client SDK generation and discoverability.”

To add Sweggar into WEBAPI Project, you need to perform only 2 steps

1. Install SwashBuclkle open source project via Nuget.

Install SwashBuclkle Nuget Package

 2. Configure Swagger Config File :
         after package installed, you will find a new file ‘SwaggerConfig.cs’ under App_Start Folder

    
Swagger Config

public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {             
                        c.SingleApiVersion("v1""DemoWebAPI");                 
                    })
                .EnableSwaggerUi(c =>
                    {
                        c.DocumentTitle("Demo Web API");

                    });
        }
    }

build and run webAPI project and browser http://localhost:65096/swagger

Swagger UI documentation















Swagger allow you can submit HTTP request GET, HTTP POST, HTTP PUT against Web API

Example - Submit HTTP GET Request For /api/Projects/{projectId}

SOAP UI - Test Web API/REST API

SoapUI is built for end-to-end testing of Rest and SOAP Apis, Web Service and Micro Service.  SoapUI can easily automated API testing and perform load testing.
this blog will demonstrates the steps by steps to perform web api testing.

Header :
X-API-UserName :
X-API-Token :

In above API, we need to pass Order ID as part of API‘s Path and for API security verification, we have to pass user Name and API token as HTTP Request Header.

1.     Install SOAPUI Tool
2.     Run the SoapUI app and click on REST Icon

SOAP UI


3.     Enter REST API URL  -  https://localhost:/Order/ID/1000

SOAPUI - REST API URL


4.     Click on Header Tabs and enter Header Name and Value ( in example, X-API-Token Header)  

SOAP UI - ADD HEADER
         
Click on OK

SOAP UI -  HEADER


5.     Click on Run Button () to submit HTTP Request for API

SOAPUI - Submit HTTP REQUEST



Web Performance and Load Testing of Web API

This blog will explain the steps by steps to create and perform load testing for web AP (restful service) and will discuss about constant and step load pattern.
In the Enterprise edition of Visual Studio, Web performance and load test projects are available and  you can install the load testing component

Steps to create Web Request:

1.       Create Web Performance and Load Test Project
·         Open the visual studio and choose Create a new project
·         select the Web Performance and Load Test Project



               Web Performance and Load Test Project:

            
       
2.       Create Web API request : Select WebTest1.Webtest and click on Add Request options         


                        
Provides the API URL  

                                            
·         Add Header, if required
·         Add Query String, if required

In current request, Token Header is added

                      

Steps to create load test:

1.       Right click on project node and choose the Add à Load test
2.       “New Load Test Wizard” Options

                                       

            There are two options
1.       Cloud-based Load test
2.       On –premises Load Test

         If you want to run in local network and on local system, choose the On-premises load test and click on Next, ‘Run Setting’ screen will be appeared

3.       Run Settings        


In Load run setting, you can provide the total load test duration time along with warm-up duration time
                Load test duration
                                Run duration: 10 mins
                                Warm –up duration: 30 secs

Click on Next, scenario screen will be appeared

4.       Load Test scenario

                  
               
You can give load test scenario name – ConstantLoad and click on Next button, Load Pattern screen will be appeared.

5.       Load Pattern

                               
             
There are two type of load patterns
·         Constant Load
·         Steps Load

In constant loan, the same loaded will be applied for all testing duration and load will not be changed.
In steps pattern, the load will be gradually increased after given step duration

We choose constant load and entered 10 user count for load testing and click on Next button, the test Mix Model screen will be appeared.

6.       Test Mix Model:

                                        

There are following models for test mix

·         Based on the total number of tests
·         Based on the number of virtual users
·         Based on user pace
·         Based on sequential test order

For this load testing, I choose the based on the number of virtual users option and click on Next button, The Tax Mix Screen will be appeared.

7.       Test Mix




You can add tests to a load test scenario

Click on Add button à Add Tests popup window will be opened and you can select test from Available tests list and click on OK button.





You can distribute load (in %) among all selected tests and if you want to manually adjust the distribution, simply enter value under % column or use scroll-bar
under distribution column .



If you want to load should be equally distributes among all tests, click on Distribute button

Click on Next button, the Network Mix will be appeared.

8.       Network Mix



In Network Mix, you can add one or more network types for load testing and also you can distribute among them (simply enter value or use scroll-bar)
Click on Next button, the browser mix screen will be appeared.

9.       browser mix



In browser mix, you can add one or more browser for load testing and also you can distribute load among them (in above pic) I have selected two browser
Chrome and Firefox for load testing and load are equally distributed.

Click on Next button, the Counter Set wizard will be opened.



And click on Finish Button, the Load Test is created and simple open the Load test in Load Test Editor



Right click on root node (LoadTest2) and Select Run Load Test.



Install Unity Container in Web API

This blog discuss about the unity and its feature and demonstrates the steps  by steps to install unity in web api project by using nugget package and explain about the type mapping registration

Unity Container :

The Unity is a full feature, a light weight, extensible dependency injection container, it helps to build the loosely coupled program and simplified object creation.

Unity Container Features:

1.       Abstraction the dependency of program and on demand it injects dependency.
2.       Simplified type-mapping registration for interface type or base type.
3.       Automatically injects registered type at run-time through constructor, property or method.
4.       Automatically manages the scope of instance and if it goes outside scope, it automatically dispose the instance.


Installation of Unity in Web API Project:

Here are steps to install unity package in our web API application.

1.       Open the nuget package manager



2.       Search ‘Unity’ package


3.       Click on install button to install unity package.

Unity.WebAPI package allows the simple Integration of the Unity IoC container with ASP.NET Web API. 

Here are steps to install unity.WebAPI package in our web api application.

1.       Open the nuget package manager
2.       Search ‘Unity.WebAPI’ package
3.       Click on install button to install unity.webapi package.


after two packages installations, there are few dll reference are added into project 



after unity.webapi package installation, the UnityConfig.cs class file is added under App_Start folder. 



In UnityConfig file, it contains the mapping for register types eg ( IOrderEngine ) and having information dependence resolver ( we are using Unity.WebAPI assembly as resolver)


C# Code :

public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();
           
            container.RegisterType<IOrderEngineOrderEngine>();
           
            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }


Add line in Global.asax.cs to configure unity container

C# Code :

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            UnityConfig.RegisterComponents();  ß------------ Add line
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }



OrdersController is WEB API  Controller, which create and update the order information. You can see, the IOrderEngine type is being passed as parameter into API controller’s constructor and when API constructor is being called; it uses unity to resolve the IOrderEngine type.

C# Code :

    [RoutePrefix("api/Orders")]
    public class OrdersController : ApiController
    {
        IOrderEngine _orderEngine;

        public OrdersController(IOrderEngine orderEngine)
        {
            _orderEngine = orderEngine;
        }

        [HttpPost]
        [ApiVersion("1.0", Deprecated = true)]
        [ApiVersion("2.0")]
        [Route("v{version:apiVersion}/Create")]
        public IHttpActionResult Create(Order Order)
        {
            return Ok(_orderEngine.Create(Order));
        }

        [HttpPut]
        [ApiVersion("1.0", Deprecated = true)]
        [ApiVersion("2.0")]
        [Route("v{version:apiVersion}/Update")]
        public IHttpActionResult Update(Order Order)
        {
            return Ok(_orderEngine.Update(Order));
        }

    }

other dependency injection and unity container  related posts : 

Setup Swagger for ASP.Net Web API

this blog demonstrates step by step to add swagger in web api project and will submit  http request GET/POST/PUT via swagger UI. Swagger ...