agyanadda@gmail.com

Python requests: Working with APIs

Advanced Python 1 min read Updated Dec 4, 2026 Topic 30 of 32

requests is the most popular Python library for HTTP: pip install requests.

GET

r = requests.get(url, params={"q": "python"}, timeout=10)

  • r.status_code — 200, 404, ...
  • r.json() — parse JSON
  • r.text — raw text
  • r.headers

POST

requests.post(url, json={"name": "Asha"}) — sends JSON with the right header. Use data= for form data and files= for uploads.

Headers and auth

headers={"Authorization": f"Bearer {token}"}. Keep tokens in environment variables.

Errors

  • Always set a timeout — without one, a request can hang forever
  • r.raise_for_status() raises an error for 4xx/5xx
  • Catch requests.exceptions.RequestException

Sessions

requests.Session() reuses connections and shared headers — faster for many requests.

Async alternatives: httpx and aiohttp.

Example

Example — Fetch and post data Python
import os
import requests

BASE = "https://jsonplaceholder.typicode.com"

try:
    r = requests.get(f"{BASE}/posts", params={"userId": 1}, timeout=10)
    r.raise_for_status()
    posts = r.json()
    print(f"User 1 has {len(posts)} posts. First: {posts[0]['title'][:30]}...")

    new = requests.post(
        f"{BASE}/posts",
        json={"title": "Hello", "body": "From Python", "userId": 1},
        headers={"Authorization": f"Bearer {os.getenv('API_TOKEN', '')}"},
        timeout=10,
    )
    print(new.status_code, new.json()["id"])

    missing = requests.get(f"{BASE}/posts/99999", timeout=10)
    missing.raise_for_status()
except requests.exceptions.HTTPError as e:
    print("HTTP error:", e.response.status_code)
except requests.exceptions.RequestException as e:
    print("Network problem:", e)

Prints "User 1 has 10 posts. First: sunt aut facere...", then 201 101 for the created post, and finally HTTP error: 404 for the missing post.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which argument sends a Python dict as a JSON body?

Exercise 2 True / False

Without a timeout, a requests call can wait forever.

Exercise 3 Fill in the Blank

Raise an error for 4xx/5xx responses with r.raise_for()

Frequently Asked Questions

requests is simple and widely used for normal scripts. httpx has almost the same API and also supports async and HTTP/2, which is useful in async web apps such as FastAPI.