Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 3

Calling a Public JSON API from Python or TypeScript

Call GitHub's public REST API with httpx or fetch: query parameters, headers, an optional bearer token, a timeout, one careful retry and explicit handling of 4xx and 5xx responses.

Contentsand lesson path

What you will learn

  • Call a JSON API from code (Python with httpx in the reference stack, or JavaScript/TypeScript with fetch) with query parameters, headers, a bearer token and a timeout, handling 4xx and 5xx responses explicitly.

Prerequisites: Python Foundations

01. The problem

Your team writes a weekly newsletter about developer tools and wants a small command-line helper: given a GitHub topic such as http-client, print the three most-starred repositories with their star counts and links. GitHub's REST API has a search endpoint for exactly this. Written out as HTTP, the request we need looks like this:

The request the helper must send
GET /search/repositories?q=topic:http-client&sort=stars&order=desc&per_page=3
Host: api.github.com
Accept: application/vnd.github+json
X-GitHub-Api-Version: 2026-03-10
Authorization: Bearer <token>        (optional)

The endpoint works without an account, but anonymous callers get tight rate limits (10 search requests a minute at the time of writing); a personal access token raises them. A helper you can rely on has to do more than send the request. It should:

  • build the query string with the library, so values are encoded correctly;
  • send the headers GitHub asks for: the Accept media type and an API version;
  • read an optional token from an environment variable and send it as Authorization: Bearer …, never in the URL;
  • give up after a fixed time instead of hanging;
  • handle a rejected token (401), a refusal or rate limit (403 or 429), other client errors (4xx) and server errors (5xx) explicitly, each with a message a person can act on;
  • retry once, briefly, when the failure is likely to be temporary.

The same checklist fits any JSON API you call: a model provider's chat endpoint, a payment service or your own backend. Only the URL, the headers and the fields you keep change. We build it in Python with httpx first, then in TypeScript with fetch.

02. Step 1: Set up and describe the request in Python

Create a folder and a virtual environment, then install httpx. The code was tested with Python 3.13 and httpx 0.28.1.

Terminal
mkdir top-repos && cd top-repos
python3 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install httpx==0.28.1

Start top_repos.py with the headers. The token is optional: without it the call is anonymous, and with it GitHub applies your account's higher limits. Reading it from the environment keeps it out of your code, your repository and your shell history.

top_repos.py · part 1
import os
import sys
import time

import httpx

API = 'https://api.github.com'
RETRYABLE = {502, 503, 504}


def build_headers() -> dict[str, str]:
    headers = {
        'Accept': 'application/vnd.github+json',
        'X-GitHub-Api-Version': '2026-03-10',
    }
    token = os.environ.get('GITHUB_TOKEN')  # optional; never hard-code it
    if token:
        headers['Authorization'] = f'Bearer {token}'
    return headers

Next, the function that describes the call. An httpx.Client holds the settings shared by every request (base URL, headers, timeout) and reuses connections between requests.

  • params takes a dictionary and encodes it into the query string, so topic:http-client is sent as topic%3Ahttp-client, and a space, & or # inside a value cannot break the URL.
  • timeout=10.0 allows each phase of the request (connecting, sending, waiting for the response, waiting for a free pooled connection) up to ten seconds. httpx applies a five-second default even if you pass nothing, but writing the value states your intent. The older requests library, by contrast, waits indefinitely unless you pass a timeout.
  • The function keeps only the three fields the newsletter needs. The response has dozens more; copying out what you use keeps the rest of your code independent of them.
top_repos.py · part 2
def top_repos(topic: str, limit: int = 3) -> list[dict]:
    params = {
        'q': f'topic:{topic}',
        'sort': 'stars',
        'order': 'desc',
        'per_page': limit,
    }
    with httpx.Client(base_url=API, headers=build_headers(), timeout=10.0) as client:
        data = get_json(client, '/search/repositories', params)
    return [
        {'name': r['full_name'], 'stars': r['stargazers_count'], 'url': r['html_url']}
        for r in data['items']
    ]

03. Step 2: Turn status codes into decisions

httpx does not raise an exception just because the server answered 404 or 500. The request worked, and the status is information for you to act on. response.raise_for_status() turns any status outside 2xx into an httpx.HTTPStatusError, which carries the response as exc.response. That includes 3xx responses, because httpx does not follow redirects unless you pass follow_redirects=True.

Failures below HTTP are separate exceptions. When a phase runs past the timeout, httpx raises a subclass of httpx.TimeoutException, such as httpx.ConnectTimeout or httpx.ReadTimeout. get_json sends the request and decides what happens next:

top_repos.py · part 3
def get_json(client: httpx.Client, path: str, params: dict) -> dict:
    """GET a JSON resource. Retry once after a timeout or a 502/503/504."""
    for attempt in (1, 2):
        try:
            response = client.get(path, params=params)
        except httpx.TimeoutException:
            if attempt == 2:
                raise
            time.sleep(1)
            continue
        if response.status_code in RETRYABLE and attempt == 1:
            time.sleep(1)
            continue
        response.raise_for_status()  # any other non-2xx raises HTTPStatusError
        return response.json()
    raise AssertionError('unreachable')

The retry rule is deliberately narrow:

  1. The request is a GET, which is safe, so sending it twice can do no harm.
  2. Only failures that are likely to be temporary qualify: a timeout, 502 Bad Gateway, 503 Service Unavailable and 504 Gateway Timeout.
  3. There is exactly one retry after a one-second pause, so a broken service costs the user a few extra seconds at most.
  4. A 4xx response is not retried: most 4xx answers repeat for the same request, and a rate limit (403 or 429) needs a longer wait than one second.

If the second attempt also gets a 5xx, raise_for_status raises and the caller reports it. Production code often grows this into exponential backoff with random jitter that also honours Retry-After, but the decision about what to retry stays the same. Python looks up get_json only when top_repos runs, so the order of the two functions in the file does not matter.

04. Step 3: Report each failure in words a person can act on

The entry point catches the two exception families and explains them. Each group of 4xx codes gets its own message, because each needs a different fix: a new token, a pause, or a change to the request.

top_repos.py · part 4
def explain(status: int) -> str:
    if status == 401:
        return 'the token was rejected; check GITHUB_TOKEN'
    if status in (403, 429):
        return 'forbidden or rate-limited; wait, or authenticate for a higher limit'
    if 400 <= status < 500:
        return 'the request itself is wrong; fix it before trying again'
    return 'GitHub had a server error; try again later'


def main() -> int:
    topic = sys.argv[1] if len(sys.argv) > 1 else 'http-client'
    try:
        repos = top_repos(topic)
    except httpx.TimeoutException:
        print('GitHub did not answer in time, even after one retry.', file=sys.stderr)
        return 1
    except httpx.HTTPStatusError as exc:
        status = exc.response.status_code
        print(f'GitHub answered {status}: {explain(status)}', file=sys.stderr)
        return 1
    for repo in repos:
        print(f"{repo['stars']:>7}  {repo['name']}  {repo['url']}")
    return 0


if __name__ == '__main__':
    sys.exit(main())

GitHub answers 403 as well as 429 when a rate limit is exceeded, which is why the two share a message; many other APIs use 429 alone. Notice what the messages leave out: the token. Error output ends up in logs, terminals and screenshots, so report the status and the reason, never the credential.

Run the script anonymously, then with a deliberately wrong token to exercise the 401 branch. In PowerShell, set the variable first with $env:GITHUB_TOKEN = 'not-a-real-token' and remove it afterwards.

Terminal
python top_repos.py http-client
GITHUB_TOKEN=not-a-real-token python top_repos.py http-client
Illustrative output, October 2026 (star counts change over time)
 109302  axios/axios  https://github.com/axios/axios
  80637  hoppscotch/hoppscotch  https://github.com/hoppscotch/hoppscotch
  47697  usebruno/bruno  https://github.com/usebruno/bruno
GitHub answered 401: the token was rejected; check GITHUB_TOKEN

05. Step 4: The same client in TypeScript with fetch

fetch is built into browsers and into Node.js 18 and later, so no package is needed. Save the code below as top-repos.mts. Node.js 22.18 or later runs TypeScript files directly by stripping the types (node top-repos.mts); on older versions run npx tsx top-repos.mts. It was tested with Node.js 22.

top-repos.mts
const API = 'https://api.github.com';

interface Repo {
  name: string;
  stars: number;
  url: string;
}

class HttpError extends Error {
  status: number;
  constructor(status: number) {
    super(`HTTP ${status}`);
    this.status = status;
  }
}

function buildHeaders(): Record<string, string> {
  const headers: Record<string, string> = {
    Accept: 'application/vnd.github+json',
    'X-GitHub-Api-Version': '2026-03-10',
  };
  const token = process.env.GITHUB_TOKEN; // optional; never hard-code it
  if (token) headers.Authorization = `Bearer ${token}`;
  return headers;
}

async function topRepos(topic: string, limit = 3): Promise<Repo[]> {
  const url = new URL('/search/repositories', API);
  url.search = new URLSearchParams({
    q: `topic:${topic}`,
    sort: 'stars',
    order: 'desc',
    per_page: String(limit),
  }).toString();

  const response = await fetch(url, {
    headers: buildHeaders(),
    signal: AbortSignal.timeout(10_000), // rejects with a TimeoutError after 10 s
  });
  // fetch only rejects on network errors and aborts; a 4xx or 5xx still resolves
  if (!response.ok) throw new HttpError(response.status);

  const data = (await response.json()) as {
    items: { full_name: string; stargazers_count: number; html_url: string }[];
  };
  return data.items.map((r) => ({
    name: r.full_name,
    stars: r.stargazers_count,
    url: r.html_url,
  }));
}

function explain(status: number): string {
  if (status === 401) return 'the token was rejected; check GITHUB_TOKEN';
  if (status === 403 || status === 429) {
    return 'forbidden or rate-limited; wait, or authenticate for a higher limit';
  }
  if (status >= 400 && status < 500) {
    return 'the request itself is wrong; fix it before trying again';
  }
  return 'GitHub had a server error; try again later';
}

try {
  for (const repo of await topRepos(process.argv[2] ?? 'http-client')) {
    console.log(`${String(repo.stars).padStart(7)}  ${repo.name}  ${repo.url}`);
  }
} catch (err) {
  if (err instanceof HttpError) {
    console.error(`GitHub answered ${err.status}: ${explain(err.status)}`);
  } else if (err instanceof DOMException && err.name === 'TimeoutError') {
    console.error('GitHub did not answer in time.');
  } else {
    throw err; // DNS failure, refused connection, a bug in this code...
  }
  process.exitCode = 1;
}

Run it the same two ways as the Python version and you get the same output. Three differences from httpx matter:

  • fetch resolves for every HTTP status. The promise rejects only when no response arrives at all: a DNS failure, a refused connection or an abort. A 404 or a 500 resolves normally, so you must check response.ok, which is true only for statuses 200 to 299, and decide what to do yourself.
  • The timeout comes from an abort signal. AbortSignal.timeout(10_000) aborts the request after ten seconds, and the promise then rejects with a DOMException named TimeoutError. Without a signal, fetch in Node.js can wait for minutes.
  • The query string comes from URLSearchParams, which does the encoding that params did in httpx.

This version leaves out the retry to keep the comparison short; adding it means wrapping the fetch call in the same two-attempt loop. The code also runs in a browser for public data, but never put a personal or API token into code that ships to the browser, where anyone can read it in DevTools. Call keyed APIs from your server and send the browser only the result.

06. Common mistakes

07. Check your understanding

Practice check · 3 questions

How the clients report what happened

Questions about how httpx and fetch signal success and failure.

Q1. The TypeScript client above passes signal: AbortSignal.timeout(10_000). The server accepts the connection, then sends nothing for 30 seconds. What happens after 10 seconds?
Q2. In httpx, what does response.raise_for_status() do when the status is 404?
Q3. Why pass params={'q': 'topic:http client'} to httpx instead of typing ?q=topic:http client into the URL yourself?
Practice only: not graded, not saved, not evidence.

08. Apply it

Turn the helper into the first half of this skill's practice project. Choose a public JSON API that matters on your track: GitHub for developer tooling, a weather or exchange-rate API for a frontend, or your model provider's API if you already have a key (kept in an environment variable). Then:

  1. Keep only the fields you need and write them to results.json.
  2. Install HTTP/2 support with python -m pip install 'httpx[http2]', create the client with httpx.Client(http2=True, ...) and save response.http_version (for example HTTP/2) alongside the results.
  3. Leave certificate verification on, and test every error branch on purpose: a wrong token, a misspelt path that returns 404, and a tiny timeout such as timeout=0.001.

In the next lab you will serve results.json from an endpoint of your own. If you work in TypeScript, do the same with fetch and record the result of each branch.

09. Review prompt

Without looking back, list what a reliable API call needs (query parameters, headers, credentials, a timeout, status handling and a retry rule) and, for each one, write the httpx or fetch code that provides it. Then explain why fetch code needs an explicit response.ok check while httpx code usually calls raise_for_status(), and which failures you would retry and why.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check