Web Api
Web Api
1 Introduction
As I am an ASP.NET developer I have been working in ASP.NET Web Forms, ASP.NET MVC, and Web
Services etc. Today in this article I will try to demonstrate ASP.NET Web API into simpler terms that would
indeed be easy to understand and implement them practically. If you love to watch and learn my honest
suggestion would go and watch below series of Web API and be API Developer as well.
https://www.youtube.com/watch?v=cBpHqLukHp4
I wont make any false assumptions for any technology. But as I have been working with Web Services and Web
API. I can certainly found Web API to be much simpler, robust in all scenarios. Most of you would think why I am
talking about Web Services when we have WCF. Yeah you are correct, as I dont have in depth knowledge of WCF
so I wont comment on that. I would be happy if as a reader you dig into the open web and find the benefits of Web
API over WCF as well. So lets get started starting with definition of ASP.NET Web API.
ASP.NET Web API is a HTTP services which follows HTTP REST protocols that can reach
broad range of clients i.e. Browser, mobile, tablets
Scott Hanselman: Principal Program Manager - Community Architect - Web Platform and Tools Microsoft.
HTTP request starts with a first line containing HTTP verbs (HTTP defined methods
are called HTTP verbs) URL and HTTP Version. The HTTP header is a name-value field
separated by a colon (:) and blank space called Payload.
POST http://localhost:51180/api/TodoItems HTTP/1.1 HTTP Verbs
content-type: application/json --Headers
Host: localhost:51180 Headers
--Payload
{
Title:"Saillesh"
}
HTTP Response starts with Status Code and its corresponding description and
subsequently headers each line as shown below: The HTTP header is a name-value
field separated by a colon (:) and blank space called Payload.
HTTP/1.1 201 Created
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Location: http://localhost:51180/api/TodoItems/2
Server: Microsoft-IIS/10.0
--Payload
{"TodoItemId":2,"Title":"Saillesh","IsDone":false}
{
Title:"Saillesh"
}
DELETE
DELETE Verb is used to delete resource from the server.
DELETE http://localhost:51180/api/TodoItems/3
content-type: application/json
Host: localhost:51180
If a request is send to the server without any accept header and with a
content type in headers. Than Conneg algorithm will choose Content type
header to decide about Response media type to respond.
If a request is send with an Accept Header, Conneg algorithm will use the
Accept Header information to decide the Response media type to send the
response.
If client give us content type as application/json and accept-header:
application/xml than conneg algorithm will use content type to serialize the
input and accept header to decide the response media type formatter to
write.
If somehow conneg algo. Is not able to find the best fit media type formatter
to be send in the Accept Header, than its uses the best effort approach and
uses the content-type header to decide the response media type formatter to
write.
If in worst scenario if conneg algorithm is not able to find the correct
response for the request, it uses the first media type formatter in collection
i.e. application/json.
ASP.NET WEB API uses MVC architecture which means Model, View, and Controller. To learn about MVC
architecture my honest suggestion for you is to watch the below video and clear your concepts of ASP.NET MVC.
https://www.youtube.com/watch?v=-c1sI8666Ac
In MVC our MODEL is our C# class, Controller is also an object which handles the client request and get the
required model applies the logic with business class and send the data integrated with html to the client in the form
of view.
https://www.youtube.com/watch?v=b6vTIiBNcJ0
Adding a Model
Adding a Controller
Note* I wont be implementing dependency injection and other design patterns. In Enterprise application our
model, API, interface and dal has to be in separate class libraries.
Now lets set up our DAL Class which will communicate with Database. I will be using EF code first
approach with existing db table
Script for creating table:
CREATE TABLE [dbo].[Customer](
[Id] [int] NOT NULL identity(1,1),
[Name] [varchar](50) NOT NULL,
}
}
Figure16: Select your server name and enter your database name click ok.
4.PUT
public HttpResponseMessage Put(int id, [FromBody]Customer Cust)
{
if (!ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
}
if (id != Cust.Id)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
_context.Entry(Cust).State = EntityState.Modified;
try
{
_context.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
throw;
return Request.CreateResponse(HttpStatusCode.NoContent);
}
4. Delete
public HttpResponseMessage DeleteCustomer(int id)
{
//retrieve the customer first
Customer customer = _context.customers.Find(id);
//if customer object is null
if (customer== null)
{
//return HttpStatusCode.NotFound response
Request.CreateResponse(HttpStatusCode.NotFound, "No records found");
}
//remove from the table
_context.customers.Remove(customer);
//save changes in database
_context.SaveChanges();
//return response 200
return Request.CreateResponse(HttpStatusCode.OK);
Thats it we have our working ASP.NET WebApi. Each Controller HTTP method has their
corresponding URI. In ASP.NET Web API we use host/API/ControllerName which quiet differ from
normal ASP.NET MVC routes. In ASP.NET Web API project we have WebApiConfig class for Web API
routes
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
We can see api/controller is the key here. Reason why using api in the routes is to avoid
collision with ASP.NET MVC routing.
ControllerMethod
POST
Get
Get(int Id)
Put
DeleteCustomer
URI
API/POST
API/GET
API/GET/ID
API/GET/ID
API/DELETE/ID
POSTMAN Provide us autocomplete features by which we can easily enter the required details.
Once we are done with headers our POSTMAN window will look like this as shown below:
Figure25: Request body with properties names and value to be binded to object.
Wow we are ready fire our first HTTP verb POST just click on Send. Put a break point using f9 in
your POST method.
POST:
Figure26: Break Point hits and we can see the passed json details are de-serialized to the customer object.
If the model state is valid it will perform the adding of the customer.
GET:
Once the whole statements are executed we will get below json response:
{
"Id": 1,
"Name": "Saillesh",
"Mobile": "1234567890"
}
Headers:
PUT:
204 No Content
The server has recognized the request and has successfully processed but doesnt
need to return an entity body.
Let check the output in DB.
DELETE:
Acknowledgements
We found how easy its is to create REST based services using ASP.NET web API. Wow we have finally created a
simple ASP.NET Web API give yourself high 5 from my side. Theres lot more to learn in ASP.NET web API stay
tuned for more ASP.NET web API. The source code has been upload to Git Hub Repository. Feel free to download
and test.
https://github.com/SailleshPawar/ASP.NET-WEB-API-DEMO/
References:
http://www.asp.net/web-api
Pro ASP.NET Web API by Tugberk Ugurlu (Author), Alexander Zeitler (Author), Ali
Kheyrollahi (Author)
https://www.w3.org/Protocols/Specs.html
https://www.w3.org/Protocols/rfc2616/rfc2616.html