ClawdClaw ClawdClaw
← Back to blog
· 9 min

Gmail API: What It Is, Scopes, Methods and a Python Example

Gmail API guide for developers: when to use it over IMAP, how to enable it, OAuth scopes, core methods, push notifications, quotas and a Python example.

The Gmail API is Google's RESTful interface for reading, sending, labeling and searching mail in a Gmail mailbox, authorized with OAuth 2.0. Use it when your app needs structured access to messages, threads and labels, or real-time change notifications, rather than a raw mail protocol. This guide covers setup, scopes, the core methods, a working Python example, quotas and the errors you will hit first.

TL;DR

  • Enable the Gmail API in a Google Cloud project, configure the OAuth consent screen, and create an OAuth client.
  • Pick the narrowest scope that works: gmail.labels and gmail.send are easier to get approved than restricted scopes like gmail.readonly or gmail.modify.
  • The core loop is messages.list for IDs, messages.get for content, history.list for changes, and watch with Pub/Sub for push.
  • Quotas are counted in units per minute, per project and per user, and you handle limits with exponential backoff.

What the Gmail API is

The Gmail API exposes a user's mailbox as a set of REST resources under users, where userId="me" means the authenticated user. The main resources are messages, threads, labels, drafts, history (a log of mailbox changes) and settings. Google publishes client libraries for common languages, so you rarely build raw HTTP requests yourself.

Gmail API vs IMAP and SMTP

Gmail also supports IMAP, POP and SMTP, all with OAuth 2.0 through XOAUTH2, so the choice is about how you work with mail.

Choose the Gmail API when you want labels, threads and Gmail search as first-class objects, incremental sync through history.list, push notifications through Pub/Sub, or fine-grained scopes such as send-only access. Choose IMAP and SMTP when you are building a generic mail client that must also work with non-Gmail providers, or you already have a mature IMAP stack and only need basic read and send.

How to enable the Gmail API in Google Cloud console

The official Python quickstart walks through these steps. In short:

  1. Create or select a project in the Google Cloud console and enable the Gmail API for it.
  2. Configure the consent screen under Menu > Google Auth platform > Branding. If you see "Google Auth platform not configured yet", click Get Started, then fill in the app name, support email, audience and contact information.
  3. Create credentials under Menu > Google Auth platform > Clients > Create Client. For a local script, set the application type to Desktop app.
  4. Download the client JSON, save it as credentials.json in your working directory.

The quickstart uses the Internal audience, which suits apps used inside your own Google Workspace organization. A public app needs the External audience, and depending on the scopes you request, verification before launch.

OAuth consent and Gmail API scopes

Google classifies Gmail scopes as non-sensitive, sensitive or restricted, which decides how much review your app needs. Scopes use the prefix https://www.googleapis.com/auth/ unless noted.

Common scopes

Scope What it allows Classification
gmail.labels View and edit labels Non-sensitive
gmail.send Send email on the user's behalf Sensitive
gmail.readonly View messages and settings Restricted
gmail.metadata View metadata such as labels and headers, not the body Restricted
gmail.compose Manage drafts and send email Restricted
gmail.modify Read, compose and send, without permanent deletion Restricted
gmail.settings.basic View and change settings and filters Restricted
https://mail.google.com/ Full access, including permanent deletion that skips the trash Restricted

The full list, including add-on and insert scopes, is on Google's Gmail API scopes page.

Restricted scopes and verification

Restricted scopes need restricted-scope OAuth app verification before a public app can use them. If your servers store or transmit data obtained through a restricted scope, you also need to pass a security assessment, so plan for it early.

If you only send mail, request gmail.send alone. Avoid https://mail.google.com/ unless you truly need permanent deletion: gmail.modify covers most read, label and send workflows. And note that gmail.metadata cannot be used with the q search parameter on messages.list.

Core Gmail API resources and methods

Messages

  • users.messages.list returns message IDs. Each entry only contains id and threadId. It accepts q (the same syntax as the Gmail search box), labelIds, includeSpamTrash, maxResults (default 100, maximum 500) and pageToken for paging.
  • users.messages.get fetches one message. The format parameter controls how much you get back, for example metadata for headers only or full for the parsed body.
  • users.messages.send sends a message. The email goes in the raw field as an RFC 2822 MIME message encoded in base64url.
  • users.messages.modify adds or removes labels, which is how you mark read, archive or star.
  • users.drafts.create and drafts.send use the same raw format for messages you send later.

Threads

users.threads.list, threads.get and threads.modify work at conversation level. A threads.modify label change applies to existing messages, not later ones.

To send a reply that joins an existing thread, three things must be true: the request includes the target threadId, the References and In-Reply-To headers follow RFC 2822, and the Subject matches.

Labels and the IMPORTANT label

users.labels.list returns system and user labels. System labels you can apply or remove yourself include INBOX, SPAM, TRASH, UNREAD, STARRED, IMPORTANT and the category labels (CATEGORY_PERSONAL, CATEGORY_SOCIAL, CATEGORY_PROMOTIONS, CATEGORY_UPDATES, CATEGORY_FORUMS). SENT and DRAFT are applied automatically.

To fetch important mail, pass labelIds=["IMPORTANT"] to messages.list; to mark mail important, add IMPORTANT with messages.modify. Custom labels cannot reuse a system name.

History

users.history.list returns changes since a startHistoryId: messages added or deleted, labels added or removed. Store the latest historyId for the next call. Records are typically kept for at least a week, sometimes less; if your startHistoryId is too old, the API returns 404 and you must do a full sync.

Watch and Pub/Sub push notifications

Instead of polling, Gmail can push changes to a Pub/Sub topic, as the push notifications guide explains:

  1. Create a Pub/Sub topic and a subscription (pull or push to your HTTPS endpoint).
  2. Grant publish rights on the topic to [email protected].
  3. Call users.watch with topicName and, optionally, labelIds and labelFilterBehavior to filter by label.
  4. Save the historyId and expiration from the response.

Each notification carries a base64url-encoded JSON payload with emailAddress and the new historyId, not the message, so you call history.list to get the changes.

Call watch again at least every 7 days or notifications stop; Google recommends renewing daily. Notifications are limited to one per second per watched user and extras are dropped, so always reconcile with history.list. Call users.stop to end a watch.

Python example: list labels and important unread messages

Install the Google client libraries:

python3 -m pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

This script follows the official quickstart flow: it saves tokens to token.json, prints your labels, then lists up to 10 unread messages carrying the IMPORTANT label.

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]


def get_creds():
    creds = None
    if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    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(port=0)
        with open("token.json", "w") as token:
            token.write(creds.to_json())
    return creds


def main():
    service = build("gmail", "v1", credentials=get_creds())
    try:
        labels = service.users().labels().list(userId="me").execute().get("labels", [])
        for label in labels:
            print(label["id"], label["name"])

        result = service.users().messages().list(
            userId="me", labelIds=["IMPORTANT", "UNREAD"], maxResults=10
        ).execute()

        for item in result.get("messages", []):
            msg = service.users().messages().get(
                userId="me", id=item["id"], format="metadata",
                metadataHeaders=["Subject", "From"],
            ).execute()
            headers = {h["name"]: h["value"] for h in msg["payload"]["headers"]}
            print(headers.get("From"), "|", headers.get("Subject"))
    except HttpError as error:
        print(f"An error occurred: {error}")


if __name__ == "__main__":
    main()

If you change SCOPES, delete token.json so consent runs again. format="metadata" keeps responses small when you only need headers.

Gmail API quotas and usage limits

Usage is measured in quota units, with a per-project and a per-user limit counted per minute. Each method costs a different number of units: sending and watch cost far more than listing labels, and a full message costs more than metadata. Newer projects can have different quotas, so check the Gmail API quota page and your project's Quotas page in Cloud console for the numbers that apply to you.

There is also a per-user concurrent request limit shared by every client on the same mailbox. Google advises batches of 50 calls or fewer.

Common Gmail API errors and fixes

  • 400 badRequest: missing or invalid parameter, or an invalid attachment. Read the message field.
  • 401 authError: expired or invalid token, or a missing scope. Refresh the token, or send the user back through OAuth.
  • 403 rateLimitExceeded / userRateLimitExceeded: project or per-user rate limit reached. Retry with exponential backoff.
  • 403 domainPolicy: the user's Workspace admin blocks your app. The admin has to allow it.
  • 404: the resource ID does not exist, or your startHistoryId is out of range (run a full sync).
  • 429 Too many concurrent requests for user: too many parallel calls on one mailbox. Reduce concurrency and back off.
  • 500 backendError and other 5xx: transient server errors. Retry with exponential backoff, starting at one second and doubling.

FAQ

Is the Gmail API free to use?

Usage is governed by quota units and limits on your Cloud project rather than a simple per-call model. Check the current plans and terms for your Google Cloud account, plus the quota page and your project's quotas, before you scale.

Which scope do I need just to send email?

https://www.googleapis.com/auth/gmail.send. It is classified as sensitive, not restricted, so it involves a lighter review than read scopes.

How do I get only important emails with the Gmail API?

Call users.messages.list with labelIds=["IMPORTANT"]. Add UNREAD to the list to narrow it to unread important mail, since labelIds returns messages that have all of the given labels.

Can I search Gmail through the API like in the search box?

Yes. The q parameter on users.messages.list uses the same query format as the Gmail search box. It is not available when you authorize with the gmail.metadata scope.

Why did my push notifications stop arriving?

Usually the watch expired. Renew users.watch at least every 7 days, ideally daily, and confirm [email protected] can still publish to your topic.

If you'd rather not do this yourself

If what you actually want is help with your inbox rather than code, ClawdClaw is a personal AI assistant powered by Claude from Anthropic that lives in your Telegram chat. It helps with email triage, drafting replies and follow-ups, and your calendar, after you sign up with Google and pair Telegram.

Try ClawdClaw

Stop running your inbox. Hire ClawdClaw.

A personal AI assistant powered by OpenClaw, on Telegram. Email triage, follow-ups, research, scheduling — handled. Like a chief of staff who never sleeps.

Get started