The requests library in Python is a powerful and user-friendly HTTP library for sending HTTP/1.1 requests. It abstracts the complexities of making requests and handling responses, making it easier to work with web APIs and HTTP communication.
To use the requests library, install it using the following command:
uv add requestsThe requests library allows you to send various types of HTTP requests:
A GET request retrieves data from a specified URL.
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.json()) # JSON responserequests.get(url): Sends aGETrequest..json(): Converts the response to JSON format.
A POST request is used to send data to a server.
import requests
data = {"title": "foo", "body": "bar", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)
print(response.json())requests.post(url, json=data): Sends aPOSTrequest with JSON data..json(): Parses the JSON response.
A PUT request updates an existing resource.
import requests
data = {"title": "updated title", "body": "updated body", "userId": 1}
response = requests.put("https://jsonplaceholder.typicode.com/posts/1", json=data)
print(response.json())requests.put(url, json=data): Sends aPUTrequest to update a resource.
A DELETE request removes a resource.
import requests
response = requests.delete("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code) # 200 indicates successrequests.delete(url): Sends aDELETErequest..status_code: Returns the HTTP status code.
The requests library provides response objects with useful attributes:
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code) # HTTP status code
print(response.headers) # Response headers
print(response.text) # Raw response text
print(response.json()) # JSON responseCustom headers can be included in a request:
headers = {"Authorization": "Bearer my_token"}
response = requests.get("https://api.example.com/data", headers=headers)Timeouts prevent hanging requests:
response = requests.get("https://jsonplaceholder.typicode.com/posts", timeout=5) # 5 seconds timeoutTo handle request failures, use exception handling:
import requests
try:
response = requests.get("https://invalid-url.com", timeout=5)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")requests.get(),requests.post(),requests.put(),requests.delete()for HTTP requests.- Response objects contain status codes, headers, text, and JSON data.
- Custom headers can be included in requests.
- Timeouts and exception handling improve reliability.
Refer to the Technical Notes Guidelines for formatting and best practices.