파이썬/파이썬(python) 중급

[33-3 파이썬] API Parameters

Olivia-BlackCherry 2022. 9. 26. 07:33

API 파라미터?

- 파라미터로 입력한 입력물에 따라 원하는 특정한 데이터를 받는다.

- 모든 API에 파라미터가 있는 것은 아니다.

- 필수 파라미터(Required), 선택 파라미터(Optional)가 있다.

- 선택 파라미터에는 기본값이 있어서 그냥 내버려 두어도 되고, 특정하게 지정하고 싶다면 적어도 된다.

 

 

 

URL (엔드포인트) : https://api.sunrise-sunset.org/json.

params(파라미터) : "lat", "lot"

import requests
LAT=37
LOG=127

parameters = {
    "lat": LAT,
    "lot": LOG,
}
response = requests.get(url= "https://api.sunrise-sunset.org/json", params= parameters)
response.raise_for_status()
data = response.json()
print(data)

{'results': {'sunrise': '5:49:03 AM', 'sunset': '5:54:17 PM', 'solar_noon': '11:51:40 AM', 'day_length': '12:05:14', 'civil_twilight_begin': '5:24:29 AM', 'civil_twilight_end': '6:18:50 PM', 'nautical_twilight_begin': '4:54:17 AM', 'nautical_twilight_end': '6:49:02 PM', 'astronomical_twilight_begin': '4:23:43 AM', 'astronomical_twilight_end': '7:19:36 PM'}, 'status': 'OK'}

 

 

 

JSON파일로 데이터 보기

웹사이트에서 Sample requests를 보자.

내가 requests했을 때, 웹사이트에서 response로 온

데이터가 담긴 주소를 알려준다.

첫 번째 문장을 보면 노란색 동그라미로 표시 된 부분이 내가 파라미터로 설정할 위도와 경도이다. 

 

위의 주소에서

내가 원하는 위도, 경도로 바꾼 후,

주소창에 그대로 입력하여,

response된 데이터를 들여다보자.

 

 

 

JSON 데이터 뽑기

데이터가 어떻게 나열되어 왔는지 알았으니,

내가 원하는 데이터를 뽑아보자. 

data = response.json()
sunrise = data["results"]["sunrise"]
sunset = data["results"]["sunset"]

print(sunrise)

>>5:49:03 AM

 

 

 

파라미터 값 변경하기

시간 표시 출력 형식을 바꿔보자

현재: 5:49:03 AM
바뀐 후: 2022-09-26 07:18:44.589823

params: formatted

formatted 파라미터는 0 또는 1의 값을 갖는다. 1은 기본 값이다.

  • formatted (integer): 0 or 1 (1 is default). Time values in response will be expressed following ISO 8601 and day_length will be expressed in seconds. Optional.
import requests

LAT=37
LOG=127

parameters = {
    "lat": LAT,
    "lot": LOG,
    "formatted": 0,
}
response = requests.get(url= "https://api.sunrise-sunset.org/json", params= parameters)
response.raise_for_status()
data = response.json()
sunrise = data["results"]["sunrise"]
sunset = data["results"]["sunset"]

print(sunrise)

 

 

 

sunrise 시각 뽑기

문자열.split(기준)

data = response.json()
sunrise = data["results"]["sunrise"]
print(sunrise)
sunrise_hour = sunrise.split("T")[1].split(":")[0]
print(sunrise_hour)

>>2022-09-25T05:49:03+00:00
05

 

 

 

위도, 경도 검색할 수 있는 사이트

https://www.latlong.net/

 

Latitude and Longitude Finder on Map Get Coordinates

What is Latitude and Longitude? Just like every actual house has its address (which includes the number, the name of the street, city, etc), every single point on the surface of earth can be specified by the latitude and longitude coordinates. Therefore, b

www.latlong.net