Python for Data & Web
Python Requests Library
The requests library is the simplest way to talk to web APIs and websites in Python — sending HTTP requests and reading back the response in just a couple of lines.
Installing Requests
requests is not part of the Python standard library, so it needs to be installed with pip before you can import it.
pip install requestsMaking a GET Request
A GET request asks a server for data, like fetching a webpage or calling a public API. The response object that comes back holds everything you need: the status code, headers, and the actual content.
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())status_code tells you whether the request succeeded — 200 means OK, 404 means not found, and 500 means a server error. When the response body is JSON, response.json() converts it directly into a Python dictionary or list you can work with.
Sending Params and Headers
Many APIs need extra query parameters (like a search term or page number) or headers (like an API key or authorization token). requests lets you pass both as simple dictionaries.
import requests
params = {"q": "python internships", "page": 1}
headers = {"Authorization": "Bearer YOUR_TOKEN"}
response = requests.get(
"https://example.com/api/search",
params=params,
headers=headers
)
print(response.status_code)Making a POST Request
A POST request sends data to the server, commonly used for submitting a form or creating a new record. Pass a dictionary through the json parameter and requests handles the encoding for you.
import requests
payload = {"name": "Aarav", "email": "aarav@example.com"}
response = requests.post("https://example.com/api/signup", json=payload)
print(response.status_code)
print(response.json())Never hard-code real API keys or passwords in your code. Use environment variables or a config file that is excluded from version control.
| Attribute/Method | Meaning |
|---|---|
| response.status_code | HTTP status like 200 or 404 |
| response.json() | Parse JSON body into Python data |
| response.text | Raw response body as a string |
| params= | Query string values |
| headers= | Extra request headers |
