- 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.
推薦閱讀
- JavaScript實例自學手冊
- Linux Mint System Administrator’s Beginner's Guide
- Mastering D3.js
- 大數據處理平臺
- 網絡安全與防護
- 我也能做CTO之程序員職業規劃
- 網中之我:何明升網絡社會論稿
- LMMS:A Complete Guide to Dance Music Production Beginner's Guide
- 三菱FX/Q系列PLC工程實例詳解
- Linux Shell Scripting Cookbook(Third Edition)
- 簡明學中文版Flash動畫制作
- 網絡信息安全項目教程
- 工業機器人應用系統三維建模
- 傳感器應用技術
- OSGi原理與最佳實踐