Calling APIs From JavaScript

So far, most of our focus has been on building API's using Java and Spring Boot, but as we have been building our web pages, we have seen a need to interact with those APIs to get data. In this chapter we will dive a little deeper into using the built-in JavaScript Fetch API. We will also look at the Axios library as an alternative to using the Fetch API directly.

Updated

Fetch vs Axios

  1. Fetch (Apprentice): Call a REST API from JavaScript with the built-in fetch function: GET, POST, PUT and DELETE, checking response.ok before using the result.
  2. Axios (Apprentice): Call a REST API with the Axios library, whose get, post, put and delete functions set the method, the JSON header and the error check for you.

Using Async / Await

  1. Using Async / Await (Journeyman): Rewrite a promise chain (then/catch) with async and await, so an API call reads top to bottom and errors land in a try/catch block.