CodeGym /행동 /Python SELF KO /공개 API 작업

공개 API 작업

Python SELF KO
레벨 24 , 레슨 3
사용 가능

9.1 Google Maps API 작업

인기 서비스의 공개 API를 조금 다뤄보자.

예를 들어, Google Maps API는 지오코딩, 경로 찾기, 위치 정보 등 다양한 서비스를 제공해. Google Maps API를 사용하려면 API 키를 등록해야 해.

지오코딩 (주소로 좌표 얻기)


import requests
API_KEY = 'YOUR_GOOGLE_MAPS_API_KEY'
address = '1600 Amphitheatre Parkway, Mountain View, CA'
url = f'https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={API_KEY}'
response = requests.get(url)
data = response.json()
if data['status'] == 'OK':
    location = data['results'][0]['geometry']['location']
    lat = location['lat']
    lng = location['lng']
    print(f'좌표: {lat}, {lng}')
else:
    print('지오코딩 오류')

9.2 OpenWeatherMap API 작업

또 다른 멋진 예는 전 세계 어떤 곳의 날씨를 얻는 거야.

OpenWeatherMap API 서비스는 전 세계의 날씨 데이터를 제공해. API를 사용하려면 등록하고 API 키를 받아야 해.

현재 날씨 얻기


import requests
API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY'
city = 'London'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
    weather = data['weather'][0]['description']
    temp = data['main']['temp']
    print(f'{city}의 날씨: {weather}, 온도: {temp}°C')
else:
    print('날씨 데이터 얻기 오류')

9.3 GitHub API 작업

너네 프로그래머잖아, 좀 더 개발자스러운 거 해보자. 예를 들어, GitHub 레포지토리를 탐색하는 거지.

GitHub API는 레포지토리, 사용자, 조직에 대한 정보를 제공해.

레포지토리 정보 얻기


import requests
repo_owner = 'octocat'
repo_name = 'Hello-World'
url = f'https://api.github.com/repos/{repo_owner}/{repo_name}'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
    print(f"레포지토리: {data['name']}")
    print(f"설명: {data['description']}")
    print(f"스타: {data['stargazers_count']}")
else:
    print('레포지토리 정보 얻기 오류')

9.4 YouTube Data API 작업

YouTube Data API는 비디오, 채널, 재생 목록에 대한 정보를 얻을 수 있게 해줘. API를 사용하려면 API 키를 받아야 해.


import requests
API_KEY = 'YOUR_YOUTUBE_API_KEY'
video_id = 'Ks-_Mh1QhMc'
url = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={API_KEY}&part=snippet,contentDetails,statistics'
response = requests.get(url)
data = response.json()
if 'items' in data and len(data['items']) > 0:
    video_info = data['items'][0]
    title = video_info['snippet']['title']
    views = video_info['statistics']['viewCount']
    print(f'비디오 제목: {title}')
    print(f'조회수: {views}')
else:
    print('비디오 정보 얻기 오류')

Open Notify API는 국제 우주 정거장(ISS)의 현재 위치 데이터를 제공해.

ISS의 현재 위치 얻기


import requests
url = 'http://api.open-notify.org/iss-now.json'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
    position = data['iss_position']
    print(f"ISS는 현재 위치: 경도 {position['longitude']}, 위도 {position['latitude']}")
else:
    print('데이터 얻기 오류')
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION