What is an API?
An API (Application Programming Interface) is a controlled way to access and exchange data with a system. APIs allow data to be shared without giving a user full access to the underlying database, which helps keep data secure, consistent and easier to use.
Some examples of APIs available to the general public include:
- Google Maps API
- Stripe API
- OpenWeatherMap API
Each of these offers a simple way for developers to use data or services in their own applications, such as maps and routes, payment processing, or weather forecasts.
How to call an API using python?
To call an API in Python, the requests package can be used.
First, install the package by running pip install requests in your terminal.
Once installed, the basic syntax below can be used as a reference. Params define the exact data you would like to request, while headers are commonly used for authentication (they can also carry other information, such as the data format you want back). The API you are calling should provide documentation explaining which inputs it expects.
python
import requests
url = "https://api.example.com/customers"
params = {"city": "London", "limit": 10}
headers = {"Authorization": "Bearer YOUR_API_KEY"}
response = requests.get(url, params=params, headers=headers, timeout=10)
The timeout argument stops your program from hanging indefinitely if the API doesn’t respond.
Once the request has been made, check that it succeeded using response.raise_for_status(), which raises an error if the API returned a failure status such as 404 or 500. The response can then be parsed with response.json(), which turns the JSON data returned by the API into a Python dictionary or list that you can work with.
response.raise_for_status()
data = response.json()
print(data)
