How to Implement PUT Method in Web API

How to Implement PUT Method in Web API Application

In this article, I am going to discuss how to Implement PUT Method in Web API with one example. Please read our previous article where we discussed how to implement the POST Method in Web API before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following.

  1. How to Implement the PUT method in Web API?
  2. Testing the PUT method using Fiddler.
How to Implement the PUT method in ASP.NET Web API?

The PUT method in Web API allows us to update an item. Here, we want to update the employee by Id. Include the following Put method in EmployeesController. Notice the id of the employee that we want to update and the Employee object with which we want to update are being passed as parameters to the Post method. The Employee parameter is decorated with the [FromBody] attribute. This tells Web API to get employee data from the request body.

public class EmployeesController : ApiController
{
    public void Put(int id, [FromBody]Employee employee)
    {
        using (EmployeeDBContext dbContext = new EmployeeDBContext())
        {
            var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);

            entity.FirstName = employee.FirstName;
            entity.LastName = employee.LastName;
            entity.Gender = employee.Gender;
            entity.Salary = employee.Salary;

            dbContext.SaveChanges();
        }
    }
}
At this point build the solution, run the application and fire up Fiddler and issue a Put request.
  1. Set the HTTP verb to PUT
  2. Content-Type: application/json. This tells that we are sending JSON formatted data to the server
  3. In the Request Body, include the updated employee object with which you want to update
  4. Finally, click on the execute button as shown below

Implementing PUT Method in WEB API

When we click on the Execute button, it will give us the below response.

Implementing PUT Method in WEB API

This works fine and updates the employee record in the database as expected. The problem here is that since the return type of the Put method is void, we get status code 204 No Content. When the update is successful, we want to return status code 200 OK indicating that the update is successful.

Also when we try to update an employee whose Id does not exist we get back HTTP status code 500 Internal Server Error. We get status code 500, because of a NULL reference exception. To fix both of these issues modify the code in the Put method as shown below.

public class EmployeesController : ApiController
{
    public HttpResponseMessage Put(int id, [FromBody]Employee employee)
    {
        try
        {
            using (EmployeeDBContext dbContext = new EmployeeDBContext())
            {
                var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);
                if (entity == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                        "Employee with Id " + id.ToString() + " not found to update");
                }
                else
                {
                    entity.FirstName = employee.FirstName;
                    entity.LastName = employee.LastName;
                    entity.Gender = employee.Gender;
                    entity.Salary = employee.Salary;

                    dbContext.SaveChanges();

                    return Request.CreateResponse(HttpStatusCode.OK, entity);
                }
            }
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }
}

At this point, issue another Put request from Fiddler. Notice in the response header we have status code 200 OK. Also, when we try to update an employee whose id does not exist, we get the status code 404 Not Found instead of 500 Internal Server Error 

In the next article, I will discuss how to Implement the DELETE Method in Web API. Here, in this article, I try to explain how to Implement PUT Method in ASP.NET WEB API step by step with a simple example. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

5 thoughts on “How to Implement PUT Method in Web API”

    1. Yes you can achieve the same thing in POST also and in DELETE also.

      My understanding is, the verbs (POST, GET, PUT, etc.,) are like contracts (ie when you send POST, I’ll be adding some resource, when you send GET I’ll be fetching and returning some resources) between client & server. So that, clients can make some assumptions like I can issue GET method again & again, it will not modify, delete or add anything in the server.

  1. Madhumitha Gopalakrishnan

    when i implement this i am getting nullreference exception.Object is not set to a new instance

Leave a Reply

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