Performing CURD operations using Web API

August 31, 2013 by Anuraj

.Net ASP.Net Web API

This post is about creating a HTTP service for CRUD operations using ASP.Net Web API. CRUD stands for “Create, Read, Update, and Delete,” which are the four basic database operations. Many HTTP services also model CRUD operations through REST or REST-like APIs. For this post I am using simple Employee model class.

public class Employee
{
	public int Id { get; set; }
	public string Name { get; set; }
	public string Email { get; set; }
	public string Phone { get; set; }
}

For communicating to Database, I am using Entity Framework. And here is the EF DbContext class.

public class DataContext : DbContext
{
	public DbSet<Employee> Employees { get; set; }
}

The employee api exposes following methods

ActionHTTP methodURL
Get all EmployeesGET/api/Employee
Get an Employee by IdGET/api/Employee/{Id}
Create new EmployeePOST/api/Employee
Update an existing EmployeePUT/api/Employee/{Id}
Delete an EmployeeDELETE/api/Employee/{Id}

And here is the implementation.

This method will return all the employees.

public IEnumerable<Employee> Get()
{
    using (DataContext dataContext = new DataContext())
    {
        return dataContext.Employees.ToList();
    }
}

You can use browser or curl to verify this. Here is the curl request to invoke the Get method.

curl -i -H "Accept: application/json" http://localhost:56103/api/employee

And here is the response.

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcYW51cmFqXGRvY3VtZW50c1x2aXN1YWwgc3R1Z
GlvIDIwMTJcUHJvamVjdHNcV2ViQVBJSGVsbG9Xb3JsZFxXZWJBUElIZWxsb1dvcmxkXGFwaVxlbXBsb3llZQ==?=
X-Powered-By: ASP.NET
Date: Sun, 01 Sep 2013 06:05:18 GMT
Content-Length: 89

[{"Id":1,"Name":"Employee1","Email":"employee1@dotnetthoughts.net","Phone":"0013456732"}]

For Get a specific employee, use Get() method with an parameter int id. As it is GET request, you need to pass the Employee Id as the query string.

public Employee Get(int id)
{
    using (DataContext dataContext = new DataContext())
    {
        return dataContext.Employees.First(x => x.Id == id);
    }
}

Here is the request

curl -i -H "Accept: application/json" http://localhost:56103/api/employee/1

And here is the response.(Removed the status line and other response text for readability)

{"Id":1,"Name":"Employee1","Email":"employee1@dotnetthoughts.net","Phone":"0013456732"}

For creating an Employee, you need to send a POST request. And you need to pass the Employee model parameter.

public void Post(Employee Employee)
{
    using (DataContext dataContext = new DataContext())
    {
        dataContext.Employees.Add(Employee);
        dataContext.SaveChanges();
    }
}

Here is the request which will create an employee by invoking the POST method in the service.

curl -i -H "Accept: application/json" -X POST -d "Name=Employee2&Email=employee2@server.com&Phone=093902902" http://localhost:56103/api/employee

And here is the response.

HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcYW51cmFqXGRvY3VtZW50c1x2aXN1YWwgc3R
1ZGlvIDIwMTJcUHJvamVjdHNcV2ViQVBJSGVsbG9Xb3JsZFxXZWJBUElIZWxsb1dvcmxkXGFwaVxlbXBsb3llZQ==?=
X-Powered-By: ASP.NET
Date: Sun, 01 Sep 2013 06:14:43 GMT

For updating an Employee, you need to send PUT request, with id and Employee model parameters.

public void Put(int id, Employee Employee)
{
    using (DataContext dataContext = new DataContext())
    {
        var selectedEmployee = dataContext.Employees.First(x => x.Id == id);
        selectedEmployee.Name = Employee.Name;
        selectedEmployee.Email = Employee.Email;
        selectedEmployee.Phone = Employee.Phone;
        dataContext.SaveChanges();
    }
}

Here is the PUT request, which helps to update an employee.

curl -i -H "Accept: application/json" -X PUT -d "Name=Employee1&Email=employee1@server.com&Phone=0013456732" http://localhost:56103/api/employee/1

And the response is similar to the POST request. For deleting an Employee, need to send a DELETE request with Id as the parameter.

public void Delete(int id)
{
    using (DataContext dataContext = new DataContext())
    {
        var selectedEmployee = dataContext.Employees.First(x => x.Id == id);
        dataContext.Employees.Remove(selectedEmployee);
        dataContext.SaveChanges();
    }
}

Here is the CURL command to delete an employee.

curl -i -H "Accept: application/json" -X DELETE http://localhost:56103/api/employee/1

For this DELETE request also, response is similar to POST request. You can use Fiddler also for sending the requests and managing the responses.

Happy Programming.

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub