In the world of web development and automation, APIs (Application Programming Interfaces) play a crucial role in enabling communication between different software applications. Python’s requests library is one of the most popular and user-friendly libraries for interacting with APIs. This blog will cover the basics, usage, and advanced features of the requests library.
What is the requests Library? 📜
The requests library in Python simplifies sending HTTP requests and handling responses. It is built on top of Python’s urllib but provides a more intuitive and human-friendly API.
Features of requests:
✅ Easy-to-use syntax
✅ Supports all HTTP methods
✅ Handles authentication and sessions
✅ Allows file uploads and streaming
✅ Supports JSON handling
Installing the requests Library 📦
Before using the requests library, you need to install it. Run the following command:
pip install requests
Once installed, you can import it into your Python scripts:
import requests
Making HTTP Requests 🌐
The requests library supports various HTTP methods, each serving different purposes. Let’s explore them with examples:
1. Sending a GET Request 🏗️
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
print(response.json())
2. Sending a POST Request 📨
url = "https://jsonplaceholder.typicode.com/posts"
data = {"title": "API Guide", "body": "Learning Python requests!", "userId": 1}
response = requests.post(url, json=data)
print(response.json())
3. Sending a PUT Request 🔄
url = "https://jsonplaceholder.typicode.com/posts/1"
data = {"id": 1, "title": "Updated Title", "body": "Updated content!", "userId": 1}
response = requests.put(url, json=data)
print(response.json())
4. Sending a DELETE Request ❌
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.delete(url)
print(response.status_code)
Handling Query Parameters 🔍
Query parameters help filter or modify API responses. They are passed using the params argument in the request.
url = "https://jsonplaceholder.typicode.com/posts"
params = {"userId": 1}
response = requests.get(url, params=params)
print(response.json())
Handling JSON Data 📜
The requests library provides built-in support for JSON data.
Parsing JSON Response
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
data = response.json()
print(data["title"])
Sending JSON Data
headers = {"Content-Type": "application/json"}
data = {"name": "Vikram", "job": "Developer"}
response = requests.post("https://reqres.in/api/users", json=data, headers=headers)
print(response.json())
Handling Authentication 🔑
Some APIs require authentication, which requests supports seamlessly.
Basic Authentication
url = "https://httpbin.org/basic-auth/user/pass"
response = requests.get(url, auth=("user", "pass"))
print(response.status_code)
Token-based Authentication
headers = {"Authorization": "Bearer YOUR_ACCESS_TOKEN"}
response = requests.get("https://api.example.com/protected", headers=headers)
print(response.json())
Handling Headers 📜
Adding custom headers can be useful for authentication, content type, or API versioning.
headers = {"User-Agent": "MyApp", "Accept": "application/json"}
response = requests.get("https://api.github.com", headers=headers)
print(response.json())
Uploading Files 📂
Some APIs require file uploads, which can be handled using requests.
url = "https://httpbin.org/post"
files = {"file": open("test.txt", "rb")}
response = requests.post(url, files=files)
print(response.json())
Handling Timeouts ⏳
To prevent infinite waiting, you can set timeouts.
url = "https://httpbin.org/delay/5"
try:
response = requests.get(url, timeout=3)
print(response.json())
except requests.exceptions.Timeout:
print("Request timed out")
Error Handling 🚨
Proper error handling ensures smooth API interactions.
try:
response = requests.get("https://jsonplaceholder.typicode.com/invalid-url")
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(f"HTTP error: {err}")
except requests.exceptions.ConnectionError:
print("Connection error")
except requests.exceptions.Timeout:
print("Timeout error")
except requests.exceptions.RequestException as err:
print(f"Something went wrong: {err}")
Summary Table 📊
| HTTP Method | Description | Example |
|---|---|---|
| GET | Fetch data from API | requests.get(url) |
| POST | Submit data to API | requests.post(url, json=data) |
| PUT | Update existing data | requests.put(url, json=data) |
| DELETE | Remove data | requests.delete(url) |
| HEAD | Fetch headers only | requests.head(url) |
| OPTIONS | Fetch allowed methods | requests.options(url) |
Conclusion 🎯
The requests library in Python is an essential tool for interacting with APIs, making HTTP requests simple and efficient. By mastering requests, you can seamlessly integrate APIs into your applications, automate tasks, and enhance your Python projects.
