201 Created

Explanation:

The 201 Created status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The new resources are effectively created before the response is sent and the new resource is returned in the body of the message, its location being either the URL of the request, or the content of the Location header.

Usage:

This status code is used to inform the client that a new resource has been successfully created as a result of the request.

Attentions:

  • The server must include a Location header in the response to indicate the URL of the newly created resource.
  • The response body should contain a representation of the new resource, and the client should be able to use the URL in the Location header to access the new resource.

Sample:

let items = [];
export default function handler(req, res) {
  if (req.method === 'POST') {
    const newItem = req.body;
    newItem.id = items.length + 1;
    items.push(newItem);
    res.status(201).location(`/api/items/${newItem.id}`).json(newItem);
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}