DEV Community

Cover image for Make API Call in Python
Code Something
Code Something

Posted on • Updated on

Make API Call in Python

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:

  1. Import requests package
  2. Use requests.get(URL) method with the API url
  3. Convert result to JSON object with .json() method on returned object.
  4. 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)
Enter fullscreen mode Exit fullscreen mode

This tutorial is also available on YouTube:

Top comments (0)