Create Web API for CRUD operation - Part 3: Implement Post Method

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

The HTTP POST request is used to create a new record in the data source in the RESTful architecture. So let's create an action method in our StudentController to insert new student record in the database using Entity Framework.

The action method that will handle HTTP POST request must start with a word Post. It can be named either Post or with any suffix e.g. POST(), Post(), PostNewStudent(), PostStudents() are valid names for an action method that handles HTTP POST request.

The following example demonstrates Post action method to handle HTTP POST request.

Example: Post Method in Web API Controller
public class StudentController : ApiController
{
    public StudentController()
    {
    }

    //Get action methods of the previous section
    public IHttpActionResult PostNewStudent(StudentViewModel student)
    {
        if (!ModelState.IsValid)
            return BadRequest("Invalid data.");

        using (var ctx = new SchoolDBEntities())
        {
            ctx.Students.Add(new Student()
            {
                StudentID = student.Id,
                FirstName = student.FirstName,
                LastName = student.LastName
            });

            ctx.SaveChanges();
        }

        return Ok();
    }
} 

As you can see above, we named action method as PostNewStudent. You can give any name as per your requirement but it must start with the word "Post". The PostNewStudent() action method includes parameter of StudentViewModel type which includes all the information about new student.

In the Post method we first need to validate the model using ModelState.IsValid. This will make sure that student object includes all the necessary information. If it is not valid then you can return BadRequest response. If it is valid then add student using Entity Framework context and return 200 OK status response.

Note:
This is just a demo project. However, you can return newly created student object with Id in the response.

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

Execute HTTP POST request in Fiddler

As you can see in the above figure, HTTP POST request includes StudentViewModel object into JSON format in the request body. After successful execution the response status is 200 OK.

Next, implement Put action method to handle HTTP PUT request in the Web API.

Want to check how much you know Web API?