Skip to content

Module 16 · External Libraries and APIs — topic 8 of 12

Requests introduction

HTTP made easy with requests: GET and POST, query parameters, JSON bodies and responses, status codes and raise_for_status, headers, timeouts, sessions and error handling.

Beginner 10 min read·Lesson 242 of 306 in Python Programming

Learning objectives

  • Send GET and POST requests with requests
  • Read status codes, headers and JSON
  • Handle errors and always set timeouts

Definition

requests is a popular third-party library for making HTTP requests. It wraps the details of URLs, headers, encodings and JSON in a simple API: requests.get(url), requests.post(url, json=data).

Introduction

Weather, exchange rates, GitHub repositories, payment gateways — most online services offer HTTP APIs. requests is the friendliest way to talk to them from Python.

Why it matters

requests removes boilerplate compared with urllib, and its patterns (timeouts, raise_for_status, sessions) are what professional code uses.

Detailed explanation

Install with python -m pip install requests.

requests.get(url, params={...}) sends a GET with an encoded query string; requests.post(url, json=data) sends a JSON body and sets the Content-Type header.

The Response has status_code, ok (True for codes below 400), headers, text, content (bytes) and json() for parsed JSON.

r.raise_for_status() raises requests.HTTPError for 4xx and 5xx responses, turning HTTP errors into exceptions.

Always pass timeout= (seconds). Without it, a request to an unresponsive server can wait forever.

requests.Session reuses connections and shares headers or cookies across requests — faster and tidier for several calls to one API.

Network problems raise requests.ConnectionError or requests.Timeout; catch requests.RequestException to handle all of them.

Keep API keys out of code: read them from environment variables and send them in headers.

Syntax

Python
import requests
r = requests.get("https://api.example.com/items", params={"page": 2}, timeout=10)
r.raise_for_status()
data = r.json()
r = requests.post("https://api.example.com/items", json={"name": "pen"}, timeout=10)
  • params for query strings, json= for bodies.
  • raise_for_status turns errors into exceptions.
  • Always set a timeout.

Code examples

Calling a public API

Python
import requests
r = requests.get("https://api.github.com/repos/python/cpython", timeout=10)
r.raise_for_status()
repo = r.json()
print(repo["full_name"], repo["stargazers_count"] > 0)

Requires requests and an internet connection; live data changes over time.

Sessions, headers and errors

Python
import os
import requests
session = requests.Session()
session.headers.update({"Authorization": f"Bearer {os.environ.get('API_TOKEN', '')}"})
try:
r = session.get("https://api.example.com/v1/orders", params={"status": "open"}, timeout=10)
r.raise_for_status()
print(len(r.json()), "open orders")
except requests.Timeout:
print("the server took too long")
except requests.RequestException as e:
print("request failed:", e)

api.example.com is a placeholder; substitute a real API and its documented authentication.

More examples

requests against a local test server

Python
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
import requests
class Echo(BaseHTTPRequestHandler):
def send_json(self, status, data):
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
url = urlparse(self.path)
if url.path == "/search":
q = parse_qs(url.query)
self.send_json(200, {"query": q["q"][0], "page": int(q["page"][0])})
else:
self.send_json(404, {"error": "not found"})
def do_POST(self):
payload = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
self.send_json(201, {"created": payload["name"]})
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), Echo)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_port}"
r = requests.get(f"{base}/search", params={"q": "python books", "page": 2}, timeout=5)
print(r.status_code, r.json())
r = requests.post(f"{base}/users", json={"name": "Asha"}, timeout=5)
print(r.status_code, r.json()["created"])
r = requests.get(f"{base}/nothing", timeout=5)
print(r.status_code, r.ok)
try:
r.raise_for_status()
except requests.HTTPError as e:
print("HTTPError:", e.response.status_code)
server.shutdown()
Output
200 {'query': 'python books', 'page': 2}
201 Asha
404 False
HTTPError: 404

Requires requests. The tiny server runs on your own computer, so no internet connection is needed.

Step-by-step explanation

  • params builds the query string ?q=python+books&page=2 automatically.
  • json= serialises the dictionary and sets the JSON content type; the server replies 201 Created.
  • A 404 response doesn't raise by itself — r.ok is False — until raise_for_status turns it into an HTTPError.

Expected output

Running “requests against a local test server” prints exactly:

TextOutput
200 {'query': 'python books', 'page': 2}
201 Asha
404 False
HTTPError: 404

Practical applications

  • Fetching exchange rates or weather data.
  • Integrating with payment, messaging and cloud APIs.

Best practices

  • Always set timeouts.
  • Call raise_for_status before using data.
  • Use sessions for repeated calls and env vars for secrets.

Common mistakes

No timeout

Avoid

requests.get(url)

Prefer

requests.get(url, timeout=10)

A stalled server would block your program indefinitely.

Ignoring the status code

Avoid

data = requests.get(url, timeout=10).json()

Prefer

r = requests.get(url, timeout=10)
r.raise_for_status()
data = r.json()

Error responses often contain error JSON that your code would misread as data.

Important notes

  • httpx offers a requests-like API with async support.

Key takeaways

  • requests.get/post send HTTP requests.
  • Responses give status, headers and json().
  • Use timeouts, raise_for_status and exception handling.

Try it yourself

  1. 1
    Use requests with a public API you like and print three fields from the response.
  2. 2
    Wrap a GET call in a function that retries up to three times on timeouts.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

Test yourself across the whole course in the Python practice bank.