Asp.net Web API and google chrome’s Postman plugin

Posted on May 13, 2012 | Category :ASP.NET 4.5, MVC 4 | 9 Comments
Be a fan

MS introduced Asp.net web api with Visual studio 11 (Consumer preview, you can download from here), Its a good framework to create REST api, very clean and maintainable. I have created a sample project for learning purpose and I used Google chrome’s Postman plugin it is good plugin to consume REST services. You can add from here.

1. Open Visual Studio 11 create new project using “ASP.NET MVC 4 Web Application” and Click on OK button


MVC4 Project



2. Select “Web API” from Project template dialog box


ASP.NET Web Api



3. Solution will be ready in few seconds and its look like


Asp.net web api project



4. Open global.asax file and check “RegisterRoutes” method, in this by default “MapHttpRoute” (MapHttpRoute is responsible for routing of web api controller) map to “api/{controller}/{id}” means Web api controllers accessing through “api/{controller}/{id}” path you can change it according to your requirement.

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }




5. Now create a Employee class with following definition in Model

namespace SampleWebApi.Models
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}




6. And Create following EmployeeModel. In this model I have created Add, UpdateEmploayee, DeleteEmployee, GetEmployees and and GetEmployee methods and for data storage I have used a static List, it store data unless App recycle. You can use database for storage. I have used static List for just showing example.

using System.Collections.Generic;
using System.Linq;

namespace SampleWebApi.Models
{
    public class EmployeeModel
    {

        public static List<Employee> _employees =new List<Employee>();

        public void Add(Employee employee)
        {
            //for getting next ID
            if (_employees.Count > 0)
            {
                employee.ID = _employees.Max(emp => emp.ID) + 1;
            }
            else
            {
                employee.ID = 1;
            }

            //add to _employee
            _employees.Add(employee);
        }

        public List<Employee> GetEmployees()
        {
            return _employees;
        }

        public Employee GetEmployee(int id)
        {
            return _employees.Where(employee => employee.ID == id).FirstOrDefault();
        }

        public int UpdateEmployee(int id, Employee employee)
        {
            var updatableemployee = _employees.Where(emp => emp.ID == id).FirstOrDefault();

            if (updatableemployee != null)
            {
                updatableemployee.Department = employee.Department;
                updatableemployee.Name = employee.Name;
                return updatableemployee.ID;
            }
            else
            {
                return 0;
            }
        }

        public bool DeleteEmployee(int id)
        {
            return _employees.Remove(_employees.Where(emp => emp.ID == id).FirstOrDefault());
        }
    }
}




7. And Following EmployeesController. In following code you are seeing that EmployeesController inherit ApiController and ApiController class is base class of web api controller. Mapping of HTTP methods and api controller’s methods is


GET ==> Get (used for getting resources)

POST ==> Post (used for Adding resource)

DELETE => Delete (used for deleting resource)

PUT ==> Put (used for Updating resource)

using System.Collections.Generic;
using System.Web.Http;
using SampleWebApi.Models;

namespace SampleWebApi.Controllers
{
    public class EmployeesController : ApiController
    {
        EmployeeModel employeemodel = new EmployeeModel();

        // GET /api/employees
        public IEnumerable<Employee> Get()
        {
            return employeemodel.GetEmployees();
        }

        // GET /api/employees/5
        public Employee Get(int id)
        {
            return employeemodel.GetEmployee(id);
        }

        // POST /api/employees
        public void Post(string name, string department)
        {
            Employee employee = new Employee();
            employee.Name = name;
            employee.Department = department;
            employeemodel.Add(employee);
        }

        // PUT /api/employees/5
        public void Put(int id, Employee employee)
        {
            employeemodel.UpdateEmployee(id, employee);
        }

        // DELETE /api/employees/5
        public void Delete(int id)
        {
            employeemodel.DeleteEmployee(id);
        }
    }
}




8. Run this project and open Google chrome’s postman plugin, in this we option to Enter Url, HTTP request type, Request Headers, Form collection, Url parameter etc, so it is very easy to test Web api with Postman plugin.


Google Chrome PostMman Plugin



9. Now I am consuming these requests through Google chrome’s postman plugin. It can used just for testing and debugging the web api’s before implementing.


1. HTTP POST : First I am adding some record to the data store, for I need to call HTTP POST request of web api endpoint.

for calling HTTP POST follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select ‘POST’ from drop down.

3. Select form type is “x-www-form-urlencoded”.

4. Add two key “name” and “department” and their values.

5. Click on “Send” button.

6. After few milliseconds api will respond, this request add a record.

I added two records for example following above steps again.


example http post request in postman plugin



2. HTTP GET : For getting Employees list I need to call HTTP post of web api endpoint

for calling HTTP GET follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select “GET” from drop down.

3. 5. Click on “Send” button.

6. After few milliseconds api will respond. It returns json array in response, you can see in following image.


example http get request in postman plugin

If you want to get specific Employee then use specific ID like

http://localhost:2411/api/employees/2

Response of this request is

{
     "Department" : "MBA",
     "ID" : 2,
     "Name" : "Ashok Bishnoi"
}



3. HTTP PUT : For updatting I need to call HTTP PUT request of web api endpoint.

for calling HTTP PUT follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Add a employee at end of endpoint(http://localhost:2411/api/employees/) , I am updating employee of ID 2, so endpoint looks like http://localhost:2411/api/employees/2

3. Select ‘PUT’ from drop down.

4. Select form type is “x-www-form-urlencoded”.

5. Add two key “name” and “department” and their values.

6. Click on “Send” button.

7. After few milliseconds api will respond, this request update the record with ID 2. In my example just “1″ you can manipulate it.


http post using postman plugin

You can check updated records using HTTP GET request.



4. HTTP DELETE : For deleting record I need to call HTTP DELETE request of web api endpoint

for calling HTTP DELETE follow these steps

1. Input endpoint, my endpoint is http://localhost:2411/api/employees/.

2. Select ‘DELETE’ from drop down.

3. Select form type is “x-www-form-urlencoded”.

4. Add one key “id” and its value, I am deleting record with ID 2.

5. Click on “Send” button.

6. After few milliseconds api will respond, this request delete the record with ID 2.


http delete request using postman plugin

You can check deleted record using HTTP GET request.


Be a fan
» Tags: , , , , ,

Comments 8

  1. 12/05/14

    Hello! I’ve been reading your web website for a whilst now and finally got the courage to go ahead and give you a shout out from Kingwood Texas! Just wanted to say keep up the great work! 514707

  2. ashok Reply
    12/05/18

    hello sir
    i have read the full article ! its amazing tutorial !

  3. 12/06/14

    Hi Govind,
    this is really very nice article dude. keep up the good work.

  4. 12/06/14

    Great article!!! We have been using Chrome’s “Advanced Rest Client Application” so far. Maybe we should switch to Postman? What do you think?

  5. 12/06/21

    Great tool, best one so far! Thanks for sharing, this saved my day.

  6. chhatrapati Reply
    12/06/26

    it’s awesome dude

  7. Dave Reply
    12/08/19

    Hey,

    Great tutorial. Postman has become my preferred tool for quickly testing out Web APIs. Just a quick question or you though, have you tried performing a POST with an object that uses a Timestamp? I can’t seem to get it to work…

    Here’s the GET result in JSON:
    {
    “ID”: 5,
    “Name”: “New Product”,
    “Timestamp”: “AAAAAAAAJxE=”
    }

    But if I try and PUT this back, it doesn’t seem to send the timestamp properly.

    Anyways, just wondering…

    Dave

  8. Muhammad Nauman Khan Reply
    14/08/06

    its awsme..thank you so much …!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Pingbacks 1

comment from Muhammad Nauman Khan August 6, 2014