Google's APIs power many everyday services, from Gmail add-ons to advanced analytics on YouTube data. Whether you're building a simple automation or a full-fledged application, the steps to set up, authenticate and use these APIs are consistent across Google Cloud services. This guide walks you through creating a project, choosing the right authentication method and calling popular APIs using Python and TypeScript.
1. Create a Google Cloud Project
- Open the Google Cloud Console and create or select a project.
- Enable the APIs you intend to use (e.g., Drive, Sheets, Gmail) via APIs & Services → Library.
- Create credentials under APIs & Services → Credentials: Choose OAuth client ID for web, desktop or mobile apps that require a user's consent, or choose a service account for server-to-server interactions without user involvement.
- Download your credential file (for OAuth it's usually called credentials.json; for service accounts it's service-account.json). Keep this file private and never commit it to source control.
2. Choose an Authentication Approach
OAuth 2.0 (User Consent)
Use OAuth when your application needs to access or modify a user's data. During the authentication flow the user signs in with their Google account and grants your app permission. Your app receives a refresh token that it can exchange for access tokens when needed.
Service Accounts (Server-to-Server)
Service accounts are ideal for back-end processes or applications accessing resources within the same organization. They authenticate using a JSON key file and do not require user consent. If you need to access individual user resources across an entire domain, configure domain-wide delegation and impersonate users on a per-request basis.
3. Install Client Libraries
Use Google's official client libraries for simplified authentication and API calls.
Python
1pip install google-auth google-auth-oauthlib google-api-python-clientTypeScript / Node.js
1npm install googleapis @types/googleapis4. Access Google Drive
Python Example
1from google.oauth2.service_account import Credentials
2from googleapiclient.discovery import build
3
4SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
5SERVICE_ACCOUNT_FILE = 'service-account.json'
6
7credentials = Credentials.from_service_account_file(
8 SERVICE_ACCOUNT_FILE,
9 scopes=SCOPES,
10)
11
12service = build('drive', 'v3', credentials=credentials)
13results = service.files().list(pageSize=10, fields="files(id, name)").execute()
14
15for file in results.get('files', []):
16 print(f"{file['name']} ({file['id']})")TypeScript Example
1import { google } from 'googleapis';
2import { JWT } from 'google-auth-library';
3
4const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
5const serviceAccountKey = require('./service-account.json');
6
7const auth = new google.auth.JWT({
8 email: serviceAccountKey.client_email,
9 key: serviceAccountKey.private_key,
10 scopes: SCOPES,
11});
12
13async function listDriveFiles(): Promise<void> {
14 await auth.authorize();
15 const drive = google.drive({ version: 'v3', auth });
16
17 const response = await drive.files.list({
18 pageSize: 10,
19 fields: 'files(id, name)',
20 });
21
22 (response.data.files ?? []).forEach((file) => {
23 console.log(`${file.name} (${file.id})`);
24 });
25}
26
27listDriveFiles().catch((err) => {
28 console.error('Error listing files:', err);
29});5. Read Google Sheets
Python Example
1from google.oauth2.service_account import Credentials
2from googleapiclient.discovery import build
3
4SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
5SHEET_ID = 'your-spreadsheet-id'
6
7credentials = Credentials.from_service_account_file(
8 'service-account.json',
9 scopes=SCOPES,
10)
11
12sheets = build('sheets', 'v4', credentials=credentials).spreadsheets()
13result = sheets.values().get(
14 spreadsheetId=SHEET_ID,
15 range='Sheet1!A1:C10'
16).execute()
17
18rows = result.get('values', [])
19for row in rows:
20 print(row)TypeScript Example
1import { google } from 'googleapis';
2import { JWT } from 'google-auth-library';
3
4const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
5const SHEET_ID = 'your-spreadsheet-id';
6const serviceAccountKey = require('./service-account.json');
7
8const auth = new google.auth.JWT({
9 email: serviceAccountKey.client_email,
10 key: serviceAccountKey.private_key,
11 scopes: SCOPES,
12});
13
14async function readSheet(): Promise<void> {
15 await auth.authorize();
16 const sheets = google.sheets({ version: 'v4', auth });
17
18 const response = await sheets.spreadsheets.values.get({
19 spreadsheetId: SHEET_ID,
20 range: 'Sheet1!A1:C10',
21 });
22
23 (response.data.values ?? []).forEach((row) => {
24 console.log(row);
25 });
26}
27
28readSheet().catch((err) => {
29 console.error('Error reading sheet:', err);
30});6. Send Email with Gmail
Note: To send email on behalf of a user you must use OAuth2. Service accounts cannot access personal mailboxes unless your domain administrator configures domain-wide delegation.
Python Example
1from base64 import urlsafe_b64encode
2from email.message import EmailMessage
3from google.oauth2.credentials import Credentials
4from googleapiclient.discovery import build
5
6# Use OAuth 2.0 to access a user's mailbox.
7# credentials.json comes from the OAuth flow.
8creds = Credentials.from_authorized_user_file(
9 'credentials.json',
10 ['https://www.googleapis.com/auth/gmail.send'],
11)
12
13service = build('gmail', 'v1', credentials=creds)
14
15message = EmailMessage()
16message.set_content('Hello from the Google API!')
17message['To'] = 'recipient@example.com'
18message['From'] = 'your-email@gmail.com'
19message['Subject'] = 'Test Email'
20
21encoded_message = urlsafe_b64encode(message.as_bytes()).decode()
22create_message = {'raw': encoded_message}
23
24sent = service.users().messages().send(userId='me', body=create_message).execute()
25print(f"Message sent: {sent['id']}")TypeScript Example
1import { google } from 'googleapis';
2
3const gmail = google.gmail('v1');
4
5async function sendEmail(accessToken: string): Promise<void> {
6 const auth = new google.auth.OAuth2();
7 auth.setCredentials({ access_token: accessToken });
8
9 const messageParts = [
10 'From: your-email@gmail.com',
11 'To: recipient@example.com',
12 'Subject: Test Email',
13 '',
14 'Hello from the Google API!',
15 ];
16 const message = Buffer.from(messageParts.join('\n')).toString('base64url');
17
18 const res = await gmail.users.messages.send({
19 auth,
20 userId: 'me',
21 requestBody: { raw: message },
22 });
23
24 console.log(`Message sent: ${res.data.id}`);
25}7. Handle Errors and Rate Limits
- Inspect HTTP status codes: Google APIs return structured errors. Check err.response?.status (Node.js) or the exception details (Python) to determine the cause.
- Implement retries: Respect the Retry-After header or use exponential backoff for status 429 (Too Many Requests) and other transient errors.
- Monitor quotas: Use the Google Cloud Console to track API usage and request quota increases if needed.
Example exponential backoff in TypeScript:
1async function retry<T>(fn: () => Promise<T>, attempts = 5): Promise<T> {
2 let delay = 1000;
3 for (let attempt = 1; attempt <= attempts; attempt += 1) {
4 try {
5 return await fn();
6 } catch (err) {
7 if (attempt === attempts) throw err;
8 await new Promise((resolve) => setTimeout(resolve, delay));
9 delay *= 2;
10 }
11 }
12 throw new Error('Unreachable');
13}8. Best Practices for Production
- Request minimal scopes: Ask only for the permissions you need.
- Secure your credentials: Store keys in a secret manager or environment variables; never commit them to source control.
- Use logging and monitoring: Integrate Google Cloud Logging or your preferred system to track API calls and errors.
- Handle pagination: Many API endpoints return paginated results; loop through nextPageToken or similar fields to retrieve all data.
- Implement caching: Where appropriate, cache API responses to reduce calls and improve performance.
- Leverage impersonation: With domain-wide delegation, impersonate specific users when a service account needs access to per-user resources.
Conclusion
Google's rich ecosystem of APIs makes it possible to build powerful, data-driven applications. By setting up your project correctly, choosing the right authentication method and following best practices for error handling and security, you can integrate services like Drive, Sheets and Gmail with minimal friction. This guide should help you get started quickly. From here you can explore other Google APIs — such as Calendar, Docs, or YouTube — and build on these same principles for even more capabilities.