How to make an API Call in Python

How to make an API Call in Python

How to use requests module to make HTTP requests

·

1 min read

There is a great video tutorial about making HTTP requests in Python:

(How to make API call in Python)

I've come to the world of Python from JavaScript.

I wasn't too familiar with making API requests in a new environment. So I decided to make this tutorial to write down what I learned.

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 use weatherapi.com API to get current temperature in London.

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"]

Finally, print out temperature in London:

print(temperature)

That's all there is to it.