Let’s continue extending our web API controller to add the ability to create (POST), update (PUT), and delete (DELETE) pizza from our inventory.
microsoft system center certification training courses malaysia
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:
microsoft sql server certification training courses malaysia
C#
[HttpPost]
public IActionResult Create(Pizza pizza)
{
PizzaService.Add(pizza);
return CreatedAtAction(nameof(Get), 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.
microsoft sharepoint certification training courses malaysia
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, as explained in the previous unit.
sap wm warehouse management training courses malaysia
Modify a pizza
Now, let’s enable a pizza to be updated through the web API by using a PUT method.
sap supply chain management scm training courses malaysia
Replace the // PUT action comment in Controllers/PizzaController.cs with the following code:
C#
[HttpPut("{id}")]
public IActionResult Update(int id, Pizza pizza)
{
if (id != pizza.Id)
return BadRequest();
var existingPizza = PizzaService.Get(id);
if(existingPizza is null)
return NotFound();
PizzaService.Update(pizza);
return NoContent();
}
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.
sap s-4 hana training courses malaysia
Note
Because the controller is annotated with the [ApiController] attribute, it’s implied that the Pizza parameter will be found in the request body.
sap fico financial accounting training courses malaysia
Remove a pizza
Finally, let’s enable a pizza to be removed through the web API by using a DELETE method.
sap erp pp production planning training courses malaysia
Replace the // DELETE action comment in Controllers/PizzaController.cs with the following code:
C#
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var pizza = PizzaService.Get(id);
if (pizza is null)
return NotFound();
PizzaService.Delete(id);
return NoContent();
}
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,
sap erp procurement material management training courses malaysia
Build and run the finished web API
Build and start the web API by running the following command:
.NET CLI
dotnet run
Test the finished web API with HTTP files
- Reopen the ContosoPizza.http file.
- Make a
POSTrequest to add a new pizza inHttpReplby using the following command:OutputPOST {{ContosoPizza_HostAddress}}/pizza/ Content-Type: application/json { "name": "Hawaii", "isGlutenFree": false } ###The preceding command returns the newly created pizza:OutputHTTP/1.1 201 Created Connection: close Content-Type: application/json; charset=utf-8 Date: Wed, 17 Jan 2024 17:03:02 GMT Server: Kestrel Location: http://localhost:5192/Pizza/3 Transfer-Encoding: chunked { "id": 3, "name": "Hawaii", "isGlutenFree": false } - Update the new
Hawaiipizza to aHawaiianpizza with aPUTrequest by using the following command:OutputPUT {{ContosoPizza_HostAddress}}/pizza/3 Content-Type: application/json { "id": 3, "name": "Hawaiian", "isGlutenFree": false } ###The preceding command returns the following output that indicates success:OutputHTTP/1.1 204 No Content Connection: close Date: Wed, 17 Jan 2024 17:07:30 GMT Server: KestrelTo verify that the pizza was updated, rerun theGETaction by using the following command:OutputGET {{ContosoPizza_HostAddress}}/pizza/3 Accept: application/json ###The preceding command returns the newly updated pizza:OutputHTTP/1.1 200 OK Connection: close Content-Type: application/json; charset=utf-8 Date: Wed, 17 Jan 2024 17:09:01 GMT Server: Kestrel Transfer-Encoding: chunked { "id": 3, "name": "Hawaiian", "isGlutenFree": false } - Our API can also delete the newly created pizza through the
DELETEaction if you run the following command:.NET CLIDELETE {{ContosoPizza_HostAddress}}/pizza/3 ###The preceding command returns a204 No Contentresult for success:OutputHTTP/1.1 204 No Content Date: Fri, 02 Apr 2021 23:30:04 GMT Server: KestrelTo verify that the pizza was removed, rerun theGETaction by using the following command:.NET CLIGET {{ContosoPizza_HostAddress}}/pizza/ Accept: application/json ###The preceding command returns the original pizzas as results:OutputHTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Date: Fri, 02 Apr 2021 23:31:15 GMT Server: Kestrel Transfer-Encoding: chunked [ { "id": 1, "name": "Classic Italian", "isGlutenFree": false }, { "id": 2, "name": "Veggie", "isGlutenFree": true } ]
You’re now finished implementing and testing a newly created web API built with ASP.NET Core.
red hat openstack training courses malaysia
Optional: Test the finished web API with Command Line HTTPREPL
- Reopen the existing
httpreplterminal, or open a new integrated terminal from Visual Studio Code by selecting Terminal > New Terminal from the main menu. - If you opened a new terminal, connect to the web API by running the following command:.NET CLI
httprepl https://localhost:{PORT}Alternatively, run the following command at any time whileHttpReplis running:.NET CLIconnect https://localhost:{PORT} - Go to the
Pizzaendpoint by running the following command:.NET CLIcd Pizza - Run the following command to see the new actions on the Pizza API:.NET CLI
lsThe preceding command shows an output of available APIs for thePizzaendpoint:Outputhttps://localhost:{PORT}/Pizza> ls . [GET|POST] .. [] {id} [GET|PUT|DELETE] - Make a
POSTrequest to add a new pizza inHttpReplby using the following command:.NET CLIpost -c "{"name":"Hawaii", "isGlutenFree":false}"The preceding command returns the newly created pizza:OutputHTTP/1.1 201 Created Content-Type: application/json; charset=utf-8 Date: Fri, 02 Apr 2021 23:23:09 GMT Location: https://localhost:{PORT}/Pizza?id=3 Server: Kestrel Transfer-Encoding: chunked { "id": 3, "name": "Hawaii", "isGlutenFree": false } - Update the new
Hawaiipizza to aHawaiianpizza with aPUTrequest by using the following command:.NET CLIput 3 -c "{"id": 3, "name":"Hawaiian", "isGlutenFree":false}"The preceding command returns the following output that indicates success:OutputHTTP/1.1 204 No Content Date: Fri, 02 Apr 2021 23:23:55 GMT Server: KestrelTo verify that the pizza was updated, rerun theGETaction by using the following command:.NET CLIget 3The preceding command returns the newly updated pizza:OutputHTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Date: Fri, 02 Apr 2021 23:27:37 GMT Server: Kestrel Transfer-Encoding: chunked { "id": 3, "name": "Hawaiian", "isGlutenFree": false } - Our API can also delete the newly created pizza through the
DELETEaction if you run the following command:.NET CLIdelete 3The preceding command returns a204 No Contentresult for success:OutputHTTP/1.1 204 No Content Date: Fri, 02 Apr 2021 23:30:04 GMT Server: KestrelTo verify that the pizza was removed, rerun theGETaction by using the following command:.NET CLIgetThe preceding command returns the original pizzas as results:OutputHTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Date: Fri, 02 Apr 2021 23:31:15 GMT Server: Kestrel Transfer-Encoding: chunked [ { "id": 1, "name": "Classic Italian", "isGlutenFree": false }, { "id": 2, "name": "Veggie", "isGlutenFree": true } ]
You’re now finished implementing and testing a newly created web API built with ASP.NET Core.
Leave a Reply