JavaScript and APIs
Learn about APIs and JavaScript, as well as how they fit into Jamstack.
We'll cover the following
JavaScript
The “J” in Jamstack is for “JavaScript.” JavaScript is a scripting and programming language that allows us to add interactivity to our web pages. With JavaScript, we can make our applications interactive and add a lot of functionalities to them. JavaScript combines with APIs to make dynamic Jamstack applications.
Adding JavaScript to a web page
Let’s take a look at a simple application that uses JavaScript to change some DOM properties and add dynamism to our HTML page.
The question we might ask here is: Is this even a Jamstack application? The answer is yes! We’re using two components of Jamstack and the web page is still being delivered directly without being hosted on web servers, making it a Jamstack application.
API
An application programming interface (API) is a software gateway that allows different software components to communicate with each other. An API helps expose the capabilities of an application to the outer world, allowing for programmatic access to its data.
With the API part of Jamstack, we can make dynamic applications. In Jamstack, we can make dynamic pages using data saved on the server. In this case, we would use pre-rendering to make the site static, making it a Jamstack application. We’ll talk about pre-rendering in detail later on in this course.
Consider the case of an application that allows performing natural language processing tasks on the provided input. Building and exposing an API for this application will allow others to programmatically perform NLP operations, such as classification and summarization of the provided text.
Let’s take a look at an API call in the code below:
import fetch from "node-fetch";const endpointUrl = new URL('https://www.thecocktaildb.com/api/json/v1/1/random.php');const options = {method: 'GET'};async function fetchQuotes() {try {const response = await fetch(endpointUrl, options);printResponse(response);} catch (error) {printError(error);}}fetchQuotes();
In the code above, we call an API endpoint of TheCocktailDB. This particular endpoint returns a random cocktail from its list. The API call is made starting in line 9 using the fetch
method provided by JavaScript.