Web APIs with Controllers

Web APIs with Controllers: Web APIs with Controllers: an overview, Creating an API Controller, Insomnia: GET, GET, Insomnia: POST, POST, Insomnia: PUT, PUT,…

Updated

  1. Web APIs with Controllers: an overview (Apprentice): REST is the common way to design a web API. Each kind of data is a resource with its own address, and the HTTP method says what to do with it. GET, POST, PUT and DELETE match SELECT, INSERT, UPDATE and DELETE, each with its usual status code.
  2. Creating an API Controller (Journeyman): An API controller derives from ControllerBase, is marked [ApiController], and gets its address from [Route]. It asks for its DAO through an interface registered in Program.cs, and its actions return data that ASP.NET Core sends as JSON.
  3. Insomnia: GET (Journeyman): Before you build the next GET actions, write the requests you want them to answer in an Insomnia collection, with your API's address in an environment, send them, and read what comes back.
  4. GET (Journeyman): GET reads data. One [HttpGet] action returns the whole collection, and an [HttpGet("{id}")] action returns one item, its id taken from the address. ASP.NET Core sends what they return as JSON, with 200 OK.
  5. Insomnia: POST (Journeyman): Before you build the POST action, write the requests that add a category in Insomnia, each with a JSON body, send them, and learn why the answer today is 405 Method Not Allowed instead of 404.
  6. POST (Journeyman): POST creates a new item from the JSON in the request body. The DAO inserts it and returns it with its new id, and the action answers 201 Created with CreatedAtAction, which also says where the new item lives. Invalid bodies get 400 automatically.
  7. Insomnia: PUT (Journeyman): Before you build the PUT action, write the requests that change a category in Insomnia, with the id in the address and the whole changed category in the body, and decide what each one should answer.
  8. PUT (Journeyman): PUT replaces an item with the one in the request body, its id taken from the address. The DAO updates the row and hands back the category as it was saved, and the action answers 200 OK with it, or 404 Not Found when there's no such item.
  9. Insomnia: DELETE (Journeyman): Before you build the DELETE action, write the requests that delete a category in Insomnia, with no body, and decide what each should answer, including a second send of the same request and a category the database won't let go.
  10. DELETE (Journeyman): DELETE removes the item at an address. It sends no body; the action deletes by the id from the route and answers 204 No Content, or 404 Not Found when there was nothing to delete.
  11. Returning ActionResult<T> (Journeyman): ActionResult<T> lets an action return either its data or a status code result, such as NotFound(). Return the item to answer 200 with it, or a helper such as NotFound(), BadRequest() or Conflict() to answer with that status instead.