The requests module in Python is a powerful library used to make HTTP requests. It simplifies working with web APIs, downloading content, and sending data over the internet using methods like GET and POST.
GET (fetch data) and POST (send data).params.raise_for_status() to handle failures safely.A typical HTTP request using requests follows this pattern:
import requests
url = "https://example.com"
params = {"q": "python"}
headers = {"User-Agent": "MyApp/1.0"}
response = requests.get(url, params=params, headers=headers)
print(response.status_code) # HTTP status code
print(response.text) # Response body as text
Install the requests module using pip:
pip install requests # Install the requests package
GET requests are used to fetch data from a URL.
import requests
# Send a GET request to the GitHub API root
response = requests.get("https://api.github.com")
# Print the HTTP status code
print(response.status_code)
# Print the response body as text
print(response.text)
POST requests are used to send data to a server.
import requests
# Data that will be sent in the POST request body
payload = {"username": "test", "password": "12345"}
# Send a POST request with form data
response = requests.post("https://httpbin.org/post", data=payload)
# Print the HTTP status code
print(response.status_code)
# Parse and print the JSON response
print(response.json())
The response object provides status, headers, and the response body.
import requests
response = requests.get("https://api.github.com")
print("Status Code:", response.status_code)
print("Headers:", response.headers)
print("Content:", response.text[:100]) # First 100 characters
Use the params argument to send query parameters in a GET request.
import requests
# Query parameters to send in the URL
params = {"q": "python", "page": 1}
# Send GET request with query parameters
response = requests.get("https://httpbin.org/get", params=params)
# Final URL with encoded query string
print(response.url)
# JSON body of the response
print(response.json())
Some APIs require custom headers like User-Agent or Authorization.
import requests
# Custom headers sent with the request
headers = {"User-Agent": "MyApp/1.0"}
# Send GET request including custom headers
response = requests.get("https://httpbin.org/headers", headers=headers)
# JSON response showing the headers the server received
print(response.json())
Always check for errors to avoid crashes due to failed requests.
import requests
try:
response = requests.get("https://api.github.com/unknown")
response.raise_for_status() # Raise exception for HTTP errors
except requests.exceptions.HTTPError as err:
print("HTTP Error:", err)
except requests.exceptions.RequestException as e:
print("Error:", e)
response.status_code might print 200 for success, 404 for not found, etc.response.text contains the raw HTML or JSON string returned by the server.response.json() parses JSON into a Python dictionary, which is easier to work with.raise_for_status() is called on a non-2xx status, an exception will be raised.Use these properties to validate that a request succeeded before processing the data further.
response.json() to parse JSON responses from APIs.response.status_code or use raise_for_status() before processing data.params for GET queries and data or json for POST requests.requests.Session() to reuse connections efficiently.https://httpbin.org/get and print the JSON response.https://httpbin.org/post and inspect the result.User-Agent) and verify them in the response.try/except.params in GET requests and observe how the URL changes.