Working with the Requests Library
The requests library lets Python programs send HTTP requests to web servers and APIs, making it easy to fetch data from the internet.
What is the Requests Library?
requests is a third-party Python library that simplifies making HTTP calls (GET, POST, PUT, DELETE) to web servers and APIs. It is installed via pip install requests.
Making a GET Request
A GET request retrieves data from a server. The response object contains the status code, headers, and body.
Working with JSON
Most modern APIs return data in JSON format. The .json() method on a response converts the JSON body directly into a Python dictionary or list.
Status Codes
HTTP status codes tell you whether a request succeeded: 200 (OK), 201 (Created), 400 (Bad Request), 401 (Unauthorized), 404 (Not Found), 500 (Server Error). Always check response.status_code or use response.raise_for_status().
Query Parameters and Headers
You can pass query parameters with the params argument and custom headers (such as API keys or authentication tokens) with the headers argument.
POST Requests
POST requests send data to a server, typically to create a resource. Use the json or data argument to send a request body.
Timeouts and Error Handling
Always set a timeout to avoid hanging forever, and wrap requests in try/except to catch requests.exceptions.RequestException.