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
Requestcarries the URL and headers.urlopensends it;readreturns the body bytes.json.loadsparses the decoded response.
Keywords and builtins used here
asforwith
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.
Step 1 of 4 in Web, step 10 of 41 in Domain tools.