How to get data from an API in Javascript

Richard Oliver Bray
4 min readDec 30, 2022
Photo by Nubelson Fernandes on Unsplash

As of November 7th 2022, I started a TikTok account which has been doing quite well. Its focus is to teach beginners how to code with bite-sized little tips.

The that explains how to get data from an API using javascript is by far and away my most popular video with over 120,000 views!! I’m honestly humbled by the success. But I know there are many of you out there who don’t use TikTok and many others who would prefer to learn via text than via video. So I thought I’d write a version of that video here to help others as well.

1. Getting the data

Firstly, you’ll need to make sure you have an API endpoint that you want to fetch data from. This could be a public API or one that you have access to through an API key. For this article we’ll use the Star Wars API.

Next, you will need to use the Fetch API in the form of the fetch() function to send a request to the API endpoint. The fetch() function is a built-in JavaScript function that allows you to send HTTP requests and retrieve responses from a server. It's a modern alternative to the older XMLHttpRequest and it's supported by most modern browsers.

To use the fetch() function, you simply pass it the URL of the API endpoint you want to fetch data from. For example:


The fetch() function returns a Promise, which means you can use the then() method, which takes two arguments: a success callback and an error callback.

const API_ENDPOINT = "";

.then(response => {
// handle the success case
return response.json();
.catch(error => {
// handle the error case

The then() method can get a bit cumbersome when working with multiple API requests, as it requires you to nest the calls inside each other. That's where the async/await syntax comes in handy.

2. Using async/await

The async/await syntax allows you to write asynchronous code that looks and behaves like synchronous code. It's essentially a shorthand way of working with Promises, and it makes it much easier to handle multiple API requests.

Richard Oliver Bray

Co-founder of Building digital products and teaching others to do the same. Saved by grace.