官术网_书友最值得收藏!

Accessing APIs

Here, we see a generic example of how to access an API and parse some basic values from the return values:

import requests
city="london"
#this would give a sample data of the city that was used in the variable
urlx="https://samples.openweathermap.org/data/2.5/weather?q="+city+"&appid=b6907d289e10d714a6e88b30761fae22"
#send the request to URL using GET Method
r = requests.get(url = urlx)
output=r.json()
#parse the valuable information from the return JSON
print ("Raw JSON \n")
print (output)
print ("\n")
#fetch and print latitude and longitude
citylongitude=output['coord']['lon']
citylatitude=output['coord']['lat']
print ("Longitude: "+str(citylongitude)+" , "+"Latitude: "+str(citylatitude))

The sample output is as follows:

>>>
Raw JSON
{'coord': {'lon': -0.13, 'lat': 51.51}, 'weather': [{'id': 300, 'main': 'Drizzle', 'description': 'light intensity drizzle', 'icon': '09d'}], 'base': 'stations', 'main': {'temp': 280.32, 'pressure': 1012, 'humidity': 81, 'temp_min': 279.15, 'temp_max': 281.15}, 'visibility': 10000, 'wind': {'speed': 4.1, 'deg': 80}, 'clouds': {'all': 90}, 'dt': 1485789600, 'sys': {'type': 1, 'id': 5091, 'message': 0.0103, 'country': 'GB', 'sunrise': 1485762037, 'sunset': 1485794875}, 'id': 2643743, 'name': 'London', 'cod': 200}

Longitude: -0.13, Latitude: 51.51
>>>

Using the requests library, we fetch the sample weather information from an open API (public API) for London, England. The output returned is JSON, which we print first as raw (that is, print the output exactly as we got it back), and then parse out the meaningful info (the city's latitude and longitude) from the JSON payload.

This is an important concept to understand, since we make use of Application Program Interfaces ( APIs) to interact with multiple tools, vendors, and even across applications to perform specific, simple, or complex tasks. 
主站蜘蛛池模板: 洪泽县| 安化县| 旌德县| 禹城市| 海林市| 大同县| 湘阴县| 宁津县| 清原| 浙江省| 庆云县| 敦煌市| 郎溪县| 海南省| 泾源县| 固镇县| 犍为县| 湘阴县| 宁津县| 马龙县| 阿拉尔市| 抚州市| 卓尼县| 札达县| 谢通门县| 保定市| 桐乡市| 商河县| 肇庆市| 溆浦县| 乡城县| 余干县| 宁城县| 紫金县| 巴彦县| 朝阳区| 佛学| 阿克陶县| 隆子县| 潮安县| 都兰县|