Async, API & Integration

contain

What is an API?

API = Application Programming Interface

A way for programs to talk to each other

Think of it like a restaurant:

  • Menu (API Documentation) - shows what you can order
  • Waiter (API) - takes your request, brings back food
  • Kitchen (Server) - prepares what you ordered

You don't need to know how the kitchen works!

Web APIs

Common APIs you might use:

API What it provides
Weather API Current weather, forecasts
GitHub API Repository data, user info
Movie API Movie details, ratings
Currency API Exchange rates

Your browser already uses APIs constantly (loading tweets, checking email, etc.)

How APIs Work

Your Website               API Server
    |                            |
    |--- Request: "weather?"  ---|
    |                            |
    |<-- Response: "{temp:75}" --|
    |                            |
  1. You request data
  2. Server processes request
  3. Server responds with data (usually JSON)

JSON: The Language of APIs

What is JSON?

JSON = JavaScript Object Notation. A text format for data.

{
  "name": "Alice",
  "age": 20,
  "courses": ["OIM3690", "OIM3640"],
  "active": true
}
  • Keys must be in double quotes
  • Values can be: strings, numbers, booleans, arrays, objects, null
  • Looks like JavaScript objects, works everywhere

Fetching Data with fetch()

Your First fetch()

fetch() is built into every browser. Let's try it:

const response = await fetch('https://oim.108122.xyz/words/random');
const word = await response.json();
console.log(word); // a random word!

Three steps: fetch the URL, convert to JSON, use the data.

Why await? Fetching data takes time (network delay). await says "wait here until the data arrives."

Why Do We Need await?

// WITHOUT await - broken!
const response = fetch('https://oim.108122.xyz/words/random');
console.log(response); // Promise { <pending> } - not the data!

// WITH await - works!
const response = await fetch('https://oim.108122.xyz/words/random');
const word = await response.json();
console.log(word); // "walked"

Network requests are asynchronous. The code doesn't stop and wait unless you tell it to.

async Functions

await can only be used inside an async function:

async function getRandomWord() {
  const response = await fetch('https://oim.108122.xyz/words/random');
  const word = await response.json();
  document.querySelector('#result').textContent = word;
}

getRandomWord();
  • async before function: marks it as asynchronous
  • await before fetch/json: pauses until data arrives

Handling Errors with try/catch

APIs can fail: network down, server errors, bad URL.

async function getRandomWord() {
  try {
    const response = await fetch('https://oim.108122.xyz/words/random');
    const word = await response.json();
    document.querySelector('#result').textContent = word;
  } catch (error) {
    document.querySelector('#result').textContent = 'Failed to load';
    console.error('Error:', error);
  }
}

Always wrap fetch in try/catch!

Live Demo: OIM Teaching API

Try It: Random Word

Open your browser console (F12) and paste:

const response = await fetch('https://oim.108122.xyz/words/random');
const word = await response.json();
console.log(word);

Run it a few times. You get a different word each time!

API docs: oim.108122.xyz/docs

Working with Rich API Data

async function showTowns() {
  const response = await fetch('https://oim.108122.xyz/mass');
  const data = await response.json();

  console.log(data.name);      // 'Massachusetts'
  console.log(data.governor);  // 'Maura Healey'

  for (const town of data.data) {
    console.log(`${town.name}: pop ${town.population}`);
  }
}

Nested JSON: objects inside arrays inside objects.

Displaying API Data on the Page

async function showTowns() {
  const response = await fetch('https://oim.108122.xyz/mass');
  const data = await response.json();

  const list = document.querySelector('#town-list');

  for (const town of data.data.slice(0, 10)) {
    const li = document.createElement('li');
    li.textContent = `${town.name} (${town.county}) - pop ${town.population.toLocaleString()}`;
    list.appendChild(li);
  }
}

This is the same loop + DOM pattern from last session, now with real data!

Posting to the Message Board

Sending data uses fetch with extra options:

async function postMessage(text) {
  const response = await fetch('https://oim.108122.xyz/message', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Token': 'alicealice'  // your first name x2
    },
    body: JSON.stringify({ message: text })
  });
  const result = await response.json();
  console.log(result);
}

postMessage('Hello from Alice!');

GET vs POST

// GET: read/fetch data (default)
await fetch('https://oim.108122.xyz/words/random');

// POST: send/submit data
await fetch('https://oim.108122.xyz/message', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ message: 'Hello!' })
});
  • GET = "give me data" (reading)
  • POST = "here's some data" (writing)

Building an Interactive App

Pattern: Search + Display

async function findTown() {
  const search = document.querySelector('#search').value.toLowerCase();
  const response = await fetch('https://oim.108122.xyz/mass');
  const data = await response.json();

  const matches = [];
  for (const town of data.data) {
    if (town.name.toLowerCase().includes(search)) {
      matches.push(town);
    }
  }

  displayResults(matches);
}

Pattern: Loading State

Show the user something is happening:

async function loadData() {
  const result = document.querySelector('#result');
  result.textContent = 'Loading...';

  try {
    const response = await fetch('https://oim.108122.xyz/mass');
    const data = await response.json();
    result.textContent = `Found ${data.data.length} towns`;
  } catch (error) {
    result.textContent = 'Error loading data';
  }
}

Public APIs to Explore

API URL No key needed
OIM Teaching API oim.108122.xyz/docs Yes
JokeAPI v2.jokeapi.dev Yes
CoinDesk data-api.coindesk.com Yes
Advice Slip api.adviceslip.com Yes
Dog API dog.ceo/dog-api Yes
OpenWeather openweathermap.org/api Free key

Important Notes

  1. CORS: Some APIs block browser requests (security). Stick to APIs that allow it.
  2. API Keys: Some APIs need a key. Never commit keys to GitHub!
  3. Rate Limits: Don't spam requests (most APIs limit calls per minute)
  4. Read the Docs: Every API is different. Check the documentation first.

References