How to Implement POST Method in Web API

How to Implement the POST Method in Web API Application

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

  1. How to Implement the POST method in Web API Application?
  2. Understanding the FromBody Attribute in Web API.
  3. Testing the Web API Post method using Fiddler.
  4. Understanding the HttpResponseMessage return type in Web API.

How to Implement the POST Method in Web API Application?

The Post Method in the Web API application 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 the [FromBody] attribute. We will discuss the [FromBody] attribute in detail 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 the 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  
Points to Remember while working with Web API Post Method:
  1. If a method return type is void in Web API Service then by default Web API Service returns the status code 204 No Content.
  2. When a new item is created, we should be returning status code 201 Item Created.
  3. With the 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 am going to discuss How to Implement PUT Method in Web API Application with an example. Here, in this article, I try to explain how to Implement the POST Method in ASP.NET Web API Application step by step with a simple example.

Registration Open For New Online Training

Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.

3 thoughts on “How to Implement POST Method in Web API”

  1. blank

    Great tutorial, incredibly helpful. Just two suggestions:

    The “How to Implement GET Method in Web API” article seems to be missing the note to ensure that you include:

    “using EmployeeService.Models;”

    and I suspect that in this article “How to Implement POST Method in Web API”, the line

    message.Headers.Location = new Uri(Request.RequestUri + employee.ID.ToString());

    should read

    message.Headers.Location = new Uri(Request.RequestUri + “/” + employee.ID.ToString());

    in order to return a valid link to the newly created record.

Leave a Reply

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