- Practical Network Automation
- Abhishek Ratan
- 253字
- 2021-07-02 14:53:08
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.
推薦閱讀
- 21天學通JavaScript
- Visual FoxPro 6.0數(shù)據(jù)庫與程序設計
- Windows環(huán)境下32位匯編語言程序設計
- Troubleshooting OpenVPN
- 突破,Objective-C開發(fā)速學手冊
- 智能生產(chǎn)線的重構方法
- Unity Multiplayer Games
- 人工智能:語言智能處理
- R Machine Learning Projects
- INSTANT Puppet 3 Starter
- 一步步寫嵌入式操作系統(tǒng)
- INSTANT Adobe Story Starter
- 巧學活用Linux
- 實戰(zhàn)突擊
- AWS Administration:The Definitive Guide(Second Edition)