WebApi

 WEBAPI

The term API stands for ‘Application Programming Interface’. In the world of web development the term ‘API’ is synonymous with online web services which client apps can use to retrieve and update data. These online services have had several names/formats over the years such as SOAP, however the current popular choice is to create a REST (or RESTful) API.
.Net’s Web API is an easy way to implement a RESTful web service using all of the goodness that the .net framework provides. Once you understand the basic principles of REST, then a .net Web API will be very easy to implement.
Web API is built on .net’s modular, pluggable pipeline model. This means that when a server hosting a web API receives a request, it passes through .nets request pipeline first. This enables you to easily add your own modules if you find that the default capabilities are not enough for your needs. With the recent announcements on ASP.net vNext this also means you can potentially host your Web API outside of Windows Server which opens up a whole range of usage cases. See https://www.asp.net/vnext for detail.
Web API uses the Controller and Action concepts from MVC so if you already understand .net MVC you are in a good place. If you don’t, then Web API is a great way to learn MVC.
Web API in .net is the way you write REST APIs services in .net. Web API gives you all the benefits of the .net framework and deals with a lot of the complexities of content negotiation, model binding etc that you’d have to deal with yourself without Web API

Web API Features

01.It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE.
02.Responses have an Accept header and HTTP status code.
03.Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
04.It may accepts and generates the content which may not be object oriented like images, PDF files etc.
05.It has automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
06.It can be hosted with in the applicaion or on IIS.
07.It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.
Why to choose Web API ?
01.If we need a Web Service and don’t need SOAP, then ASP.Net Web API is best choice.
02.It is Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.
03.It doesn't have tedious and extensive configuration like WCF REST service.
04.Simple service creation with Web API. With WCF REST Services, service creation is difficult.
05.It is only based on HTTP and easy to define, expose and consume in a REST-ful way.
06.It is light weight architecture and good for devices which have limited bandwidth like smart phones.
07.It is open source.

 

 

Lets develope a simple and quick example so that you can see how it Works :

 

FIRST :

  1. Create an Asp.net Web proyect solution.
  2. check "webApi" and select Empty proyect.

api1 api3 api2

 

  • as you can see down below  if you go to App:Start folder  there is the  route maps to call webapi api/{controller}/{id}"  you can choose as you prefer that:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web.Http;

namespace webapi

{

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 }

);

}

}

}

 

  •  Let us créate a new class for creating an Object called "carro".

api4

  • here  the content :

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace webapi.Models

{

public class Carro

{

public int idcarro { get; set; }

public string marca { get; set; }

public int modelo { get; set; }

 

}

}

 

 

 

  • Let us create the controller class and implement this  carro object on there:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using webapi.Models;

namespace webapi.Controllers

{

public class CarroController : ApiController

{

Carro[] carros = new Carro[] {

new Carro {idcarro=1,marca="fiat",modelo=1984 },

new Carro { idcarro = 1, marca = "audi", modelo = 1984 },

new Carro { idcarro = 2, marca = "VW", modelo = 1984 },

new Carro { idcarro = 3, marca = "peugeot", modelo = 1984 },

new Carro { idcarro = 4, marca = "renault", modelo = 1984 },

};

public IEnumerable<Carro> GetAllCarro() {

return carros;

}

public IHttpActionResult GetCarro(int id )

{

var carro = carros.FirstOrDefault((a) => a.idcarro == id);

if (carro != null)

{

return Ok(carro);

}

else

{

return NotFound();

}

}

}

}

 

  • As well as you can see  in this example you will retrieve all the content of the object carro and also you will be able to call by id (specific Brand).

https://localhost:33480/api/carro/

 

<ArrayOfCarro><Carro><idcarro>1</idcarro><marca>fiat</marca><modelo>1984</modelo></Carro><Carro><idcarro>1</idcarro><marca>audi</marca><modelo>1984</modelo></Carro><Carro><idcarro>2</idcarro><marca>VW</marca><modelo>1984</modelo></Carro><Carro><idcarro>3</idcarro><marca>peugeot</marca><modelo>1984</modelo></Carro><Carro><idcarro>4</idcarro><marca>renault</marca><modelo>1984</modelo></Carro></ArrayOfCarr

 

 

  • if you want to get only one carro just place the id :

https://localhost:33480/api/carro/2

and this will bring you

<Carro><idcarro>2</idcarro><marca>VW</marca><modelo>1984</modelo></Carro>

 

 

 

  • Now from the front-end side you can develop a look and feel  as you prefer . Here I leave you a quick view done with jquery :

just  add a new HTML page ítem to your proyect and type the following  Js code:

 

<!DOCTYPE html>

<html xmlns="https://www.w3.org/1999/xhtml">

<head>

<title>Carros dansau WebApi</title>

<meta charset="utf-8" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

 </head>

<body>

<div>

<h2>Carros Dansau</h2>

<ul id="Carros"/>

</div>

<div>

<h2>Buscar por su ID</h2>

<input type="text" id="carId" size="7"/>

<input type="button" value="Buscar" onclick="find();" />

<p id="carro"></p>

</div>

 

<script>

var uri = 'api/carro';

$(document).ready(function () {

/// send an AJAX request

jQuery.getJSON(uri)

.done(function (data) {

$.each(data, function (key, item) {

$('<li>', { text: formatItem(item) }).appendTo($('#carros'));

});

});

});

function formatItem(item) {

return item.idcarro + '-' + item.marca + '-' + item.modelo;

}

function find() {

var id = $('#carId').val();

$.getJSON(uri + '/' + id, function (data) {

$.each(data, function (key, item) {

$('#carro').text(formatItem(data));

});

});

///another way

//jQuery.getJSON(uri + '/' + id)

//.done(function (data) {

// $('#carro').text(formatItem(data));

//})

//.fail(function (jqXHR, textStatus, err) {

// $('#carro').text('Error: ' + err);

//});

}

</script>

</body>

</html>

 


From  Shailendra Chauhan  here  helped me with some definitions on this post.

For a Deep understanding please go here : https://msdn.microsoft.com/en-us/library/dn448365(v=vs.118).aspx

hope this can be of useful to you. Thanks :)