The requests library is the easiest way to interact with web APIs and download data from the internet. It handles many details automatically.
Installing requests
First, install the library (only once):
pip install requests
Importing the library
import requests
Making a GET request
GET is used to retrieve data.
response = requests.get("https://api.github.com")
print(response.status_code) # 200 means success
print(response.text) # Raw text response
Convert JSON responses easily:
data = response.json()
print(data["current_user_url"])
Passing parameters
Add query parameters with params:
params = {"q": "python", "sort": "stars"}
response = requests.get("https://api.github.com/search/repositories", params=params)
repos = response.json()
print(repos["total_count"]) # Number of results
Making a POST request
POST is used to send data (e.g., create something).
payload = {"username": "testuser", "score": 100}
response = requests.post("https://httpbin.org/post", json=payload)
print(response.json()["json"]) # Echoed back data
Adding headers
Set custom headers (common for authentication):
headers = {"User-Agent": "my-script", "Authorization": "token abc123"}
response = requests.get("https://api.example.com/data", headers=headers)
Handling responses
Check status:
if response.status_code == 200:
print("Success!")
elif response.status_code == 404:
print("Not found.")
Raise an exception for bad status (optional):
response.raise_for_status() # Raises error for 4xx/5xx
Simple examples
Fetch a random quote:
response = requests.get("https://api.quotable.io/random")
quote = response.json()
print(f'"{quote["content"]}" — {quote["author"]}')
Download an image:
img_response = requests.get("https://httpbin.org/image/png")
with open("downloaded.png", "wb") as file:
file.write(img_response.content)
Important notes
- Always check
response.status_code. - Use
.json()for JSON APIs. - Use
json=parameter to send JSON in POST. - Handle network errors with try/except.
- Respect API rate limits and terms of service.
Quick summary
- Import with
import requests. - Use
get()for retrieving data,post()for sending. - Pass parameters with
params=, data withjson=ordata=. - Convert JSON with
.json(). - Check
status_codeand useraise_for_status().
Practice making requests to free APIs like quotable.io or jsonplaceholder.typicode.com. The requests library is essential for working with web services in Python programs.
Top comments (0)