1. Library Overview
In our digital lives, we interact with various web services daily: checking the weather, mobile payments, social media, etc. These services rely on the HTTP protocol for data transmission. The Python Requests library is a powerful tool that simplifies HTTP communication by hiding the complexities of low-level socket handling and providing a user-friendly API. Whether it’s calling a weather forecast API to get real-time data, automating form submissions, or scraping public data, Requests can achieve complex web interactions with just a few lines of code. As the most popular HTTP library in the Python ecosystem (with over 50k stars on GitHub), it has become a standard toolkit for developers.
2. Installing the Library
Install with a single command using pip:
pip install requests
3. Basic Usage
1. GET request to retrieve data
import requests
response = requests.get('https://api.weather.gov/points/40.7128,-74.0060')
print(response.json()['properties']['forecast']) # Get the weather forecast API address for New York
2. Request with parameters
params = {'q': 'Python', 'page': 1}
response = requests.get('https://api.github.com/search/repositories', params=params)
print(f"Found {response.json()['total_count']} Python repositories")
3. POST request to submit data
data = {'username': '[email protected]', 'password': 'secure123'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.json()['form']) # View submitted form data
4. Handling response content
response = requests.get('https://www.example.com')
print(f"Status code: {response.status_code}")
print(f"Response headers: {response.headers['Content-Type']}")
print(f"Text content: {response.text[:100]}...")
4. Advanced Usage
1. Session management
Automatically handle cookies to improve efficiency for consecutive requests
with requests.Session() as s:
s.get('https://httpbin.org/cookies/set/sessionid/123456789')
response = s.get('https://httpbin.org/cookies')
print(response.json()) # Display all cookies for the current session
2. Timeout and retry control
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=[429, 500, 502, 503, 504])
session.mount('https://', HTTPAdapter(max_retries=retry_strategy))
try:
response = session.get('https://unstable-api.example', timeout=2.5)
except requests.exceptions.Timeout:
print("Request timed out, please check your network connection")
5. Practical Application Scenarios
1. Smart Home Control
Control devices via the Home Assistant API:
HA_URL = "http://homeassistant.local:8123/api"
HEADERS = {'Authorization': 'Bearer YOUR_TOKEN'}
# Turn on the living room lights
requests.post(
f"{HA_URL}/services/light/turn_on",
headers=HEADERS,
json={"entity_id": "light.living_room"})
# Get indoor temperature
response = requests.get(
f"{HA_URL}/states/sensor.living_room_temperature",
headers=HEADERS)
print(f"Current room temperature: {response.json()['state']}℃")
2. Automated Office Tasks
Daily summary of Jira tasks and send via email:
issues = requests.get(
"https://your-company.atlassian.net/rest/api/2/search",
auth=('[email protected]', 'API_TOKEN'),
params={'jql': 'assignee=currentuser() AND status!=Done'}).json()['issues']
task_list = "\n".join([f"- {issue['key']}: {issue['fields']['summary']}"
for issue in issues])
requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN/messages",
auth=('api', 'MAILGUN_API_KEY'),
data={
'from': '[email protected]',
'to': '[email protected]',
'subject': f'Daily Task Summary {datetime.today().strftime("%Y-%m-%d")}',
'text': f"Pending tasks:\n{task_list}"
})
3. Financial Data Aggregation
Integrate data from multiple platforms to generate investment reports:
def fetch_stock_data(symbol):
alpha_vantage = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey=YOUR_KEY"
return requests.get(alpha_vantage).json()['Global Quote']
def fetch_crypto_data(coin):
coinbase = f"https://api.coinbase.com/v2/prices/{coin}-USD/spot"
return requests.get(coinbase).json()['data']
portfolio = {
'stocks': ['AAPL', 'MSFT'],
'cryptos': ['BTC', 'ETH']}
report = {}
for stock in portfolio['stocks']:
report[stock] = fetch_stock_data(stock)['05. price']
for crypto in portfolio['cryptos']:
report[crypto] = fetch_crypto_data(crypto)['amount']
print("Real-time asset prices:")
for asset, price in report.items():
print(f"{asset}: ${float(price):.2f}")
The Requests library, with its “human-friendly” design philosophy, simplifies the complex HTTP protocol into intuitive method calls. Its elegant API design has influenced the development paradigms of countless subsequent libraries, as the Zen of Python states: “Simple is better than complex.” Whether for rapid prototyping or enterprise-level applications, Requests provides stable and efficient network communication capabilities.