๐ How to Use the requests Library in Python
The requests library is the go-to tool for making HTTP requests in Python. GET data from APIs, POST forms, handle auth โ all in a few lines.
Use a requests.Session() object when making multiple requests to the same host โ it reuses TCP connections and cookies.
๐ป Code Example:
import requests # 1. GET request โ fetch data from an API response = requests.get('https://pynfinity.com/api/site-stats') print(response.status_code) # 200 print(response.json()) # Parsed JSON dict # 2. GET with query parameters params = {'topic': 'python', 'limit': 5} resp = requests.get('https://api.example.com/posts', params=params) # URL becomes: .../posts?topic=python&limit=5 # 3. POST request โ send data payload = {'username': 'santoshtvk', 'course': 'infinite_python'} resp = requests.post('https://api.example.com/enroll', json=payload) print(resp.json()) # 4. Headers & Auth headers = {'Authorization': 'Bearer tvk_token_123', 'X-API-Key': 'pynfinity_key'} resp = requests.get('https://api.example.com/protected', headers=headers) # 5. Error handling resp = requests.get('https://pynfinity.com/testapi/json/404') resp.raise_for_status() # Raises HTTPError if 4xx/5xx
| Concept | Key Takeaway |
|---|---|
| requests.get(url) | Fetch data โ most common HTTP method |
| requests.post(url, json={}) | Send data to create a resource |
| requests.put / patch | Update an existing resource |
| requests.delete(url) | Delete a resource |
| response.text | Raw response as string (HTML, XML) |
Keep exploring and happy coding! ๐