Diary of an IT Guy #AnakBinus

Build Bridges, not Walls. Collaboration Forever!

Posts Tagged ‘API

Integrasi REST API dalam Aplikasi Python

leave a comment »

Berikut adalah contoh coding sederhana untuk mengkonsumi REST API dari MAPQuest dalam sebuah aplikasi Python sederhana. Di sini akan dilakukan input antara dua kota dengan output menampilkan jumlah kilometer dan perkiraan konsumi bahan bakar dalam liter.

import urllib.parse
import requests

main_api = "https://www.mapquestapi.com/directions/v2/route?"
key = "AGhVxXq1gAn9cNLB1XfYYA6FeEQ9SG4U"

while True:
    orig = input("Starting Location: ")
    if orig == "quit" or orig == "q":
        break
    dest = input("Destination: ")
    if dest == "quit" or dest == "q":
        break
    
    url = main_api + urllib.parse.urlencode({"key":key, "from":orig, "to":dest})
    print("URL: " + (url))
    json_data = requests.get(url).json()
    json_status = json_data["info"]["statuscode"]
    if json_status == 0:
        print("API Status: " + str(json_status) + " = A successful route call.\n")
        print("=============================================")
        print("Directions from " + (orig) + " to " + (dest))
        print("Trip Duration: " + (json_data["route"]["formattedTime"]))
        #print("Miles: " + str(json_data["route"]["distance"]))
        #print("Fuel Used (Gal): " + str(json_data["route"]["fuelUsed"]))
        print("Kilometers: " + str((json_data["route"]["distance"])*1.61))
        print("Fuel Used (Ltr): " + str((json_data["route"]["fuelUsed"])*3.78))
        print("=============================================")

Hasil outputnya:

Kita upgrade app di atas menjadi lebih lengkap lagi dengan dilengkapi error input error handling sbb:

import urllib.parse
import requests

main_api = "https://www.mapquestapi.com/directions/v2/route?"
key = "AGhVxXq1gAn9cNLB1XfYYA6FeEQ9SG4U"

while True:
    orig = input("Starting Location: ")
    if orig == "quit" or orig == "q":
        break
    dest = input("Destination: ")
    if dest == "quit" or dest == "q":
        break
    
    url = main_api + urllib.parse.urlencode({"key":key, "from":orig, "to":dest})
    print("URL: " + (url))
    json_data = requests.get(url).json()
    json_status = json_data["info"]["statuscode"]
    if json_status == 0:
        print("API Status: " + str(json_status) + " = A successful route call.\n")
        print("=============================================")
        print("Directions from " + (orig) + " to " + (dest))
        print("Trip Duration: " + (json_data["route"]["formattedTime"]))
        #print("Miles: " + str(json_data["route"]["distance"]))
        #print("Fuel Used (Gal): " + str(json_data["route"]["fuelUsed"]))
        print("Kilometers: " + str((json_data["route"]["distance"])*1.61))
        print("Fuel Used (Ltr): " + str("{:.2f}".format((json_data["route"]["fuelUsed"])*3.78)))
        print("=============================================")

        for each in json_data["route"]["legs"][0]["maneuvers"]:
            print((each["narrative"]) + " (" + str("{:.2f}".format((each["distance"])*1.61) + " km)"))
        print("=============================================\n")
    
    elif json_status == 402:
        print("**********************************************")
        print("Status Code: " + str(json_status) + "; Invalid user inputs for one or both locations.")
        print("**********************************************\n")
    elif json_status == 611:
        print("**********************************************")
        print("Status Code: " + str(json_status) + "; Missing an entry for one or both locations.")
        print("**********************************************\n")
    else:
        print("************************************************************************")
        print("For Staus Code: " + str(json_status) + "; Refer to:")
        print("https://developer.mapquest.com/documentation/directions-api/status-codes")
        print("************************************************************************\n")

Hasilnya adalah sbb:

Written by isal

14 September 2021 at 09:29

Ditulis dalam Web Programming

Tagged with , ,

%d blogger menyukai ini: