Python ยท Chapter 43 of 45

HTTP with requests

The `requests` library is the friendly HTTP client used by almost every Python project.

`requests.get(url)`, `requests.post(url, json=data)` return a Response with `.status_code`, `.text`, `.json()`.

GET and POST

GET fetches data; POST sends data. Pass `params=` for query strings, `json=` for JSON bodies, `headers=` for headers.

Handle errors

Check `resp.status_code` or call `resp.raise_for_status()` to raise on 4xx/5xx.

Example 1 (python)
import requests
resp = requests.get("https://api.github.com")
print(resp.status_code)
print(resp.json()["current_user_url"])
Output
200
https://api.github.com/user

GET a JSON API and parse the response.

Example 2 (python)
import requests
resp = requests.post("https://httpbin.org/post", json={"x": 1})
print(resp.json()["json"])
Output
{'x': 1}

POST a JSON body.

Key points

  • `pip install requests` first.
  • `get`, `post`, `put`, `delete` methods.
  • `resp.json()` parses JSON.
  • Always handle non-200 responses.
๐Ÿ’ก Note: For async code, use `httpx` (same API, supports both sync and async).

๐Ÿ“ Quick Quiz

1. Which parses a JSON response?

2. For a JSON body, pass:

3. Which raises on 4xx/5xx?