Friday, July 19, 2019

how to create a new ASP.NET Web API

This blog will demonstrates steps by steps to how to create a new ASP.NET Web API and explain its characteristics


ASP.NET Web API is a very light weight .net framework to create HTTP service and it is very easy to build restful service, which covers boarder client like mobile device, desktop and other platform.

ASP.NET Web API


Characteristic of Web API:
  • ASP.NET Web API creates Web API on top of ASP.NET and so it can use ASP.NET request/response pipeline.
  • ASP.NET Web API maps with HTTP verbs (GET, POST, PUT etc.) to Method Name.
  • It supports many response Data formatter (like JSON, XML, BSON).
  • It supports only HTTP protocol.
Here is 4 simple steps to create ASP.NET WEB API by using visual studio.

 Step 1: Open visual studio and click New Project:


 Select Visual C# a Web Asp.NET Web Application (.Net Framework) Template 


    ASP.NET Web Application

    Select Empty project template - it’s an empty project template for creating ASP.NET Web API project

    Web API Empty Project


    Here is Web API Empty Project - SimpleWebAPI


    ASP.NET Web API Project




    Step 2: Add Web API Controller 


    Select Web API 2 Controller – Empty - to create an empty Web API controller

      Add Web API Controller


      Give API Controller Name – TaskController.cs

        Give Web API Controller Name

        Here is TaskController Controller Generated Class 

        C# Code: TaskController.cs

        public class TaskController : ApiController
              {
                public TaskController()
                {

                }  
              }



        Step 3: Add Model Class –Task.cs

        Add Model Class


        Here is Model Class - Task.cs

        C# Code: Task.cs

        public class Task
               {
                public int TaskID { getset; }
                public string Description { getset; }

               }
            


           Step 4: Add API Controller Method – GetTaskByID

           C# Code: TaskController.cs

            public class TaskController : ApiController
            {
                public TaskController()
                {

                } 
              
                [HttpGet]
                public Task GetTaskByID(int taskID)
                {
                    //@Todo Logic to get task by ID
                    return new Task() {  TaskID = 1001, Description = "Todo Task"};
                }
            } 


            By default WebApiConfig.cs class contain web api routing settings
            C# Code: WebApiConfig.cs

              public static class WebApiConfig
            {
                public static void Register(HttpConfiguration config)
                {
                    // Web API configuration and services

                    // Web API routes
                    config.MapHttpAttributeRoutes();

                    config.Routes.MapHttpRoute(
                        name: "DefaultApi",
                        routeTemplate: "api/{controller}/{id}",
                        defaults: new { id = RouteParameter.Optional }
                    );
                }
            }


           It’s done J !! Your web API is ready for use.



          You can use google chrome postman tool to call web api 


        Postman

             Response Body:

        Postman Web API Response




             For API more interactive documentation you can use the Swagger UI and easily setup swagger for ASP.NET Web API

        Swagger UI

        HTTP status code standard of restful API

        While designing the restful API, we need to make sure that API should always return the right and consistence HTTP status Code and without consistent HTTP status codes, customers will not know the difference between success or failure without parsing the response body.

        HTTP standard provides almost 70 status codes to describe the response status and you can use below HTTP status code for restful API.

        200 – OK
        204 – OK – No Content
        400 – Bad Request
        401 – Unauthorized
        500 – Internal Server Error
        503 – Service is not available

        HTTP – GET (Resource Inquiry):

        HTTP GET Sequence Diagram
        HTTP GET Sequence Diagram

        The above sequence diagram explain how the HTTP request is being processed and returns the HTTP status code.

        There are the possible scenarios for processing of the HTTP GET request.

        1.    Scenario :   If request resource is found, Returns HTTP – 200 OK with Resource data

        HTTP GET 200 OK

        2.    Scenario:   If request resource is not found, Returns HTTP – 200 OK with NULL data.

        HTTP GET 200 OK
                   
        3.    Scenario:       Any Validation Error/invalid input – returns HTTP – 400 Bad Request with validation or error message.

                     
        HTTP GET 400 BAD REQUEST


        HTTP – POST (Resource Creation) 

        HTTP POST Sequence Diagram
        HTTP POST Sequence Diagram

        The above sequence diagram explain how the HTTP request is being processed and returns the right HTTP status code.

        There are the possible scenarios for processing of the HTTP POST request.

        1.    Scenario:   If requested resource is successfully created, Returns HTTP – 201 OK with Newly created Resource data

        HTTP POST 201 OK
        2.    Scenario:

        If request resource is already found or duplicate resource, returns – returns HTTP – 400 Bad Request with validation message

                                                                                       OR

        ·              Any validation or invalid input error - returns HTTP – 400 Bad Request with validation message

        HTTP POST 400 BAD REQUEST
          
           HTTP – PUT (Resource Update)

        HTTP PUT Sequence Diagram
        HTTP PUT Sequence Diagram


        The above sequence diagram explain how the HTTP request is being processed and returns the right HTTP status code.

        There are the possible scenarios for processing of the HTTP PUT request.

        1.    Scenario:   Any validation or invalid input error - returns HTTP – 400 Bad Request with validation message
                   
        HTTP PUT 400 BAD REQUEST


        2.    Scenario:  If request resource is not available, return HTTP – 400 Bad Request – with message “Resource is not available

        HTTP PUT 400 BAD REQUEST

        In this scenario, if resource is not available, many architect prefer to create new resource and returns HTTP – 201 OK with newly created resource data

        HTTP PUT 201 OK
                
        3.    Scenario:  If request resource is available and successfully updated, Returns HTTP – 200 OK with updated Resource data
             

        HTTP PUT 200 OK


        HTTP – Patch (Partially Resource Update)


        HTTP PATCH Sequence Diagram
        HTTP PATCH Sequence Diagram

        The above sequence diagram explain how the HTTP request is being processed and returns the right HTTP status code.

        There are the possible scenarios for processing of the HTTP PATCH request.

        1.    Scenario : If request resource is available and successfully updated , Returns HTTP – 200 OK with updated Resource data

        HTTP PATCH 200 OK
                 

        2.    Scenario :  Any validation or invalid input error - returns HTTP – 400 Bad Request with validation message

        HTTP PATCH 400 BAD REQUEST
                                                                 
        3.    Scenario :  If request resource is not available, return HTTP – 400 Bad Request – with message “Resource is not available

                        
        HTTP PATCH 400 BAD REQUEST




        HTTP – DELETE (Delete Resource)

        HTTP DELETE Sequence Diagram
        HTTP DELETE Sequence Diagram

        The above sequence diagram explain how the HTTP request is being processed and returns the right HTTP status code.

        There are the possible scenarios for processing of the HTTP DELETE request.

        1.    Scenario : If request resource is available and successfully deleted, Returns HTTP – 200 OK 

        HTTP DELETE 200 OK


        2.     Scenario :  Any validation or invalid input error - returns HTTP – 400 Bad Request with validation message


        HTTP DELETE 400 BAD REQUEST

        3.    Scenario :  If request resource is not available, return HTTP – 400 Bad Request – with message “Resource is not available


        HTTP DELETE 400 BAD REQUEST


        Note: In some scenario, requested URI is not matching with any API URI., then by default Web API/IIS returns HTTP – 404 - with message “HTTP resource was found that matches the request URI”

        References:
         
        Thanks for Visiting!

        Choose Web API over WCF

        While designing the service layer for new application, this debate is always happened in my team.

                Are we going to choose Web API over WCF or going with WCF?

        Choosing right technology always contribute the major role of the success of application. If without understanding all possible factor and product requirement, you cherry-picked any technology, it could be a reason for application failure or performance issue and also it could limited the exposure of client.  



        Let back on our topic ‘Web API vs WCF’. there is no doubt, WCF provides a lots of feature and it is much more versatile in case of supporting to many transport protocols (HTTP, TCP, Named Pipes etc.) and can easily build secure, reliable and transaction enabled service and much more in messaging like two –way communication (duplex channel) .

        Web API if you need to build  a lightweight, restful service based HTTP protocol and it can leverage of the full feature of HTTP protocol like cache control, versioning etc and you want to expose your service to a broad range of client i.e. web browser, tables, mobile then web API always have advantage over WCF. WCF has very extensive configuration compare to web API and WEB API is very simple and light weight service and easily accessible in limited bandwidth device like smart phones and tablet. Web API supports any text format including XML so in performance, Web API is faster than WCF.

        WCF:

        WCF
        WCF

        ·         Should support special scenarios such as one way messaging, message queues, duplex communication etc.
        ·         Should support fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
        ·         Should be transaction enabled service or it will be called under other transaction scope.



        Web API:


        Web API
        WEB API

        ·         Should be restful service over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
        ·         Should be expose your service to a broad range of clients including browsers, mobiles, iPhone and tablets.

        Thanks for visiting !!


        The Basic Principles of Designing of Restful APIs

        This blog will covers the basic principles of designing of restful APIs and I will use ASP.NET Web API as example to elaborate the designing principles with proper practical example.
        In a day to day life, most of software developer creates Web API project and publish Web API as internal service for internal application or publish as external service to external clients.

        If developer follows these principles while designing the APIs it avoids common mistakes and helps to build the consistence, reliable and robust APIs. 

        ·         Use NOUNS and NOT the verbs
        ·         Use the HTTP Verbs
        ·         Use the Plurals
        ·         Use Query Parameters
        ·         Use the Proper HTTP Code
        ·         Versioning
        ·         Use Pagination Concept for Huge Data 

        Use NOUNS and NOT the verbs:

        It’s a very common mistake what develop make, they starts using verb in API URL and trying to explain the APIs functionalities by using the method name like GetAllProjects or CreateProject b but in Rest API, the HTTP Verbs can better describes the API instead of using method name in URI

        Eg.

        GET all Projects:

        API/GetAllProjects

        Or

        Create Project:

        API/CreateProject

        To avoid above common mistake, we need to use NOUNS instead of Verbs

        Eg.

        GET all Projects:

        HTTP GET API/Projects

        Create Project:

        HTTP POST API/Projects

        Use the HTTP Verbs

        HTTP verbs are known as method just like resource are nouns and HTTP verbs defined the type of operation of REST API

        HTTP Verb
        Semantic
        GET
        Retrieve a single resource or collection of resource 
        POST
        Create a new resource
        PUT
        Completely replace a resource
        PATCH
        Partially update a resource
        HEAD
        Retrieve only header information of response
        DELETE
        Delete the existing resource

        Use the Plurals

        Keep the resource URL name the plurals instead of singulars and if you are using singulars or plurals name convention, make consistence.

        API/Projects --------- plurals

        API/Project ---------- singulars, in case of get ALL project resources, it will be confusing

        Use Query Parameters
        Most of time, we need to filter the resource by passing ID or Code.

        Get Project Resource by Project ID

        HTTP GET API/Projects/1000

        Get Project Resource by Project Code

        HTTP GET API/Projects/Code/PJ1212

        In some scenario, we need to pass more than one filters so the query parameter should be used for Restful API designing.

        HTTP GET API/Projects?City=Houston&Type=IT

        Use the Proper HTTP Code

        While designing the restful API, we need to make sure that API should always return the right and consistence HTTP status Code and without consistent HTTP status codes, customers will not know the difference between success or failure without parsing the response body

        HTTP standard provides almost 70 HTTP status codes to describe the HTTP Response status and you can use below HTTP status code for restful API. 

        200 – OK
        204 – OK – No Content
        400 – Bad Request
        401 – Unauthorized
        500 – Internal Server Error
        503 – Service is not available 


        Versioning

        Versioning is very important feature of API and it is always advisable that publish API with version code so you can easily distinct between current version and previous version of API and it helps us to support backward compatibility and customer get time to transition from current version to next version.

        There are many ways to maintain the versioning of API by using API URI, Header or query parameters.

        HTTP GET:  API/v1/Projects

        HTTP GET:  API/v2/Projects

        Use Pagination Concept for Huge Data

        In case of API returns huge data, it is advisable to use pagination concept and display only allowable size of data.

        You can use PageSize and CurrentPage logic to implement pagination or limit & offset logic 

        HTTP GET:  API/v1/Projects?PageSize=25&CurrentPage=2

        OR

        HTTP GET:  API/v1/Projects?limit=25&offset =25

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