Saturday, January 6, 2018

Web API (Part 1)

What is Web API?

A framework for building HTTP Services that can be accessed from any client including browsers and mobile devices. Web Api provides an ideal platform for building RESTful applications using the .NET framework.

  • Supports only HTTP protocol.
  • Built on top of .net framework and supports asp.net request\response pipeline.
  • Web API response supports different formats like JSON, XML, BSON (binary JSON).
  • Web API can be hosted on IIS, Self Hosting and other web servers that supports .net 4.0+
  • Supports HTTP verbs (GET, PUT, POST, DELETE) and maps these verbs to web api method names


If we had RESTFul services then Why Web API?

  • In order to create and use RESTful services, one needs to configure and enable webHttpBindings.
  • While in case of Web API, configuration is done by using code only. WebApiConfig.cs class registers routs using HttpConfiguration object where we can define routing using name, routeTemplate (defines URI) and defaults params.
    • Global.asax.cs Application_Start event invokes WebApiConfig.Register(GlobalConfiguration.Configuration) method.
  • RESTful services supports HttpGet and POST verbs by [WebGet] and [WebInvoke] respectively. And to use other verbs (PUT and DELETE) one has to configure in IIS or .svc file to accept those requests.
  • In Web API, method names indicates which Http verb is to be invoked. such as for HttGet request, just name your method as Get() or prefix the method name with GET (not case sensitive). In case you have not specified Get in the method name prefix, you can decorate the method with [HttpGet] attribute. similarly for other verbs.
  • Passing data through parameters using WebGet requires configuration. UriTemplate must be specified.

Creating a sample web api project:

Prerequisites:
  • If you are using .Net framework 3.5, you need to make sure that you have ASP.net MVC 4 installed. 
  •  File - New Project - ASP.NET MVC 4 Web Application
  •  After giving an appropriate name to your application, click OK. Select Web API template and go with Razor view engine.
  • We need only App_Start and Controllers folder for now.
         

  •  We have ValuesController inside controllers folder and WebApiConfig.cs file in App_Start foledr as below:
        

  • The content of Global.asax.cs file is as below. Please note that we do not need the commented code for now.
       
  • Let's have a look on WebApiConfig.cs class content to better understand the code.
  •  Walking through Controller i.e. ValuesController.cs
    •  Please note that we have the default controller as we created web api. Inside this controller, we have a list of languages containg three programmng languages and a few methods supported by HttpVerbs Get, Put, Post and Delete.
 

  • Note that these methods are prefixed with or named as the above four Http verbs. 
  • Next step is to test the web api.

 Testing Web API methods:

  •  Testing Get methods:
    • Let's build and run our application.
    • you will get a we page opened with an url something like this:
      • http://localhost:32730/
    • Now, as we have mentioned the routeTemplate value in WebApiConfig.cs file as 
      • routeTemplate: "api/{controller}/{id}". 
    • We would need to append api/our controller name/parameter value to test our Get methods as below:
      • http://localhost:32730/api/Values - for first Get method.
      • http://localhost:32730/api/Values/1 - for second Get method.
  •  Get methods result
 
 
Exploring the Get methods and changing response.

  • Let's modify the Get method to return HttpResponseMessage as below:
   
 
     
  •  We can change the name of Get method and then we have to decorate the method with [HttpGet] verb as below: System.Web.Http.GetHttpAttribute sealed class has this attribute.
                  
  •  Add Model and return HttpMessageResponse of model type.
    • Inside Models folder, add a new class as Products.cs
                
    •  The model class looks like below:
                      

    •   Now, we can modify the Get method as below:
    • Points to remember here are we can create the response of any type and return with the HttpStatusCode. By default the HttpStatusCode of a web api response is OK i.e. 200.
                   

 Testing POST, PUT and DELETE Methods:

  • In order to test the other methods than Get, we need a web debugger tool such as Fiddler or Postman.
    • In this tutorial, we are going to use Fiddler web debugger tool.
    • We can test Get methods as well using this tool.
    • To use fiddler, lets have a look at the tool first.
 
    • In the Composer tab, in the left-most dropdown, we have the options for all HttpVerbs to be used.
    • Next to that, there is a textbox which accepts the URL. Here we can enter our web api url to test post, put and delete methods.
    • Below there is a section named Request Body, from where we can pass the parameters to the web api methods. The [FromBody] attribute takes the input from this request body section.
  •  POST method:
    • Select verb as POST, pass Content-Type as application/json. And in RequestBody, supply the parameter which are to be accepted by [FromBody] in method parameter.
                   
                 
                 
    • Method signature looks like below.
                
    • In Fiddler, go to Inspectors or simply click on the left most side pane containing the result 
                 
  •  [FromUri] attribute:
    • We can replace [FromBody] attribute in method signature with [FromUri] and below will be the process to achieve the result.
                   
      • In fiddler request Url, change the url value to -
      • http://localhost:32730/api/Values?value=java  
        • Please make a note that the query string has the value to be posted. 

  •  PUT and DELETE
    • Similarly, by changing the Url as matched in method signature, we can test put and delete methods as well
                

                  

Note: In case of your method doesn't have any return type (void), the inspectors tab will show the response code as 204. in order to get 200 (OK), you will need to return something from your method.


Thanks for reading. Will post Web API Part 2 with a few more details.

No comments:

Post a Comment

SQL INTERVIEW QUESTIONS (SCENARIO BASED) - Part 1

FINDING Second Highest Salary in SQL CREATE TABLE #EMP ( NAME NVARCHAR ( 100 ), SALARY BIGINT ) INSERT INTO #EMP VALUES (...