Working with API’s In Python

Hey Guys..! Welcome to another great tutorial, In This tutorial you will learn how to work with API’s in Python. Working with API’s data is a really a fun activity. I will show you how to play it.

To work with API’s you need your API key, I,e mandatory. In this tutorial, I am using Openweathermap API to get weather data from the cities. So go there and get your secret API key.

We need requests library for accessing the API calls. If you don’t have in your system, install it by using the below command.

pip install requests

Now,

This is the URL to get the cities weather data from API. You need to change that city and API key.

api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key}

Now you are ready to use this URL, I will give you the code to get the appropriate data from that API. This API providing data in the format of JSON, so we can use it so easily.

# data.py

import requests

key = 'YOUR API KEY'

city = input('Enter City:').strip()

url = 'https://api.openweathermap.org/data/2.5/weather?q='+city+'&units=metric&appid='+key


res = requests.get(url).json()

#print(res)


#print('coords:',res['coord'])


print('Country:',res['sys']['country'])
print('City:',res['name'])
print('Longitude:',res['coord']['lon'])
print('Lotitude:',res['coord']['lat'])

print('Temperature:',res['main']['temp'],'C')
print('Min.Temp:',res['main']['temp_min'],'C')
print('Max.Temp:',res['main']['temp_max'],'C')
print('Humidity:',res['main']['humidity'])
print('Pressure:',res['main']['pressure'])

Here, I grab the Country, city, Latitude, Longitude, Temperatures, Humidity and Pressure of that city from the API.

Now you can use this data into your web applications. Its very easy and simple. I hope these lines of code can help you a lot.

You can try other API’s also, the process is same for all the API’s. Try yourself with Google NEWS API. Thank you.

Leave a Reply