[네트워크 보안] 4장. Lab - Integrate a REST API in a Python Application

샤이니·2021년 11월 9일
0

네트워크 보안

목록 보기
2/3

실습 - Python 어플리케이션에 REST API 통합

MapQuest Directions API에서 JSON 데이터를 검색하고, 분석하고, 사용자에게 출력할 수 있도록 형식을 지정하는 vs code 앱 생성. MapQuest Directions API에서 GET Route 요청을 사용함

여기서 GET Route Direction API 문서를 검토하기 :
https://developer.mapquest.com/documentation/directions-api/route/get/

1. DEVASC VM 시작

2. MapQuest 길찾기 애플리케이션 시연

application은 starting location과 destination을 묻는다. 그런 다음 MapQuest Directions API에서 JSON 데이터를 요청하고, 분석하고, useful 정보를 표시한다.

3. MapQuest API 키 가져오기

4. 기본 MapQuest 방향 애플리케이션 빌드

5. 더 많은 기능으로 MapQuest 길찾기 애플리케이션 업그레이드

6. 전체 애플리케이션 기능 테스트

  • 최종 코드
import urllib.parse
import requests
main_api = "https://www.mapquestapi.com/directions/v2/route?"
key = "fZadaFOY22VIEEemZcBFfxl5vjSXIPpZ"
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("Kilometers: " + str("{:.2f}".format((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 bothlocations.")
        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")

API request 생성

  1. 호출시 사용하는 변수 url = = main_api + urllib.parse.urlencode({"key":key, "from":orig, "to":dest})

    • main_api - 액세스하는 기본 URL
    • orig - 출발지
    • dest - 목적지
    • key - 개발자 웹사이트에서 검색한 MapQuest
  2. requests.get().json() -> MapQuest API에 대한 API 호출 수행

  3. key/value pair으로 이루어져있음.

  4. URL 을 클릭시 JSON data를 볼수 있음.

0개의 댓글