By Papa-Yaw Afari
This tutorial provides a generalized guide for integrating Google APIs with Python, applicable to Google Sheets, Drive, Gmail, Calendar, and more. You will learn how to:
✔ Enable and authenticate a Google API
✔ Set up API credentials
✔ Install and use the `google-auth` and `gspread` libraries
✔ Access Google services using Python
1. Go to the Google Cloud Console (https://console.cloud.google.com/). (You may need to create account)
2. Create a new project or select an existing one.
3. Navigate to APIs & Services > Library.
4. Search for the API you want to use (e.g., Google Sheets API, Google Drive API, Gmail API, etc.).
5. Click Enable.
1. Go to APIs & Services > Credentials.
2. Click Create Credentials > Service Account.
3. Enter a name (e.g., `MyPythonAppService`).
4. Assign a role (Editor, Viewer, or Owner, depending on permissions needed).
5. Click Continue > Done.
6. Open the new service account and go to the Keys tab.
7. Click Add Key > JSON. This will download a `credentials.json` file.
Some APIs (like Google Sheets or Google Drive) require you to share access with your service account.
For example, if using Google Sheets:
1. Open Google Sheets and create a new spreadsheet.
2. Click Share in the top-right corner.
3. Copy the service account email from Google Cloud Console.
4. Paste it in the Add people and groups field and grant Editor access.
To use Google APIs in Python, install the necessary libraries:
```sh
pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client gspread
```
For most Google APIs, use service account authentication:
```python
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets"]
creds = service_account.Credentials.from_service_account_file("credentials.json", scopes=SCOPES)
# Connect to Google Drive API
drive_service = build("drive", "v3", credentials=creds)
# Connect to Google Sheets API
sheets_service = build("sheets", "v4", credentials=creds)
print("Google API connection successful!")
```
### Example: Google Drive API (List Files)
```python
results = drive_service.files().list().execute()
files = results.get("files", [])
for file in files:
print(f"File name: {file['name']} (ID: {file['id']})")
```
### Example: Google Sheets API (Write Data)
```python
spreadsheet_id = "your_google_sheet_id_here"
range_name = "Sheet1!A1:C1"
values = [["Timestamp", "Metric", "Value"]]
body = {"values": values}
sheets_service.spreadsheets().values().update(
spreadsheetId=spreadsheet_id, range=range_name,
valueInputOption="RAW", body=body).execute()
print("Data written to Google Sheets")
```
To test your setup, run:
```sh
python google_api_test.py
```
If everything is set up correctly, you should see data fetched or updated.
### 1️⃣ Permission Denied (403 Error)
✔ Ensure the service account email has been added to Google Sheets/Drive with the correct access.
### 2️⃣ Quota Exceeded (429 Error)
✔ Add a short delay (`time.sleep(0.1)`) between requests.
✔ Avoid sending too many API calls in a short time.
### 3️⃣ `google.auth.exceptions.DefaultCredentialsError`
✔ Ensure `credentials.json` is in the correct directory.
✔ Verify that the path in `from_service_account_file()` is correct.
This setup works for various Google APIs. To integrate with other services:
- **Google Calendar API** → Schedule events
- **Gmail API** → Send & read emails
- **Google Maps API** → Geolocation & directions
- **YouTube Data API** → Retrieve video analytics