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.
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
- params for query strings, json= for bodies.
- raise_for_status turns errors into exceptions.
- Always set a timeout.
Code examples
Calling a public API
Requires requests and an internet connection; live data changes over time.
Sessions, headers and errors
api.example.com is a placeholder; substitute a real API and its documented authentication.
More examples
requests against a local test server
200 {'query': 'python books', 'page': 2}
201 Asha
404 False
HTTPError: 404Requires 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:
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
Prefer
A stalled server would block your program indefinitely.
Ignoring the status code
Avoid
Prefer
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
- 1Use requests with a public API you like and print three fields from the response.
- 2Wrap 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.