In the recent past I am fortunate to get my hands on to new technology ASP.Net Web API. I was fascinated to hear ASP.Net Web API’s definition from MSDN as follows – “ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.”. For folks like me who enjoyed working with traditional XML Web Services to WCF Services, ASP.Net Web API is a huge bonus in terms of lightweight, MVC coding standards, No huge configuration settings and finally fantastic routing. Apart from afore said reasons, there are many others like having own media formatters to serve different MIME types, custom exception and action filters, flexible tracing etc. On top of every sensible reason, ASP.Net Web API is easy to code and use.
In this short tutorial, I am going to show how to build a simple ASP.Net Web API and test it using Fiddler (a powerful web debugger which logs all traffic between computer and internet).
First lets get started by creating a ASP.Net MVC 4 Project in Visual Studio 2010, and select WebAPI template. Right Click Models folder and add a new class called Product. Add the following code to it.
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BasicWebAPI1.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } } }
Right click Controllers folder and create a new controller called Products. Add the following code to it.
using BasicWebAPI1.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; namespace BasicWebAPI1.Controllers { public class ProductsController : ApiController { private static List<Product> _products = new List<Product>() { new Product() { Id = 1, Name = "Honda Civic", Description = "Luxury Model 2013" }, new Product() { Id = 2, Name = "Honda Accord", Description = "Deluxe Model 2012" }, new Product() { Id = 3, Name = "BMW V6", Description = "V6 Engine Luxury 2013" }, new Product() { Id = 4, Name = "Audi A8", Description = "V8 Engine 2013" }, new Product() { Id = 5, Name = "Mercedes M3", Description = "Basic Model 2013" } }; public ProductsController() { } [HttpGet] public IEnumerable<Product> GetProducts() { return _products; } [HttpGet] public Product GetProduct(int id) { Product pro = _products.Find(p => p.Id == id); if (pro == null) throw new HttpResponseException(HttpStatusCode.NotFound); else return pro; } [HttpGet] public IEnumerable<Product> GetProductsBySearch(string search) { var products = _products.Where(p => p.Description.Contains(search)); if (products.ToList().Count > 0) return products; else throw new HttpResponseException(HttpStatusCode.BadRequest); } [HttpPost] public HttpResponseMessage PostProduct(Product p) { if (p == null) return new HttpResponseMessage(HttpStatusCode.BadRequest); _products.Add(p); return new HttpResponseMessage(HttpStatusCode.Created); } [HttpDelete] public IEnumerable<Product> DeleteProduct(int id) { Product pro = _products.Find(p => p.Id == id); _products.Remove(pro); return _products; } [HttpPut] public HttpResponseMessage PutProduct(Product p) { Product pro = _products.Find(pr => pr.Id == p.Id); if (pro == null) return new HttpResponseMessage(HttpStatusCode.NotFound); pro.Id = p.Id; pro.Name = p.Name; pro.Description = p.Description; return new HttpResponseMessage(HttpStatusCode.OK); } } }
Lets us use the default route provided by framework as of now. It is located in WebApiConfig.cs in App_Start folder –
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace BasicWebAPI1 { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
Lets run the project by clicking F5. In the mean time download latest fiddler tool. Run your fiddler to test our Web API. Open fiddler and navigate to Composer tab. In composer tab, you can compose your request and send it to server.
For a default GET request, Please check below request in fiddler –
When you execute the query, you get following response. Response can be viewed in Inspectors tab in fiddler.
Now lets get a single product, so change your composed query as shown below –
Result as shown below (check in Inspectors tab of fiddler) –
Now lets post a product (create a product) –
Result of created product, it returns a 201 created status code. IMP: Remember the code plumbing we have for this tutorial is very basic. You might need to put more validation and exception handling logic in place. Also when ever a item has been added to the repository it is a good practice to return the newly created item URL for further usage on the caller.
Lets update the newly created product (make a PUT operation) –
Response is a Http 200 code, which is OK –
Delete operation can be performed as below. In the request, I mentioned to delete product with ID: 7. And the Web API needs to perform delete operation and need to send me back all the remaining products.
Response are shown below –
The final action we are going to perform is search. We search products by their description and return products which matches the keyword. Request construction is going to use QueryString and as is shown below –
Response is as follows –
A lot more can be accomplished using ASP.Net Web API, but to make this tutorial simple and easy we went very basic. My next set of tutorials would drill down more in depth concepts of Web API. Stay tuned.