I wrote this quick tutorial to learn how to make API calls in Python after transitioning to it from JavaScript.
I thought making API calls in Python would be difficult. But I was wrong. It's actually straightforward (like many things in Python.)
To make an API call in Python follow these steps:
- Import
requests
package - Use
requests.get(URL)
method with the API url - Convert result to JSON object with
.json()
method on returned object. - Access JSON properties as Python dictionary (Using [""] brackets)
Here is a code example:
import requests
url = "http://api.weatherapi.com/v1/current.json?key=47a53ef1aeff4b29ba811204220210&q=London&aqi=no"
# Make API Call
response = requests.get(url)
# Convert result object to JSON dictionary
json = response.json()
# Get json.current.temp_f property from the JSON response
temperature = json["current"]["temp_f"]
# Print temperature from returned JSON object
print(temperature)
This tutorial is also available on YouTube:
Top comments (0)