SeouliteLab

파이썬으로 구글 API 호출하기: google-api-python-client 모듈 활용법 본문

카테고리 없음

파이썬으로 구글 API 호출하기: google-api-python-client 모듈 활용법

Seoulite Lab 2024. 4. 17. 08:33

구글 API를 호출하여 다양한 구글 서비스와 상호 작용하기 위해 파이썬에서는 google-api-python-client 모듈을 사용할 수 있습니다. 이 모듈을 사용하면 구글의 다양한 API를 편리하게 호출하고 데이터를 가져오거나 수정할 수 있습니다. 이제 몇 가지 예제를 통해 google-api-python-client 모듈의 활용법을 살펴보겠습니다.

예제 1: Gmail API 사용하기

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials

# 인증 정보 설정
creds = Credentials.from_authorized_user_file('credentials.json')
service = build('gmail', 'v1', credentials=creds)

# 사용자의 이메일 목록 가져오기
response = service.users().messages().list(userId='me').execute()
messages = response['messages']
print(messages)

이 예제에서는 google-api-python-client를 사용하여 Gmail API에 연결하고, 현재 사용자의 이메일 목록을 가져옵니다. 인증 정보는 credentials.json 파일을 통해 설정되며, 사용자의 권한을 부여받습니다.

예제 2: Google Drive API 사용하기

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials

# 인증 정보 설정
creds = Credentials.from_authorized_user_file('credentials.json')
service = build('drive', 'v3', credentials=creds)

# 파일 목록 가져오기
response = service.files().list().execute()
files = response.get('files', [])
for file in files:
    print(file['name'])

이 예제에서는 google-api-python-client를 사용하여 Google Drive API에 연결하고, 현재 사용자의 파일 목록을 가져옵니다. 마찬가지로 credentials.json 파일을 통해 사용자의 인증 정보를 설정합니다.

예제 3: Google Calendar API 사용하기

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials

# 인증 정보 설정
creds = Credentials.from_authorized_user_file('credentials.json')
service = build('calendar', 'v3', credentials=creds)

# 이벤트 목록 가져오기
events_result = service.events().list(calendarId='primary', maxResults=10).execute()
events = events_result.get('items', [])
for event in events:
    print(event['summary'])

이 예제에서는 google-api-python-client를 사용하여 Google Calendar API에 연결하고, 현재 사용자의 이벤트 목록을 가져옵니다. 인증 정보는 credentials.json 파일을 통해 설정됩니다.