API Integration Lesson

Start

API integration means connecting a program to another service to request or send data. In a web app, this usually happens with fetch, which sends a request to a URL and waits for a response.

Build

Many APIs return JSON, so the program must convert the response into JavaScript data before using it. After that, the data can be read like any other object or array.

Code Runner Challenge

API Integration Lesson

View IPYNB Source
%%js

// CODE_RUNNER: API Integration Lesson

async function loadProfile() {
  const response = await fetch("/api/profile");
  const profile = await response.json();

  console.log("Username: " + profile.username);
  console.log("Level: " + profile.level);
}

loadProfile();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Observe

API code should be written carefully because the program depends on something outside itself. The request might be slow, the server might fail, or the returned data might not match what the page expects.