WebApi Tutorials

 

                                                         REST WebAPI

API:- API means a software code that helps two different software’s to communicate and exchange data with each other.

WebAPI:- Web API as the name suggests, is an API over the web which can be accessed using HTTP protocol.It is a concept and not a technology.

Asp.NET WebAPI:- ASP.NET Web API is a framework for building HTTP services that can be accessed from any client including browsers and mobile devices.It is an ideal platform for building RESTful applications on the.NET Framework.

The term API stands for ‘Application Programming Interface’. ASP.NET Web API is a framework for building Web API’s, i.e. HTTP based services on top of the .NET Framework. The most common use case for using Web API is for building RESTful services. These services can then be consumed by a broad range of clients like

1. Browsers

2. Mobile applications

3. Desktop applications

4. IOTs

What are IOTs

The term IOTs stands for Internet Of Things. Internet Of Things are the objects or devices that have an IP address and can communicate over the internet with other internet enabled devices and objects. Examples for IoT include security systems, electronic appliances, thermostats, cars etc..., in addition to desktops, laptops, and smart phones.

One important thing to keep in mind is that, though ASP.NET Web API framework is widely used to create RESTful services, it can also be used to create services that are not RESTful. In short, ASP.NET Web API framework does not dictate any specific architeture style for creating services. In this video, we will discuss creating RESTful services from scratch using ASP.NET Web API framework.

 

Restful WebAPI :- A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.


HttpRequest:-

C    ->  Create       ->        POST          ->  StatusCode   ->   return 201 (CREATED)

R    ->  Read         ->        GET             ->  StatusCode   ->   return 200 (OK)

U    ->  Update     ->        PUT             ->  StatusCode   ->   return 200 (OK)

D    ->  Delete      ->        DELETE       ->  StatusCode   ->   return 204 (NO CONTENT)

StatusCode   ->   return 400 (BadRequest)

StatusCode   ->   return 401 (Unauthorized)

StatusCode   ->   return 404 (NotFound)

StatusCode   ->   return 500 (InternalServerError)

StatusCode   ->   return 501 (NotImplemented)

StatusCode   ->   return 503 (ServiceUnavalialble)

 

[FormBody] vs [FormURI] in WebAPI:- You have seen that by default, ASP.NET Web API gets the value of a primitive parameter from the query string and a complex type parameter from the request body. But, what if we want to change this default behavior?

Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.

  //     An attribute that specifies that an action parameter comes only from the entity

  //     body of the incoming System.Net.Http.HttpRequestMessage.

     public sealed class FromBodyAttribute : ParameterBindingAttribute

    {

       public FromBodyAttribute(); 

       public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter);

    }

  //An attribute that specifies that an action parameter comes from the URI of the

 //incoming System.Net.Http.HttpRequestMessage.

namespace System.Web.Http

{  

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]

    public sealed class FromUriAttribute : ModelBinderAttribute

    {      

        public FromUriAttribute();      

        public override IEnumerable<ValueProviderFactory> GetValueProviderFactories(HttpConfiguration configuration);

    }

} 

Note:-  ModelBinderAttribute also inherited from ParameterBindingAttribute in webAPI.

  

IHttpActionResult vs HttpResponseMessage:- In Web API 1, we have HttpResponseMessage type that a controller action method returns. A new type called "IHttpActionResult" is introduced in Web API 2 that can be returned from a controller action method. Instead of returning HttpResponseMessage from a controller action, we can now return IHttpActionResult. There are 2 main advantages of using the IHttpActionResult interface.

· The code is cleaner and easier to read

· Unit testing controller action methods is much simpler. We will discuss, how easy it is to unit test a method that returns IHttpActionResult instead of HttpResponseMessage in a later video.

 Api Controller Return Type or IHttpActionResult Return Type

·         Ok

·         BadRequest()

·         Conflict()

·         Created()

·         CreatedAtRoute()

·         InternalServerError()

·         Redirect()

·        Unauthorized()

and many more click on Return type Ok() in ur program.

 

 Same Origin Policy:- Browsers allow a web page to make AJAX requests only with in the same domain. Browser security prevents a web page from making AJAX requests to another domain. This is called same origin policy.

There are 2 ways to solve this problem

 Using JSONP (JSON with Padding)

Install-Package WebApiContrib.Formatting.Jsonp

 

Enabling CORS (Cross Origin Resource Sharing)

Install-Package Microsoft.AspNet.WebApi.Cors

 Note:- Enable CORS (Cross Origin Resource Sharing) which allows cross domain ajax calls.

  

Media Type:-Media type (aka MIME type) specifies the format of the data as type/subtype e.g. text/html, text/xml, application/json, image/jpeg etc.

 In HTTP request, MIME type is specified in the request header using Accept and Content-Type attribute.

·  The Accept header attribute specifies the format of response data which the client expects.

·  Content-Type header attribute specifies the format of the data in the request body so that receiver can parse it into appropriate format.

  

An HTTP header is a field of an HTTP request or response that passes additional context and metadata about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.

·   The Accept header attribute specifies the format of response data which the client expects.

 

   GET /posts HTTP/1.1

   Accept:application/json

      GET /posts/42 HTTP/1.1

   Accept: application/xml

 

·Content-Type header attribute specifies the format of the data in the request body so that receiver can parse it into appropriate format.


      ContentType: application/x-www-form-urlencoded

      ContentType: application/multipart/form-data

 

Request Body:- Request Body contains the data to send to the server. For example, a POST request contains the data for the new item that you want to create. The data format may be in XML or JSON.

 

Response Body:- The Response Body contains the data sent as response from the server. For example, if the request is for a specific product, the response body includes product details either in XML or JSON format.

 

Response Status codes:- These are the HTTP status codes, that give the client details on the status of the request. Some of the common status codes are 200/OK, 404/Not Found, 204/No Content. For the complete list of HTTP status codes and what they mean, please visit

 

Web APi Hosting:-

·         IIS Hosting like mvc application

·         Self Hosting

·         In memory hosting.

  

Content Negotiation:- One of the standards of the RESTful service is that, the client should have the ability to decide in which format they want the response - XML, JSON etc. A request that is sent to the server includes an Accept header. Using the Accept header the client can specify the format for the response. For example

Accept: application/xml returns XML

Accept: application/json returns JSON

Depending on the Accept header value in the request, the server sends the response. This is called Content Negotiation.

 

Media type formatters :-  The Media type formatters are the classes that are responsible for serializing the request/response data so that the Web API Framework can understand the request data format and also send data in the format which the client expects.

MediaTypeFormatter is an abstract class from which JsonMediaTypeFormatter and XmlMediaTypeFormatter classes inherit from. JsonMediaTypeFormatter handles JSON and XmlMediaTypeFormatter handles XML.


Web API versioning :- Once a Web API service is made public, different client applications start using your Web API services. As the business grows and requirements change, we may have to change the services as well, but the changes to the services should be done in way that does not break any existing client applications. This is when Web API versioning helps. We keep the existing services as is, so we are not breaking the existing client applications, and develop a new version of the service that new client applications can start using.

 Different options available to version Web API services : Versioning can be implemented using

1. URI's

2. Query String

3. Version Header

4. Accept Header

5. Media Type

 

 

No comments:

Post a Comment