Creating Web APIs
You can think of a Web API kind of as a web based database. APIs work just like web applications do, but their goal is not to create web pages. Instead, an API is intended to access data. The application requesting the data can then use it however it wants or needs to. You may find it easiest to think of an API like a DAO (Data Access Object) that you can call over the web. APIs can perform all CRUD operations. API vs Web Applications A web browser application uses HTML and the DOM to display the application to the screen. You will remember that in the MVC Controllers we use @GetMapping and @PostMapping to annotate methods to make web accessible. Navigating to a new page results in GET request to the web server. When a form is submitted a POST request is made, sending the form data in the body of the request. With a basic web application all CRUD operations are completed through these GET and POST requests. GET The GET verb is used to handle all read operations. POST The POST verb is used to handle all other operations (INSERT, UPDATE and DELETE).
Updated
RESTful Web APIs
- RESTful Web APIs: an overview (Apprentice): REST is the standard most web APIs follow, with one HTTP verb (GET, POST, PUT, DELETE) for each CRUD operation.
- Creating a REST Controller (Journeyman): Build a REST API in Spring Boot with a @RestController class whose methods return JSON for each GET, POST, PUT and DELETE request.
- Insomnia: GET (Journeyman): Before you write the GET method, save the request you want it to answer in an Insomnia collection, with your API's address in an environment, send it, and read what comes back.
- GET (Journeyman): Handle a GET request in Spring Boot with @GetMapping, return the categories as JSON, and check it from Insomnia.
- Insomnia: POST (Journeyman): Before you write the POST method, save the request that adds a category in Insomnia, with a JSON body, send it, and learn why the answer today is 405 Method Not Allowed instead of 404.
- POST (Journeyman): Handle a POST request with @PostMapping and @RequestBody, insert the new category with a JdbcTemplate and return it with its generated id and a 201 status.
- Insomnia: PUT (Journeyman): Before you write the PUT method, save the request that changes a category in Insomnia, with the id in the address and the whole changed category in the body, and decide what it should answer.
- PUT (Journeyman): Handle a PUT request with @PutMapping, taking the category's id from the URL and its new values from the body, update it with a JdbcTemplate and return the updated category with a 200 status.
- Insomnia: DELETE (Journeyman): Before you write the DELETE method, save the request that deletes a category in Insomnia, with no body, decide what it should answer, and plan how to prove the category is gone.
- DELETE (Journeyman): Handle a DELETE request with @DeleteMapping, taking the category's id from the URL, and answer 204 No Content.