Testing ASP.Net Web API–GET, POST, PUT, DELETE using Fiddler

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 –

WebAPI1

When you execute the query, you get following response. Response can be viewed in Inspectors tab in fiddler.

WebAPI2

 

Now lets get a single product, so change your composed query as shown below –

WebAPI3

Result as shown below (check in Inspectors tab of fiddler) –

WebAPI4

Now lets post a product (create a product) –

WebAPI5

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.

WebAPI6

Lets update the newly created product (make a PUT operation) –

WebAPI7

Response is a Http 200 code, which is OK –

WebAPI8

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.

WebAPI9

Response are shown below –

WebAPI10

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 –

WebAPI11

Response is as follows –

WebAPI12

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.

You may also like...

  • Mohammad

    Very nice article, nice to see fiddler being used in asp.net development.

  • Saurabh Nijhawan

    Good one!

  • Jitender Singh

    Very Useful article, Thanks

  • Bartho

    Very Helpful. Thanks!

  • Jay

    Very nice. Simple, Crisp and Clear! Thanks.

  • Aurimas

    Good introductionary article, but why not write unit/integration tests from the start. People shouldn’t follow bad practices. This is one of them.

  • RamiVemula

    @Aurimas, agreed but cannot afford for small tutorials.

  • Raj Ubendran

    Simple but bank on explaining the concept very well.

  • Rakibul

    I do the task.But when i post data from fiddler using the JSON you write in Request Body then execute the command.but in ProductsController the PostProduct(Product p) function get p as NULL value of Product type. Why it causes ?

  • RamiVemula

    @Rakibul – Please check the names of the properties in your Model.

  • john

    Did everyone get the examples to work with Fiddler? I got Get to work and return the 5 records in JSON. but can’t get any of the other functions to return anything.

  • ramiramilu

    John, all the code samples are thoroughly tested, please ensure you replicate the code exactly as described in the tutorial.

  • Ramesh Bas

    POST http://localhost:49568/JsonDemo/UpdateUsersDetail HTTP/1.1

    Host: localhost:49568

    Content-Type: application/x-www-form-urlencoded; charset=UTF-8

    Accept-Encoding: gzip, deflate

    usersJson=[{ “id”:1, “UserName”:”ramesh”, “Company”: “My company”},{ “id”:2, “UserName”:”suresh” “Company”: “My company”}]}

  • ramiramilu

    @Ramesh, So what was your question?

  • Ramesh Bas

    posting from Fiddler.Lot of people had problems in POST. coming as empty in API

  • ramiramilu

    your content-type should be application/json. Have you followed the tutorial exactly the same way?