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.
For communicating to Database, I am using Entity Framework. And here is the EF DbContext class.
The employee api exposes following methods
Action
HTTP method
URL
Get all Employees
GET
/api/Employee
Get an Employee by Id
GET
/api/Employee/{Id}
Create new Employee
POST
/api/Employee
Update an existing Employee
PUT
/api/Employee/{Id}
Delete an Employee
DELETE
/api/Employee/{Id}
And here is the implementation.
This method will return all the employees.
You can use browser or curl to verify this. Here is the curl request to invoke the Get method.
And here is the response.
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.
Here is the request
And here is the response.(Removed the status line and other response text for readability)
For creating an Employee, you need to send a POST request. And you need to pass the Employee model parameter.
Here is the request which will create an employee by invoking the POST method in the service.
And here is the response.
For updating an Employee, you need to send PUT request, with id and Employee model parameters.
Here is the PUT request, which helps to update an employee.
And the response is similar to the POST request. For deleting an Employee, need to send a DELETE request with Id as the parameter.
Here is the CURL command to delete an employee.
For this DELETE request also, response is similar to POST request. You can use Fiddler also for sending the requests and managing the responses.