Create Resource using POST Method in Rest Asp.Net Web API

In one of my previous articles, Get Single Resource in Asp.Net Web API, we discussed how to get the single resource employee based on its Id in Asp.Net Rest web API. Today we talk about how to create the resource in Asp.Net Web API. By using HTTP GET verb, we get the resource, and by using the HTTP POST verb, we create the resource in Rest API.

        // POST: Add Employee
        [Route("api/employees/addemployee")]
        [HttpPost]
        public HttpResponseMessage AddEmployee([FromBody]Employee emp)
        {
            try
            {
                if(emp == null ||  !ModelState.IsValid)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }

                int empId = Company.AddEmployee(emp);
                return Request.CreateResponse(HttpStatusCode.Created, empId);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }

As shown above, we have created a new API method AddEmployee() of POST type, which takes Employee object as input and returns HTTP status code Created (status Code 201) and newly created employee Id on success.

If you observe here, we are checking the input object has data or not by checking its value with null and checking its state by using ModelState.Valid property. In the next article, we will discuss how to invoke this POST API method through the Fiddler tool.

                                                                                   CompanyRestAPI04082020-01.zip (55.61 mb)