Exercise – Implement CRUD operations

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 POST verb, as denoted by the [HttpPost] attribute.
  • Inserts the request body’s Pizza object 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 id parameter’s value is included in the URL segment after pizza/.
  • Returns IActionResult, because the ActionResult return type isn’t known until runtime. The BadRequestNotFound, and NoContent methods return BadRequestResultNotFoundResult, and NoContentResult types, 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 DELETE verb, as denoted by the [HttpDelete] attribute.
  • Requires that the id parameter’s value is included in the URL segment after pizza/.
  • Returns IActionResult because the ActionResult return type isn’t known until runtime. The NotFound and NoContent methods return NotFoundResult and NoContentResult types, respectively.
  • Queries the in-memory cache for a pizza that matches the provided id parameter.

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

  1. Reopen the ContosoPizza.http file.
  2. Make a POST request to add a new pizza in HttpRepl by 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 }
  3. Update the new Hawaii pizza to a Hawaiian pizza with a PUT request 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: Kestrel To verify that the pizza was updated, rerun the GET action 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 }
  4. Our API can also delete the newly created pizza through the DELETE action if you run the following command:.NET CLIDELETE {{ContosoPizza_HostAddress}}/pizza/3 ### The preceding command returns a 204 No Content result for success:OutputHTTP/1.1 204 No Content Date: Fri, 02 Apr 2021 23:30:04 GMT Server: Kestrel To verify that the pizza was removed, rerun the GET action 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

  1. Reopen the existing httprepl terminal, or open a new integrated terminal from Visual Studio Code by selecting Terminal > New Terminal from the main menu.
  2. If you opened a new terminal, connect to the web API by running the following command:.NET CLIhttprepl https://localhost:{PORT} Alternatively, run the following command at any time while HttpRepl is running:.NET CLIconnect https://localhost:{PORT}
  3. Go to the Pizza endpoint by running the following command:.NET CLIcd Pizza
  4. Run the following command to see the new actions on the Pizza API:.NET CLIls The preceding command shows an output of available APIs for the Pizza endpoint:Output https://localhost:{PORT}/Pizza> ls . [GET|POST] .. [] {id} [GET|PUT|DELETE]
  5. Make a POST request to add a new pizza in HttpRepl by 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 }
  6. Update the new Hawaii pizza to a Hawaiian pizza with a PUT request 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: Kestrel To verify that the pizza was updated, rerun the GET action by using the following command:.NET CLIget 3 The 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 }
  7. Our API can also delete the newly created pizza through the DELETE action if you run the following command:.NET CLIdelete 3 The preceding command returns a 204 No Content result for success:OutputHTTP/1.1 204 No Content Date: Fri, 02 Apr 2021 23:30:04 GMT Server: Kestrel To verify that the pizza was removed, rerun the GET action by using the following command:.NET CLIget 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 linux certification malaysia

Comments

Leave a Reply

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