0
# Authentication
1
2
gspread provides multiple authentication methods for accessing Google Sheets API, supporting different use cases from server-side applications to interactive scripts.
3
4
## Capabilities
5
6
### Service Account Authentication
7
8
Authenticate using a service account JSON file or dictionary. Recommended for server-side applications and automated scripts.
9
10
```python { .api }
11
def service_account(filename: Union[Path, str] = DEFAULT_SERVICE_ACCOUNT_FILENAME,
12
scopes: Iterable[str] = DEFAULT_SCOPES,
13
http_client: HTTPClientType = HTTPClient) -> Client:
14
"""
15
Authenticate using service account credentials.
16
17
Parameters:
18
- filename (Union[Path, str]): Path to service account JSON file. Defaults to DEFAULT_SERVICE_ACCOUNT_FILENAME.
19
- scopes (Iterable[str]): OAuth2 scopes. Defaults to DEFAULT_SCOPES.
20
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
21
22
Returns:
23
Client: Authenticated client instance.
24
"""
25
26
def service_account_from_dict(info: Mapping[str, Any], scopes: Iterable[str] = DEFAULT_SCOPES,
27
http_client: HTTPClientType = HTTPClient) -> Client:
28
"""
29
Authenticate using service account credentials from dictionary.
30
31
Parameters:
32
- info (Mapping[str, Any]): Service account information dictionary.
33
- scopes (Iterable[str]): OAuth2 scopes. Defaults to DEFAULT_SCOPES.
34
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
35
36
Returns:
37
Client: Authenticated client instance.
38
"""
39
```
40
41
Usage examples:
42
43
```python
44
# From file
45
gc = gspread.service_account()
46
47
# From specific file
48
gc = gspread.service_account(filename='path/to/service_account.json')
49
50
# From dictionary
51
service_account_info = {
52
"type": "service_account",
53
"project_id": "your-project-id",
54
"private_key_id": "key-id",
55
"private_key": "-----BEGIN PRIVATE KEY-----\n...",
56
"client_email": "your-service-account@your-project.iam.gserviceaccount.com",
57
"client_id": "client-id",
58
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
59
"token_uri": "https://oauth2.googleapis.com/token"
60
}
61
gc = gspread.service_account_from_dict(service_account_info)
62
63
# With custom scopes
64
gc = gspread.service_account(scopes=['https://www.googleapis.com/auth/spreadsheets'])
65
```
66
67
### OAuth2 Authentication
68
69
Interactive OAuth2 flow for applications that need user consent. Suitable for desktop applications and interactive scripts.
70
71
```python { .api }
72
def oauth(scopes: Iterable[str] = DEFAULT_SCOPES, flow: FlowCallable = local_server_flow,
73
credentials_filename: Union[str, Path] = DEFAULT_CREDENTIALS_FILENAME,
74
authorized_user_filename: Union[str, Path] = DEFAULT_AUTHORIZED_USER_FILENAME,
75
http_client: HTTPClientType = HTTPClient) -> Client:
76
"""
77
Authenticate using OAuth2 flow.
78
79
Parameters:
80
- scopes (Iterable[str]): OAuth2 scopes. Defaults to DEFAULT_SCOPES.
81
- flow (FlowCallable): OAuth2 flow callable. Defaults to local_server_flow.
82
- credentials_filename (Union[str, Path]): Path to OAuth2 credentials JSON file. Default: DEFAULT_CREDENTIALS_FILENAME.
83
- authorized_user_filename (Union[str, Path]): Path to store authorized user info. Default: DEFAULT_AUTHORIZED_USER_FILENAME.
84
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
85
86
Returns:
87
Client: Authenticated client instance.
88
"""
89
90
def oauth_from_dict(credentials: Optional[Mapping[str, Any]] = None,
91
authorized_user_info: Optional[Mapping[str, Any]] = None,
92
scopes: Iterable[str] = DEFAULT_SCOPES,
93
flow: FlowCallable = local_server_flow,
94
http_client: HTTPClientType = HTTPClient) -> Tuple[Client, Dict[str, Any]]:
95
"""
96
Authenticate using OAuth2 flow from dictionary.
97
98
Parameters:
99
- credentials (Optional[Mapping[str, Any]]): OAuth2 credentials information dictionary.
100
- authorized_user_info (Optional[Mapping[str, Any]]): Existing authorized user information.
101
- scopes (Iterable[str]): OAuth2 scopes. Defaults to DEFAULT_SCOPES.
102
- flow (FlowCallable): OAuth2 flow callable. Defaults to local_server_flow.
103
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
104
105
Returns:
106
Tuple[Client, Dict[str, Any]]: Authenticated client instance and authorized user info.
107
"""
108
```
109
110
Usage examples:
111
112
```python
113
# Basic OAuth2 flow
114
gc = gspread.oauth()
115
116
# From specific file
117
gc = gspread.oauth(filename='oauth_credentials.json')
118
119
# From dictionary
120
oauth_info = {
121
"client_id": "your-client-id.apps.googleusercontent.com",
122
"client_secret": "your-client-secret",
123
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
124
"token_uri": "https://oauth2.googleapis.com/token"
125
}
126
gc = gspread.oauth_from_dict(oauth_info)
127
128
# With custom port and host
129
gc = gspread.oauth(port=8080, host='127.0.0.1')
130
```
131
132
### Generic Authorization
133
134
Authenticate using pre-existing credentials objects from google-auth library.
135
136
```python { .api }
137
def authorize(credentials: Credentials, http_client: HTTPClientType = HTTPClient,
138
session: Optional[Session] = None) -> Client:
139
"""
140
Authorize using existing credentials object.
141
142
Parameters:
143
- credentials (Credentials): Google auth credentials object (e.g., from google.auth).
144
- http_client (HTTPClientType): HTTP client type. Default: HTTPClient.
145
- session (Optional[Session]): Custom requests Session object.
146
147
Returns:
148
Client: Authenticated client instance.
149
"""
150
```
151
152
Usage example:
153
154
```python
155
from google.auth import default
156
157
# Use default credentials (e.g., from environment or gcloud)
158
credentials, project = default()
159
gc = gspread.authorize(credentials)
160
```
161
162
### API Key Authentication
163
164
Authenticate using Google API key. Limited functionality - only allows reading publicly shared spreadsheets.
165
166
```python { .api }
167
def api_key(api_key: str) -> Client:
168
"""
169
Authenticate using API key.
170
171
Parameters:
172
- api_key (str): Google API key.
173
174
Returns:
175
Client: Client instance with API key authentication.
176
177
Note: API key authentication has limited access - can only read publicly accessible spreadsheets.
178
"""
179
```
180
181
Usage example:
182
183
```python
184
gc = gspread.api_key('your-api-key-here')
185
186
# Only works with publicly shared spreadsheets
187
sheet = gc.open_by_url('https://docs.google.com/spreadsheets/d/spreadsheet-id/edit#gid=0')
188
```
189
190
### Authentication Scopes
191
192
```python { .api }
193
DEFAULT_SCOPES = [
194
'https://www.googleapis.com/auth/spreadsheets',
195
'https://www.googleapis.com/auth/drive'
196
]
197
198
READONLY_SCOPES = [
199
'https://www.googleapis.com/auth/spreadsheets.readonly',
200
'https://www.googleapis.com/auth/drive.readonly'
201
]
202
```
203
204
The DEFAULT_SCOPES provide full read/write access to spreadsheets and drive files. Use READONLY_SCOPES when you only need read access to spreadsheets and drive metadata.
205
206
### Helper Functions
207
208
Additional utility functions for managing OAuth credentials.
209
210
```python { .api }
211
def get_config_dir(config_dir_name: str = "gspread", os_is_windows: bool = os.name == "nt") -> Path:
212
"""
213
Construct a config dir path.
214
215
Parameters:
216
- config_dir_name (str): Configuration directory name. Default: "gspread".
217
- os_is_windows (bool): Whether OS is Windows. Default: os.name == "nt".
218
219
Returns:
220
Path: Configuration directory path.
221
"""
222
223
def load_credentials(filename: Path = DEFAULT_AUTHORIZED_USER_FILENAME) -> Optional[OAuthCredentials]:
224
"""
225
Load OAuth credentials from file.
226
227
Parameters:
228
- filename (Path): Path to authorized user file. Default: DEFAULT_AUTHORIZED_USER_FILENAME.
229
230
Returns:
231
Optional[OAuthCredentials]: Loaded credentials or None if file doesn't exist.
232
"""
233
234
def store_credentials(creds: OAuthCredentials, filename: Path = DEFAULT_AUTHORIZED_USER_FILENAME,
235
strip: str = "token") -> None:
236
"""
237
Store OAuth credentials to file.
238
239
Parameters:
240
- creds (OAuthCredentials): OAuth credentials to store.
241
- filename (Path): Path to store credentials. Default: DEFAULT_AUTHORIZED_USER_FILENAME.
242
- strip (str): Fields to strip from stored credentials. Default: "token".
243
244
Returns:
245
None
246
"""
247
248
def local_server_flow(client_config: Mapping[str, Any], scopes: Iterable[str], port: int = 0) -> OAuthCredentials:
249
"""
250
OAuth flow using local server strategy.
251
252
Parameters:
253
- client_config (Mapping[str, Any]): OAuth client configuration.
254
- scopes (Iterable[str]): OAuth scopes.
255
- port (int): Local server port. 0 for random port.
256
257
Returns:
258
OAuthCredentials: Authorized OAuth credentials.
259
"""
260
```
261
262
### Type Definitions
263
264
```python { .api }
265
class FlowCallable(Protocol):
266
"""Protocol for OAuth flow callables."""
267
268
def __call__(self, client_config: Mapping[str, Any], scopes: Iterable[str], port: int = 0) -> OAuthCredentials: ...
269
270
# Type aliases
271
HTTPClientType = Type[HTTPClient]
272
273
# Default paths
274
DEFAULT_CONFIG_DIR = get_config_dir()
275
DEFAULT_CREDENTIALS_FILENAME = DEFAULT_CONFIG_DIR / "credentials.json"
276
DEFAULT_AUTHORIZED_USER_FILENAME = DEFAULT_CONFIG_DIR / "authorized_user.json"
277
DEFAULT_SERVICE_ACCOUNT_FILENAME = DEFAULT_CONFIG_DIR / "service_account.json"
278
```