Web Development Basics
requests Library
HTTP library for Python, allowing clean and simple requests to be sent to external services.
Interview: Essential for consuming third-party API services, web scraping, and writing microservices in Python.
The requests library is the standard client-side library for sending HTTP requests in Python. It replaces the complex built-in urllib modules, providing an elegant "HTTP for Humans" API.
Core API Methods
The library provides quick functions matching all standard HTTP methods: requests.get(), requests.post(), requests.put(), requests.delete(), and requests.patch().
Handling Query Parameters and JSON
Instead of manually formatting url query strings (e.g. ?key=val), requests handles url-encoding automatically using the params dictionary. To send JSON payloads, utilize the json parameter, which sets the correct Content-Type: application/json header automatically.
Timeouts and Error Handling
Always set a timeout for production requests. If external servers hang, a python thread will block indefinitely without a timeout. To handle response statuses, call response.raise_for_status(), which raises an HTTPError for 4xx/5xx responses.
Use Cases
API Integration — Fetching and posting data to external services (like Stripe payments or Github APIs).
Microservices Communication — Sharing data between internal web services within a private cloud network.
Integration Testing — Writing scripts to programmatically verify that your local web API returns correct status codes and payloads.
Common Mistakes
Not specifying a timeout — Omitting the timeout parameter, which can cause the application to block indefinitely if the server is down.
Using data instead of json for JSON payloads — Passing dicts to `data` (which encodes them as form-data) instead of `json` (which encodes them as JSON).
Not calling raise_for_status() — Assuming requests throws errors automatically on bad response codes like 404 or 500 (it does not, you must manually check status_code or call raise_for_status()).