Configuration & API Setup
⚙️ Configuration & API Setup
📋 Overview
To interact with Gmail from Python, you need:
- A Google Cloud project (free tier available)
- Gmail API enabled in that project
- OAuth 2.0 credentials (client ID and secret)
- Python libraries installed
- Secure credential storage
🔧 Step-by-Step Setup
Step 1: Create a Google Cloud Project
Step 2: Enable the Gmail API
Step 3: Create OAuth 2.0 Credentials
credentials.json in your project
📁 Project Structure
Organize your Gmail cleanup project like this:
credentials.json or token.json to Git! Add them to .gitignore.
📦 Python Dependencies
Create requirements.txt:
Install them:
🔐 Understanding OAuth 2.0
Gmail API uses OAuth 2.0 for secure authentication. Here's how it works:
- First Run: User visits Google login page (browser opens automatically)
- Grant Access: User clicks "Allow" to grant your app access to Gmail
- Token Saved: Python saves access token to
token.json - Future Runs: Script reads token from file, no login needed (until token expires)
You only need to authorize once! After that, the script can access Gmail without manual login.
🔧 Configuration File Setup
Create .env.example (template for users):
Create .env with your actual values (don't commit this!):
⚠️ Common Setup Issues
Issue 1: "Gmail API has not been used in project"
Solution: Make sure you enabled the Gmail API in Step 2. Give it 30 seconds to activate.
Issue 2: "Credentials file not found"
Solution: Make sure credentials.json is in the same folder as your Python script.
Issue 3: "2-factor authentication enabled"
Solution: Gmail requires 2FA. This is good for security! The OAuth flow handles it.
💻 Coding Challenges
Challenge 1: Project Setup
Set up the complete project structure:
- Create gmail-cleanup/ directory
- Create .env and .env.example files
- Create requirements.txt with Gmail API dependencies
- Create credentials.json from Google Cloud Console
- Create .gitignore with appropriate entries
Goal: Complete the setup without errors.
Challenge 2: Install Dependencies
Install and verify Python dependencies:
- pip install -r requirements.txt
- Create a test script that imports all libraries
- Print library versions to verify installation
Goal: Verify all dependencies are correctly installed.
Challenge 3: OAuth Authentication
Create a script that performs initial OAuth setup:
- Read credentials.json
- Perform OAuth flow (opens browser)
- Save token.json for future use
- Verify that token.json was created
Goal: Understand and complete the OAuth authentication flow.
🎯 What's Next
Chapter 2 will teach you how to load and manage configuration securely with environment variables and .env files, then Chapter 3 will connect to the Gmail API and start querying your mailbox.