I'm implementing a RESTful service using Web API. The service is responsible for managing products. Products can be created, deleted and updated. Here is my current Web API controller:
[Route("api/[controller]")]
public class ProductsController : Controller
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
this._productService = productService;
}
[HttpGet("{id}", Name = "GetProductById")]
public IActionResult Get(int id)
{
return this.Ok(this._productService.Get(id));
}
[HttpPost]
public IActionResult Post([FromBody] Product product)
{
var newProductId = this._productService.Add(product);
var routeValues = new
{
controller = "Products",
id = newProductId
};
return this.CreatedAtRoute("GetProductById", routeValues, null);
}
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Product product)
{
this._productService.Edit(product);
return this.Ok();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
this._productService.Delete(id);
return this.Ok();
}
}
A new requirement has come in, such that depending on the scenario, products are updated according to either of the following flows:
- A new revision of the product, with a new ID, is created in the database. Eventually, once the new revision goes live, the previous revision will be archived.
- The product is updated in the database as-is, without creating a new revision. The ID of the product will therefore remain the same.
My understanding is that a PUT request satisfies point 2. But what about point 1? Should it be implemented as a PUT or a POST request? I'm thinking it should be a PUT request as, from a consuming point of view, the product is being updated, even though behind the-scenes a new record gets created.
If I were to implement it as a PUT, then should the Put
method in my controller return the id of the product, to cater for point 1 above (as the new product revision has a new ID)? Or should I create two separate methods to cater for each of the above points?