Weather data, payment gateways, exchange rates, your own back end: most modern programs talk to other systems through web APIs. In Python, the requests library makes this simple. Install it with pip install requests.
A GET request
import requests
response = requests.get("https://api.example.com/courses", params={"city": "Bengaluru"}, timeout=10)
response.raise_for_status()
courses = response.json()
paramsbuilds the query string safely.timeoutstops your program waiting forever if the server does not answer. Always set it.raise_for_status()raises an error for 4xx and 5xx responses, so failures are not silently ignored..json()turns the JSON body into Python lists and dictionaries.
A POST request
payload = {"name": "Asha", "course": "Python Full Stack"}
response = requests.post("https://api.example.com/enquiries", json=payload, timeout=10)
Using json= encodes the data and sets the right Content-Type header for you.
Headers and authentication
Many APIs need a key: headers={"Authorization": "Bearer " + api_key}. Keep keys in environment variables, never in your code or Git repository.
Handling errors
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.exceptions.Timeout:
print("The server took too long to respond.")
except requests.exceptions.HTTPError as err:
print("Request failed:", err)
Good habits
- Reuse a
requests.Session()when making many calls to the same server; it is faster. - Respect rate limits; add a short pause or retry with back-off when the API returns 429.
- Log the status code and a short message when a call fails, not the whole response with private data.
A practice project
Call a free public API, such as a weather or currency API, save selected fields to a CSV file every day, and plot the trend with pandas.
Related: APIs and JSON for freshers, what is a REST API and Python exception handling.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
