Home
 
  

Asp.net Web API and google chromes Postman plugin

April 20, 2014

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 chromes 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
  1. Select Web API from Project template dialog box
  1. 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 }
);
}
  1. 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; }
}
}
  1. 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());
}
}
}
  1. 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 controllers 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);
}
}
}
  1. Run this project and open Google chromes 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.
  1. Now I am consuming these requests through Google chromes postman plugin. It can used just for testing and debugging the web apis before implementing.
  2. 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.

  1. 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.
    1. Click on Send button.
  3. After few milliseconds api will respond. It returns json array in response, you can see in following image.

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"
}
  1. 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/](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.

You can check updated records using HTTP GET request.

  1. 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.

You can check deleted record using HTTP GET request.

Govind Malviya

Govind Malviya

Director of Product Development @LoginRadius

 

© 2020