How to implement POST Method in WEB API

How to implement the POST Method in WEB API

In this article, I am going to discuss how to implement the POST Method in WEB API with one example. Please Read our previous article where we discussed how to implement the GET Method in ASP.NET WEB API before proceeding to this article as we are going to use the same example.

Implementing the POST method in WEB API:

Post allows us to create a new item. 

Here, we want to add a new Employee to the Employees table. First, Include the following Post() method within the EmployeesController. Notice that the Employee object is being passed as a parameter to the Post method.

The Employee parameter is decorated with [FromBody] attribute. We will discuss [FromBody] attribute in details in a later article but for now to understand this [FormBody] attribute tells the Web API to get the employee data from the request body.

public class EmployeesController : ApiController
{
    public void Post([FromBody] Employee employee)
    {
        using (EmployeeDBContext dbContext = new EmployeeDBContext())
        {
            dbContext.Employees.Add(employee);
            dbContext.SaveChanges();
        }
    }
}

At this point build the solution. Run the application and Fire up Fiddler and issue a Post request

  1. Set the HTTP verb to POST
  2. Content-Type: application/json. This tells that we are sending JSON formatted data to the server
  3. In the Request Body, include the employee object that we want to add to the Employees database table in JSON format
  4. Finally, click on the Execute button as shown in the below image

Implementing POST Method in WEB API   When we click on the Execute button, it will give us the below Response.

Implementing POST Method in WEB API

This works fine and adds the employee to the database as expected. The problem here is that since the return type of the Post method is void, we get status code 204 No Content. As per REST standard, when a new item is created, it should return the status code 201 Item Created. With 201 status code, we may also include the location i.e. URI of the newly created item.

Let’s see how to achieve this. To achieve this, we need to modify the POST method as shown below.
public class EmployeesController : ApiController
{
    public HttpResponseMessage Post([FromBody] Employee employee)
    {
        try
        {
            using (EmployeeDBContext dbContext = new EmployeeDBContext())
            {
                dbContext.Employees.Add(employee);
                dbContext.SaveChanges();

                var message = Request.CreateResponse(HttpStatusCode.Created, employee);
                message.Headers.Location = new Uri(Request.RequestUri +
                    employee.ID.ToString());

                return message;
            }
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }
}

At this point, issue another Post request from Fiddler. Notice in the response header we have status code 201 Created and also the location i.e. the URI of the newly created item as shown in the below image.

Implementing POST Method in WEB API   Here are the important points to remember
  1. If a method return type is void in Web API Service then by default Web API Service return the status code 204 No Content.
  2. When a new item is created, we should be returning status code 201 Item Created.
  3. With 201 status code, we should also include the location i.e. URI of the newly created item. 
  4. When an item is not found, instead of returning NULL and status code 200 OK, return 404 Not Found status code along with a meaningful message such as “Employee with Id = 15 not found

In the next article, I will discuss how to implement PUT Method in WEB API with an example.

SUMMARY

In this article, I try to explain Implementing the POST Method in WEB API step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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