201 HTTP Status Code in ASP.NET Core Web API

201 HTTP Status Code in ASP.NET Core Web API

In this article, I will discuss How to Return 201 HTTP Status Code from the ASP.NET Core Web API Controller Action Method with Examples. Please read our previous article discussing How to Return 200 HTTP Status Code from the ASP.NET Core Web API Controller Action method with Examples.

201 HTTP Status Code

The 201 HTTP Status Code is used to indicate that a request has been successfully processed, and as a result, a new resource has been created. This status code is primarily associated with HTTP methods like POST, which submit an entity to the specified resource. The following are the key points of the 201 HTTP Status Code:

  • Meaning: The 201 Status Code signifies that the server has successfully created a new resource as a result of the request. It is a positive acknowledgement from the server indicating that the operation requested by the client was successful.
  • Headers: When a 201 Created status is returned, it is often accompanied by a Location header. This header specifies the URL of the newly created resource. The body of the response might also include a representation of the resource with details of its state.
  • Use Cases: Common scenarios where a 201 Created Status Code might be returned include creating a new user account, posting a new message in a forum, uploading a file, or any action where a new entity is added to the server’s data store.
How to Return 201 HTTP Status Code in ASP.NET Core Web API

To return a 201 HTTP Status Code, which indicates that a request has been fulfilled and has resulted in the creation of a new resource, from an ASP.NET Core Web API action, you can use the Created, CreatedAtAction or CreatedAtRoute method.

In ASP.NET Core Web API, the Created, CreatedAtAction and CreatedAtRoute methods return a 201 Created response with a Location header to the newly created resource. These methods are typically used in POST actions where a new resource has been created as a result of the request. They not only indicate that the resource was successfully created but also provide a URI to access the newly created resource.

We are going to work with the same example that we worked on in our previous article. If you are coming directly to this article, then please create the following Employee model, which we will be using in our controller.

namespace ReturnTypeAndStatusCodes.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
        public string Department { get; set; }
    }
}
Using the CreatedAtAction Method in ASP.NET Core Web API

The CreatedAtAction method is used to return a 201 HTTP Status Code and adds a Location header to the response. The header points to the action that can retrieve the newly created resource. The CreatedAtAction method returns a CreatedAtActionResult that creates a 201 Created response.

For a better understanding, please modify the Employee Controller as follows. In the below example, the GetEmployee method is going to return an employee based on the employee ID. The CreateEmployee method is going to create a new employee and return the 201 status code.

using ReturnTypeAndStatusCodes.Models;
using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        //Data Source
        private static List<Employee> Employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Rakesh", Age = 25, Gender = "Male", Department = "IT" },
            new Employee { Id = 2, Name = "Hina", Age = 26, Gender = "Female", Department = "HR" },
            new Employee { Id = 3, Name = "Suresh", Age = 27, Gender = "Male", Department = "IT" },
        };

        [HttpPost]
        public ActionResult<Employee> CreateEmployee(Employee employee)
        {
            // Add and save employee in your database or storage
            employee.Id = Employees.Count + 1;
            Employees.Add(employee);

            // Assuming you have an API for getting the resource
            // GetEmployee is the name of the action method which takes the employee id and return the employee
            return CreatedAtAction(nameof(GetEmployee), new { id = employee.Id }, employee);
        }

        [HttpGet("{id}")]
        public ActionResult<Employee> GetEmployee(int id)
        {
            var employee = Employees.FirstOrDefault(emp => emp.Id == id);
            if (employee == null)
            {
                // 404 Not Found if the employee does not exist
                return NotFound();
            }
            // 200 OK with the employee in the response body
            return Ok(employee);
        }
    }
} 

In this example, after adding the new employee to the store, CreatedAtAction is used to return a 201 Created status code. The first parameter is the name of the action method (GetEmployee) that can be used to retrieve the new resource. The Second Parameter is an anonymous object that contains route values (in this case, the ID of the new employee), and the third parameter is the value to format in the entity-body of the response.

Now, run the application, get the port number where your application is running and then issue a Post request using Postman, as shown in the image below. Here, you can see that we have selected the HTTP method as POST. Provided the URL as https://localhost:7128/api/Employee. As it is a Post request, we have selected the Body; in the body, we are sending the RAW data in JSON format and then clicking on the Send Button, as shown in the image below.

How to Return 201 HTTP Status Code from the ASP.NET Core Web API Controller Action Method with Examples

Once you click on the Send button, it will make an HTTP Post Request to the server by sending the Employee details in the Request body. The server will then process the request, create a new employee and return 201 HTTP Status Code along with the Employee details. To see the same, please select the Response Body tab as shown in the image below:

How to Return 201 HTTP Status in ASP.NET Core Web API

Along with the 201 Create HTTP Status Code and the response body, the server also set the Location header with the unique URI to access the newly created response. Now, if you select the response header tab, then you will see the following:

201 HTTP Status in ASP.NET Core Web API

Using the CreatedAtRoute Method in ASP.NET Core Web API

The CreatedAtRoute method returns a CreatedAtRouteResult and is similar to CreatedAtAction but uses route names to generate the URL. So, if you have a named route, you can use the CreatedAtRoute method. This is useful when the route to the action is defined using the Name property in the route’s attribute.

The CreatedAtRoute method is also used to return a 201 HTTP Status Code and adds a Location header to the response. The location header points to the action that can retrieve the newly created resource. For a better understanding, please modify the Employee Controller as follows. In the below example, the GetEmployee method is going to return an employee based on the employee ID. The CreateEmployee method is going to create a new employee and return the 201 status code.

using ReturnTypeAndStatusCodes.Models;
using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        //Data Source
        private static List<Employee> Employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Rakesh", Age = 25, Gender = "Male", Department = "IT" },
            new Employee { Id = 2, Name = "Hina", Age = 26, Gender = "Female", Department = "HR" },
            new Employee { Id = 3, Name = "Suresh", Age = 27, Gender = "Male", Department = "IT" },
        };

        [HttpPost]
        public ActionResult<Employee> CreateEmployee(Employee employee)
        {
            // Add and save employee in your database or storage
            employee.Id = Employees.Count + 1;
            Employees.Add(employee);

            // Assuming you have a named route for getting the resource
            // GetGetEmployeeRoute is the Route name of the Resource which takes the id and return the employee
            return CreatedAtRoute("GetGetEmployeeRoute", new { id = employee.Id }, employee);
        }

        //Generate Resource with Route Name
        [HttpGet("{id}", Name = "GetGetEmployeeRoute")]
        public ActionResult<Employee> GetEmployee(int id)
        {
            var employee = Employees.FirstOrDefault(emp => emp.Id == id);
            if (employee == null)
            {
                // 404 Not Found if the employee does not exist
                return NotFound();
            }
            // 200 OK with the employee in the response body
            return Ok(employee);
        }
    }
}

In this example, CreatedAtRoute is used with a named route (“GetGetEmployeeRoute“) to generate the Location header URL. The first parameter is the name of the route, the second parameter is an anonymous object with route values, and the third parameter is the created resource to be returned in the response body.

With the above changes in place, run the application and test the Post action method and it should work as expected in the previous example.

How to Return 201 Status Code without Data:

Both the CreatedAtAction and CreatedAtRoute methods automatically set the HTTP status code to 201 and include the Location header in the response, which is the URI of the newly created resource. The last parameter in both methods is the resource, which will be included in the response body.

If you don’t want to include the newly created resource data in the response body, then you need to set the last parameter value to null. For a better understanding, please modify the Employee Controller as follows:

using ReturnTypeAndStatusCodes.Models;
using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        //Data Source
        private static List<Employee> Employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Rakesh", Age = 25, Gender = "Male", Department = "IT" },
            new Employee { Id = 2, Name = "Hina", Age = 26, Gender = "Female", Department = "HR" },
            new Employee { Id = 3, Name = "Suresh", Age = 27, Gender = "Male", Department = "IT" },
        };

        [HttpPost]
        public ActionResult<Employee> CreateEmployee(Employee employee)
        {
            // Add and save employee in your database or storage
            employee.Id = Employees.Count + 1;
            Employees.Add(employee);

            //CreatedAtRoute Method takes the Route name 
            //With the Newly Created Resource Data
            //GetGetEmployeeRoute is the Route Name
            //return CreatedAtRoute("GetGetEmployeeRoute", new { id = employee.Id }, employee);

            //Without the Newly Created Resource Data
            //GetGetEmployeeRoute is the Route Name
            //return CreatedAtRoute("GetGetEmployeeRoute", new { id = employee.Id }, null);

            //CreatedAtAction Method takes the Action Method
            //With the Newly Created Resource Data
            //GetEmployee is the Action Method Name
            //return CreatedAtAction("GetEmployee", new { id = employee.Id }, employee);

            //Without the Newly Created Resource Data
            //GetEmployee is the Action Method Name
            return CreatedAtAction("GetEmployee", new { id = employee.Id }, null);
        }

        //Generate Resource with Route Name
        [HttpGet("{id}", Name = "GetGetEmployeeRoute")]
        public ActionResult<Employee> GetEmployee(int id)
        {
            var employee = Employees.FirstOrDefault(emp => emp.Id == id);
            if (employee == null)
            {
                // 404 Not Found if the employee does not exist
                return NotFound();
            }
            // 200 OK with the employee in the response body
            return Ok(employee);
        }
    }
}
Using Created Method in ASP.NET Core Web API

The Created method is used to return the HTTP Status Code 201, indicating that a new resource has been successfully created. This method is useful in POST actions where a new entity is added to the database or some resource is created as a result of the request. The Created method also adds a Location header to the response, specifying the URI of the newly created resource.

There are several overloads of the Created method, allowing you to specify the URI of the newly created resource and optionally include the value of the created entity in the response body. The following are the overloaded versions:

  • Created(): This method will return 201 Status Code without the URL Location header. This method will not include the data in the response body.
  • Created(Uri uri, object value): This method will return 201 Status Code without URL Location header. This method will include the data in the response body. The meaning of the parameters are as follows:
  • Created(string uri, object value): This method will return 201 Status Code without URL Location header and response body.

For a better understanding of the above three overloaded methods, please modify the Employee Controller as follows. In the below example, the GetEmployee method is going to return an employee based on the employee ID. The CreateEmployee1 method uses Created(), the CreateEmployee2 method uses Created(Uri uri, object value), and the CreateEmployee3 method uses Created(string uri, object value) overloaded versions. The following example code is self-explained, so please go through the comment lines.

using ReturnTypeAndStatusCodes.Models;
using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        //Data Source
        private static List<Employee> Employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Rakesh", Age = 25, Gender = "Male", Department = "IT" },
            new Employee { Id = 2, Name = "Hina", Age = 26, Gender = "Female", Department = "HR" },
            new Employee { Id = 3, Name = "Suresh", Age = 27, Gender = "Male", Department = "IT" },
        };

        //POST: api/Employee/CreateEmployee1
        [HttpPost]
        public ActionResult<Employee> CreateEmployee1(Employee employee)
        {
            // Add and save employee in your database or storage
            employee.Id = Employees.Count + 1;
            Employees.Add(employee);

            //Method without Location Header
            return Created();
        }

        //POST: api/Employee/CreateEmployee2
        [HttpPost]
        public ActionResult<Employee> CreateEmployee2(Employee employee)
        {
            // Add and save employee in your database or storage
            employee.Id = Employees.Count + 1;
            Employees.Add(employee);

            //Method without Location Header and Response Body using Uri
            //GetEmployeeById is the Route Name
            //var locationUri = new Uri(Url.Link("GetEmployeeById", new { id = employee?.Id }));

            var locationUri = new Uri($"https://localhost:7128/api/Employee/GetEmployee/{employee?.Id}");

            return Created(locationUri, employee);
        }

        //POST: api/Employee/CreateEmployee3
        [HttpPost]
        public ActionResult<Employee> CreateEmployee3(Employee employee)
        {
            // Add and save employee in your database or storage
            employee.Id = Employees.Count + 1;
            Employees.Add(employee);

            //Method without Location Header and Response Body using string Uri
            //GetEmployee is the action name
            //var locationUri = Url.Action("GetEmployee", "Employee", new { id = employee?.Id }, Request.Scheme);
            var locationUri = $"https://localhost:7128/api/Employee/GetEmployee/{employee?.Id}";
            return Created(locationUri, employee);
        }

        //GET: api/Employee/GetEmployee/1
        [HttpGet("{id}", Name = "GetEmployeeById")]
        public ActionResult<Employee> GetEmployee(int id)
        {
            var employee = Employees.FirstOrDefault(emp => emp.Id == id);
            if (employee == null)
            {
                // 404 Not Found if the employee does not exist
                return NotFound();
            }
            // 200 OK with the employee in the response body
            return Ok(employee);
        }
    }
}

With the above changes in place, run the application and test the Post Action Methods, and it should work as expected.

When Should We Return 201 HTTP Status Code in ASP.NET Core Web API?

In ASP.NET Core Web API, the HTTP status code 201 is returned to indicate that a request has been successfully processed and, as a result, a new resource has been created. Here are specific scenarios when you should return a 201 Status Code:

  • Creating a New Resource: The most common scenario for returning a 201 Status Code is after a POST request that results in the creation of a new entity. For example, when a client sends a request to create a new user, product, or any other entity, and the operation is successful, the server should respond with a 201 Status Code.
  • Providing Location Header: Along with the 201 Status Code, it is best practice to include a Location header in the response. This header should contain the URI of the newly created resource. This allows the client to directly access the new resource without needing to perform another query to find it.
  • Returning Resource Representation (Optional): In some cases, along with the status code and the Location header, the server may also return a representation of the newly created resource in the response body. This inclusion is optional and depends on the specific requirements of the API and its consumers.
  • Asynchronous Creation: In situations where resource creation is initiated but processed asynchronously (meaning the resource might not be created immediately), a 201 Status Code might still be returned if the server expects the creation process to succeed. However, this usage can vary, and some APIs might opt to use a 202 Accepted status code in such cases, especially if the outcome of the creation process is uncertain at the time of the response.

In the next article, I will discuss How to Return 202 HTTP Status Code in ASP.NET Core Web API with Examples. In this article, I try to explain How to Return 201 Created HTTP Status Code in ASP.NET Core Web API with Examples, and I hope you enjoy this article on “201 HTTP Status Code in the ASP.NET Core Web API”.

1 thought on “201 HTTP Status Code in ASP.NET Core Web API”

  1. blank

    var employee = Employees.FirstOrDefault(emp => emp.Id == id);
    there is error in above code. could you pleasse look into it.

Leave a Reply

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