pyodide: loading…

[concept]Web & APIs

Requests Basics

# theory

fetching: requests vs pyfetch

In a regular Python script you use the requests library:

import requests

response = requests.get("https://api.example.com/data")
print(response.status_code)
print(response.json())

This site runs Python in a browser Web Worker via Pyodide, so the network goes through the browser's fetch instead. The Pyodide-native wrapper is pyodide.http.pyfetch:

from pyodide.http import pyfetch

response = await pyfetch("https://jsonplaceholder.typicode.com/users/1")
print(response.status)
data = await response.json()
print(data)

Same shape, two differences worth knowing:

  • It's async. You must await both the fetch and .json().
  • It runs from the browser, so the target API has to send CORS headers. Sites that don't, you can't reach directly.

When you ship a real script you'll write requests.get. The patterns translate.

status, json, errors

response = await pyfetch(url)

response.status     # 200, 404, 500 ...
response.ok         # True if status < 400
await response.string()  # raw text
await response.json()    # parsed JSON

Handle failures explicitly. Network errors raise; bad status codes don't:

try:
    response = await pyfetch(url)
    if response.status >= 400:
        print(f"HTTP {response.status}")
    else:
        data = await response.json()
except Exception as e:
    print(f"request failed: {e}")

query params

pyfetch doesn't have a params= keyword like requests does. Build the query string yourself:

from urllib.parse import urlencode

params = {"userId": 1}
url = f"https://jsonplaceholder.typicode.com/posts?{urlencode(params)}"
response = await pyfetch(url)
posts = await response.json()
print(f"{len(posts)} posts for user 1")

public test API

Examples below hit jsonplaceholder.typicode.com. It's a free, CORS-friendly fake API with users, posts, comments, todos. Real HTTP, real JSON, no auth required. Good for practice without spinning up your own backend.

# examples [3]

# example 01 · fetch a real JSON response

Hit a public CORS-friendly API and read the response. Real HTTP, real status code, real JSON.

1
2
3
4
5
6
7
8
9
10
🐍
Loading PythonSetting up pandas & numpy...
# example 02 · fetch a list and aggregate

GET a collection, parse it, do real work on it. Same pattern you'd use with a paginated production API.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
🐍
Loading PythonSetting up pandas & numpy...
# example 03 · handle an explicit 404

Hit a URL that returns 404. response.ok is False; nothing raises. You check.

1
2
3
4
5
6
7
8
9
10
11
🐍
Loading PythonSetting up pandas & numpy...

# challenges [2]

# challenge 01/02todo
Fetch https://jsonplaceholder.typicode.com/users/2 and print exactly the user's email address (the value of the 'email' field, no extra prefix).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
🐍
Loading PythonSetting up pandas & numpy...
# challenge 02/02todo
Fetch all posts from https://jsonplaceholder.typicode.com/posts and print exactly one line: 'total posts: N' where N is the actual count.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
🐍
Loading PythonSetting up pandas & numpy...

# project

# project-challenge

thread: Sales Performance Dashboard · reward: 50 xp

# brief

The inventory system returns sales data via an API. Process the simulated API response to extract sales records and calculate summary statistics.

# task

Process Sales API Response

# your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
🐍
Loading PythonSetting up pandas & numpy...