Implement CRUD
Implement CRUD operation
Let's continue extending our web API controller to add the ability to create (POST), update (PUT), and delete (DELETE) pizza from our inventory.
Add a pizza
Let's enable a pizza to be added through the web API by using a POST method.
Replace the // POST action comment in Controllers/PizzaController.cs with the following code:
[HttpPost]
public IActionResult Create(Pizza pizza)
{
PizzaService.Add(pizza);
return CreatedAtAction(nameof(Create), new { id = pizza.Id }, pizza);
}The preceding action:
Responds only to the HTTP
POSTverb, as denoted by the[HttpPost]attribute.Inserts the request body's
Pizzaobject into the in-memory cache.
Note
Because the controller is annotated with the [ApiController] attribute, it's implied that the Pizza parameter will be found in the request body.
The first parameter in the CreatedAtAction method call represents an action name. The nameof keyword is used to avoid hard-coding the action name. CreatedAtAction uses the action name to generate a location HTTP response header with a URL to the newly created pizza.
Modify a pizza
Now, let's enable a pizza to be updated through the web API by using a PUT method.
Replace the // PUT action comment in Controllers/PizzaController.cs with the following code:
The preceding action:
Responds only to the HTTP PUT verb, as denoted by the
[HttpPut]attribute.Requires that the
idparameter's value is included in the URL segment afterpizza/.Returns
IActionResult, because theActionResultreturn type isn't known until runtime. TheBadRequest,NotFound, andNoContentmethods returnBadRequestResult,NotFoundResult, andNoContentResulttypes, respectively.
Note
Because the controller is annotated with the [ApiController] attribute, it's implied that the Pizza parameter will be found in the request body.
Remove a pizza
Finally, let's enable a pizza to be removed through the web API by using a DELETE method.
Replace the // DELETE action comment in Controllers/PizzaController.cs with the following code:
The preceding action:
Responds only to the HTTP
DELETEverb, as denoted by the[HttpDelete]attribute.Requires that the
idparameter's value is included in the URL segment afterpizza/.Returns
IActionResultbecause theActionResultreturn type isn't known until runtime. TheNotFoundandNoContentmethods returnNotFoundResultandNoContentResulttypes, respectively.Queries the in-memory cache for a pizza that matches the provided
idparameter.
Remember to save the Controllers/PizzaController.cs file before proceeding,
Build and run the finished web API
Try to create a pizza as shown:


You can also see the newly created pizza if you do a get request for showing all pizzas. Note that this has to be done before you stop the application since we don't have a backing database and we are reading from cache!

Similarly, you can try editing and deleting a pizza!
Videos for learning more
Last updated