Find a course

Module 4: Using Real APIsLesson 10 of 1215 min

Calling APIs from Code

Make real API calls with curl, JavaScript fetch and Python requests, handle errors and timeouts correctly, and retry failed calls with exponential backoff.

Step 1 of 13Learn

Your first calls: curl and fetch

The quickest way to try an endpoint is curl, a command-line tool included with macOS, Linux and current versions of Windows:

curl -i "https://api.example.com/v1/books?limit=2"

curl -X POST "https://api.example.com/v1/books" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"title": "Tide Lines", "author": "M. Haddad"}'

-i shows response headers, -X sets the method, -H adds a header and -d sends a body. Graphical tools such as Postman, Insomnia or the "REST client" extensions for code editors do the same with forms and saved collections of requests.

In JavaScript, browsers and Node.js provide fetch:

async function getBooks() {
  const res = await fetch('https://api.example.com/v1/books?limit=2', {
    headers: { 'Accept': 'application/json' }
  });
  if (!res.ok) throw new Error('HTTP ' + res.status);
  const data = await res.json();
  return data;
}

Network calls take time, from a few milliseconds to several seconds, so fetch is asynchronous: it returns a Promise, and await pauses the function until the response arrives without freezing the rest of the program. Two awaits are needed: one for the response headers and status, one (res.json()) for the full body to arrive and be parsed.

Step 2 of 13Practice · Fill in the blanks

Fill in the blanks

In curl, the option sets the HTTP method, adds a header, and sends a request body.

Step 3 of 13Learn

The same call in Python

In Python, the third-party requests library is the most popular way to call APIs (install it with pip install requests):

import requests

resp = requests.get(
    "https://api.example.com/v1/books",
    params={"limit": 2, "q": "river"},          # encoded for you
    headers={"Authorization": f"Bearer {token}"},
    timeout=10,                                  # seconds
)
resp.raise_for_status()      # raises an exception for 4xx and 5xx
books = resp.json()

new = requests.post(
    "https://api.example.com/v1/books",
    json={"title": "Tide Lines"},                # serialized + Content-Type set
    timeout=10,
)
print(new.status_code)       # e.g. 201

Notice three conveniences: params builds and encodes the query string, json= serializes the body and sets the Content-Type header, and raise_for_status() turns error statuses into exceptions.

And one essential argument: timeout. Without it, requests may wait indefinitely for a server that never answers, hanging your script. Always set a timeout on network calls, in every language. In JavaScript, fetch has no timeout option of its own, but you can pass signal: AbortSignal.timeout(10000) to cancel after 10 seconds.

Python also includes urllib.request in the standard library, and the newer httpx library offers a requests-like API with async support.

Step 4 of 13Practice · Spot the mistake

This Python script should fetch open tickets safely. Click the lines with problems.

Step 5 of 13Compare

The same POST in three tools

AspectcurlJavaScript fetchPython requests
Method-X POSTmethod: "POST"requests.post(...)
Header-H "Authorization: Bearer T"headers: { Authorization: ... }headers={"Authorization": ...}
JSON body-d '{"title":"x"}'body: JSON.stringify(obj)json=obj
HTTP errorsShown with -i; exit code 0No throw: check res.okNo raise: call raise_for_status()

Step 6 of 13Learn

Retries with exponential backoff

Some failures are temporary: a 503 during a deployment, a 429 rate limit, a dropped connection. Retrying helps, but how you retry matters. If ten thousand clients all retry immediately and repeatedly, they hammer a struggling server and keep it down.

The standard approach is exponential backoff: wait longer after each failed attempt, doubling the delay each time.

attempt 1 fails → wait 1 s
attempt 2 fails → wait 2 s
attempt 3 fails → wait 4 s
attempt 4 fails → wait 8 s
attempt 5 fails → give up and report the error

The delay before retry number n is base × 2n−1, usually with a maximum cap (say 30 seconds) and a maximum number of attempts.

Real implementations add jitter: a random variation in each delay, so thousands of clients that failed at the same moment don't all retry at the same moment too. A common version picks a random delay between 0 and the computed backoff.

Rules that keep retries safe:

  • Retry only temporary failures: network errors, 429, 502, 503, 504 and usually 500.
  • Never retry 400, 401 (without refreshing credentials), 403, 404 or 422.
  • Retry idempotent requests freely; retry POST only with an idempotency key.
  • If the server sends Retry-After, wait at least that long.

Step 7 of 13Explore

Exponential backoff explorer

The curve shows the wait before each retry attempt. Change the base delay and the cap to see how quickly the delay grows and where it levels off.

0255075100 246810
Wait before retry 5
16 s
Total wait over 6 retries
61 s

Step 8 of 13Practice · Work it out

A client uses exponential backoff with a base delay of 0.5 seconds and no cap. How many seconds does it wait before retry number 5?

Step 9 of 13Practice · Code challenge

Write backoffDelay(attempt, base, cap) that returns the wait in seconds before retry number attempt (starting at 1): base × 2^(attempt − 1), but never more than cap.

Runs in a sandbox in your browser.
  • backoffDelay(1, 1, 30)
  • backoffDelay(4, 1, 30)
  • backoffDelay(3, 0.5, 30)
  • backoffDelay(7, 1, 30)
  • backoffDelay(10, 2, 60)

Step 10 of 13Tap to reveal

A checklist for every API call in production code

  1. Set a timeout

    Never wait forever. Pick a timeout that matches what the user or job can tolerate, often 5–30 seconds.

  2. Check the status

    Treat only 2xx as success. fetch does not throw on 4xx or 5xx, so test res.ok.

  3. Parse defensively

    Expect missing fields, nulls and occasionally non-JSON bodies such as HTML error pages.

  4. Retry wisely

    Retry only temporary failures, with exponential backoff, jitter, a cap and a maximum number of attempts.

  5. Log what matters

    Record the method, URL (without secrets), status and timing of failures so problems can be diagnosed later.

Step 11 of 13Learn

Testing code that calls APIs

Code that calls real APIs is awkward to test: the network is slow, the service may be down, test calls may cost money or create real records, and responses change over time. Professional teams handle this in layers.

  • Unit tests with fakes. Wrap API calls in your own small client module, such as weatherClient.getForecast(city), and in unit tests replace it with a fake that returns fixed JSON. Your parsing, error handling and business logic get tested in milliseconds.
  • Recorded responses. Tools can record real HTTP responses once and replay them in tests, so tests stay realistic without hitting the network every time.
  • Mock servers. A local server generated from the API's OpenAPI description answers with example data, which is useful for front-end work before the real back end exists.
  • Sandbox environments. Many providers, especially payment companies, offer a sandbox with test keys where nothing is real: test card numbers succeed or fail on purpose so you can exercise every path.
  • A few end-to-end checks. A small number of tests against the real staging service catch contract changes that fakes would miss.

Also test the unhappy paths deliberately: timeouts, 429s, 500s, malformed JSON and empty lists. That's where most production bugs hide.

Step 12 of 13Practice · Sort into groups

Which testing approach is described?

Tap an item, then tap its group (or drag it there).

Step 13 of 13Practice · Choose one

Why do production retry strategies add random jitter to exponential backoff delays?