How to make an API Call in Python
How to make an API call in Python? This video tutorial will explain how to make an HTTP request in Python. But if you like to read, I posted instructions under the video.
For the most part I write JavaScript code. But the time has come to finally figure out how to make API calls in Python. It shouldn't really be that difficult should it? Well, it's Python and everything, including API calls, is simple in this language.
At the time of this writing, I wasn’t too familiar with making API requests in a new environment, as someone who has come into the world of Python from JavaScript. This is why I decided to make this tutorial 🙂
In time I will continue to update this page with more examples. For now here is how to make a simple HTTP request in Python using requests module.
I will be using the API from weatherAPI.com. Which is basically a GET request URL that takes your API key, and location in the q parameter.
How to make an API call in Python?First we need to import the requests package:
import requests
The url variable contains my API key and "London" as its query:
url = "http://api.weatherapi.com/v1/current.json?key=47a53ef1aeff4b29ba811204220210&q=London&aqi=no"
Now let’s call get method on the imported requests object:
response = requests.get(url)
Next, we need to convert the response object to JSON format using the built-in json method. The return value is a dict (Python dictionary) data type:
json = response.json()
Access temp_f property from the resulting JSON dictionary:
# Get json.current.temp_f property from the JSON response temperature = json["current"]["temp_f"]
Note that the return value is a Python dictionary.
This means you have to use [“”] brackets to access each property.
Finally, print out temperature in London:
print(temperature)
That’s all there is to it.
Putting It TogetherHere's the full source code for making API calls in Python:
import requestsurl = "http://api.weatherapi.com/v1/current.json?key=47a53ef1aeff4b29ba811204220210&q=London&aqi=no"
response = requests.get(url)
json = response.json()
temperature = json["current"]["temp_f"]
print(temperature)
I'll be updating this page later with more examples, or more complex cases (like making multiple API calls.)