typestar

urllib GET requests in Python

Fetching JSON from an API with the standard library.

import json
import urllib.request

url = "https://api.example.com/repos?page=1"
req = urllib.request.Request(url, headers={"Accept": "application/json"})

with urllib.request.urlopen(req, timeout=10) as res:
    status = res.status
    body = res.read().decode()

repos = json.loads(body)
names = [r["name"] for r in repos]

How it works

  1. Request carries the URL and headers.
  2. urlopen sends it; read returns the body bytes.
  3. json.loads parses the decoded response.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
315
Tokens
87
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 52 seconds.

Type this snippet

Step 1 of 4 in Web, step 10 of 41 in Domain tools.

← Previous Next →