Logo

dev-resources.site

for different kinds of informations.

Make API Call in Python

Published at
10/10/2022
Categories
python
Author
Code Something
Categories
1 categories in total
python
open
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)

This tutorial is also available on YouTube:

Featured ones: