Google スプレッドシートを python3 で読む (Quickstart)

こちらで行ったのと同様のことを、
[Google スプレッドシートを python3 で読む](https://qiita.com/ekzemplaro/items/f392569828b7fa91dc20)
Quickstart で書かれている方法で行ってみました。
[Python Quickstart | Sheets API](https://developers.google.com/sheets/api/quickstart/python)

## Ubuntu 24.10 で必要なライブラリーをインストール

```bash
sudo apt install python3-google-auth
sudo apt install python3-google-auth-oauthlib
sudo apt install python3-googleapi
```
## credentials.json　を取得

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/76abdef9-1985-7bae-d853-53314f45861c.png)


```json:credentials.json
{
  "installed": {
    "client_id": "****.apps.googleusercontent.com",
    "project_id": "project*****",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "*****",
    "redirect_uris": [
      "http://localhost"
    ]
  }
}
```

## プログラム

```py:api_read.py
#! /usr/bin/python
#
#	api_read.py
#
#						Mar/05/2019
# ------------------------------------------------------------------
import sys
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# ------------------------------------------------------------------
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

# The ID and range of a sample spreadsheet.
SPREADSHEET_ID = '*****'
RANGE_NAME = 'Sheet1!A1:E4'

# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
	with open('token.pickle', 'rb') as token:
		creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
	if creds and creds.expired and creds.refresh_token:
		creds.refresh(Request())
	else:
		flow = InstalledAppFlow.from_client_secrets_file(
			'credentials.json', SCOPES)
		creds = flow.run_local_server()
	# Save the credentials for the next run
	with open('token.pickle', 'wb') as token:
		pickle.dump(creds, token)

service = build('sheets', 'v4', credentials=creds)

# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,
					range=RANGE_NAME).execute()
values = result.get('values', [])

if not values:
	sys.stderr.write('No data found.\n')
else:
	for row in values:
		print(row)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
```

## テストに使ったスプレッドシート
![tochigi_aug31.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/c4c40ac0-3429-880b-1d6b-64e0356f8a98.png)



## 実行結果

```text
$ ./api_read.py 
*** 開始 ***
['t1301', '小山', '39561', 'FALSE', '2015-3-12']
['t1302', '下野', '72843', 'FALSE', '2017-6-22']
['t1303', '栃木', '59218', 'FALSE', '2013-9-2']
['t1304', '佐野', '98765', 'FALSE', '2012-8-5']
*** 終了 ***
```

## 注意
>シート名が Sheet1 でないとエラーになります。

## 確認したバージョン

```text
$ python --version
Python 3.12.7
```