Friday, December 25, 2020

Create Web API for CRUD operation - Part 5: Implement Delete Method

 This section is a continuation of the previous four sections where we created necessary infrastructure for the Web API and also implemented GET, POST & PUT methods. Here, we will implement Delete action method in the Web API.

The HTTP DELETE request is used to delete an existing record in the data source in the RESTful architecture.

So let's create an action method in our StudentController to delete an existing student record in the database using Entity Framework. The action method that will handle HTTP DELETE request must start with the word "Delete". It can be named either Delete or with any suffix e.g. DELETE(), Delete(), DeleteStudent(), DeleteAllStudents() are valid names for an action method that handles HTTP DELETE request.

The following example demonstrates Delete action method to handle HTTP DELETE request.

Example: Delete Method in Web API Controller
public class StudentController : ApiController
{

    public StudentController()
    {
    }

    public IHttpActionResult Delete(int id)
    {
        if (id <= 0)
            return BadRequest("Not a valid student id");

        using (var ctx = new SchoolDBEntities())
        {
            var student = ctx.Students
                .Where(s => s.StudentID == id)
                .FirstOrDefault();

            ctx.Entry(student).State = System.Data.Entity.EntityState.Deleted;
            ctx.SaveChanges();
        }

        return Ok();
    }
}

As you can see above, Delete action method includes an id parameter of int type because it just needs an id to delete a record. It fetches an existing student from the database that matches with the specified id and then marks its status as deleted. This will delete a student from the database.

Now, you can send HTTP DELETE request using Fiddler as shown below and view the response.

Execute HTTP DELETE request in Fiddler

As you can see in the above figure, HTTP DELETE request url http://localhost:64189/api/student?id=1 includes query string id. This id query string will be passed as an id parameter in Delete() method. After successful execution the response status is 200 OK.

Thus you can create Get, Post, Put and Delete methods to implement HTTP GET, POST, PUT and DELETE requests respectively.

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...