Making an HTTP GET request in Python is straightforward with the requests library: you pass a URL and get back a response object with status code, headers, and body. This guide covers the basic GET call, how to read plain text or JSON, how to add query parameters and headers, and how to handle errors and timeouts. You need pip install requests and basic familiarity with dictionaries and JSON when the API returns JSON.
1. Install requests
The requests library is not in the standard library. Install it in your virtual environment:
pip install requests
Then import and call requests.get(url). If you get ModuleNotFoundError, ensure the interpreter you use has requests installed (see install a package with pip).
2. Basic GET and response body
requests.get(url) returns a Response object. Use .status_code for the HTTP status (200, 404, etc.), .text for the body as a string, and .json() to parse the body as JSON (raises an error if the body is not valid JSON). The shorthand .ok is True when status is in the 200s.
import requests
r = requests.get("https://api.example.com/data")
print(r.status_code) # 200
print(r.text) # raw body string
data = r.json() # parsed dict/list (if Content-Type is JSON)
Always check r.status_code or r.raise_for_status() before assuming the request succeeded; otherwise you may get a 404 or 500 body and r.json() could still return something that is not the data you expect.
3. Query parameters and headers
Pass query parameters as a dict with params=. Requests will encode them and append to the URL. Pass custom headers (e.g. API keys, Accept) with headers=.
params = {"q": "python", "limit": 10}
headers = {"Authorization": "Bearer YOUR_TOKEN", "Accept": "application/json"}
r = requests.get("https://api.example.com/search", params=params, headers=headers)
# URL becomes: .../search?q=python&limit=10
4. Timeouts and errors
Network calls can hang. Always pass timeout= (seconds) so the call fails after a reasonable time. Use r.raise_for_status() to raise an exception for 4xx/5xx responses so you can handle them in a try/except. For retries and more control see set a timeout and retry HTTP requests.
try:
r = requests.get("https://api.example.com/data", timeout=5)
r.raise_for_status()
data = r.json()
except requests.exceptions.Timeout:
print("Request timed out")
except requests.exceptions.RequestException as e:
print("Request failed", e)
5. Next steps
For POST requests and sending JSON see make an HTTP POST request. For parsing the response see read and write JSON. For building APIs in Python see FastAPI or Flask.