The Garmin Connect API library comes with two examples:
example.py - Simple getting-started example showing authentication, token storage, and basic API calls
demo.py - Comprehensive demo providing access to 286 API methods organized into 16 categories for easy navigation
$ ./demo.py
📁 Exported data will be saved to the directory: 'your_data'
📄 All API responses are written to: 'response.json'
Attempting to login using stored tokens from: ~/.garminconnect
Successfully logged in using stored tokens!
📊 Your Stats Today: 4,045 steps | 1445.0 kcal
🐌 Time to get those legs moving!
==================================================
🚴 Full-blown Garmin Connect API Demo - Main Menu
==================================================
Select a category:
[1] 👤 User & Profile
[2] 📊 Daily Health & Activity
[3] 🔬 Advanced Health Metrics
[4] 📈 Historical Data & Trends
[5] 🏃 Activities & Workouts
[6] ⚖️ Body Composition & Weight
[7] 🏆 Goals & Achievements
[8] ⌚ Device & Technical
[9] 🎽 Gear & Equipment
[0] 💧 Hydration & Wellness
[a] 🔧 System & Export
[b] 📅 Training Plans & Calendar
[c] ⛳ Golf
[d] ✏️ Activity Editing
[e] 🏃 Activity Details & Courses
[f] 🐕 Dogs
[q] Exit program
Make your selection:
API Coverage Statistics
Total API Methods: 364 methods; every method with a one-line description is listed in the Method Reference
Categories: 16 organized sections
Web-app endpoint map: the endpoints the Garmin Connect web app uses documented with the exact request it sends and whether it was verified live, in docs/API_ENDPOINTS.md; the dashboard's GraphQL operations are in docs/graphql_operations.md
User & Profile: 8 methods (basic user info, settings)
Daily Health & Activity: 22 methods (today's health data plus daily calories, resting HR and sleep ranges, editing when a night started and ended)
Advanced Health Metrics: 35 methods (fitness metrics, HRV, VO2, FTP range, training readiness, training zones, running tolerance, training load balance, daily training status, activity training load)
Historical Data & Trends: 29 methods (date range queries, weekly aggregates)
Activities & Workouts: 39 methods (comprehensive activity, workout management, typed workout uploads including strength and swim CSS targets, in-place edit, scheduling, push to device, import, activity type/subtype filtering, earliest-upcoming-workout lookup, activity photos: list, add and remove)
Body Composition & Weight: 11 methods (weight tracking, body composition)
Hydration & Wellness: 30 methods (hydration, nutrition, blood pressure, menstrual reads and writes, Jet Lag Adviser trips)
System & Export: 5 methods (reporting, logout, GraphQL, health snapshot download)
Training Plans & Calendar: 23 methods (calendar weeks/years/events, upcoming and primary race events, active plans and plan tasks, plans, plan by ID, typed strength workout uploads including timed sets, exercise catalog search, in-place workout editing, push to device, workout scheduling management)
Golf: 5 methods (scorecard summary, scorecard detail, shot data, club stats, user stats)
Since 0.3.0 this library no longer uses garth, which is deprecated.
Sessions saved by older versions (oauth1_token.json/oauth2_token.json,
created with garth.save()) cannot be converted, and assigning a resumed
client to Garmin().garth no longer does anything. Log in once with your
username and password; new tokens are saved to garmin_tokens.json in your
tokenstore and are used for later logins:
garmin = Garmin(email, password)
garmin.login("~/.garminconnect") # later runs: Garmin().login("~/.garminconnect")
Run demo software (recommended)
Clone the repo, then:
python3 -m venv .venv --copies
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -e ".[example]"
python3 ./example.py # simple getting-started example
python3 ./demo.py # comprehensive demo (286 API methods)
📚 Method Reference
364 public methods on Garmin, generated from the code by scripts/gen_method_reference.py. Click a section to expand it.
Login, profile & account (22)
Method
Description
connectapi(path, **kwargs)
Send a GET to a Connect API path and return the decoded JSON.
connectwebproxy(path, **kwargs)
Send a GET to a Connect API path (legacy alias of connectapi).
Note: Using python -m pdm instead of pdm avoids PATH issues on some
Windows setups where pip install pdm places the pdm executable outside
the directories on PATH. Once pdm install has run, subsequent pdm run ...
commands work normally because the venv's Scripts/ directory is on PATH
while the venv is active.
Development commands:
pdm run format # Auto-format code (isort, black, ruff --fix)
pdm run lint # Check code quality (isort, ruff, black, mypy)
pdm run codespell # Check spelling
pdm run test # Run test suite
pdm run testcov # Run tests with coverage report
pdm run all # Run all checks (lint + codespell + pre-commit + test)
pdm run clean # Clean build artifacts and cache files
pdm run build # Build package for distribution
pdm run --list # Show all available commands
See CONTRIBUTING.md for the checks CI runs and what a pull request needs.
🔐 Authentication
Authentication uses the same mobile SSO flow as the official Garmin Connect mobile apps.
No browser is needed.
How it works:
First login: Authenticates via sso.garmin.com/mobile/api/login using the iOS
app's client ID (GCM_IOS_DARK). If MFA is required, a callback (prompt_mfa) prompts for the one-time code.
Token exchange: The service ticket is exchanged for DI OAuth Bearer tokens
(access_token + refresh_token) via diauth.garmin.com. Tokens are stored at
~/.garminconnect/garmin_tokens.json.
Auto-refresh: Before each API request the library checks whether the DI token is about
to expire and refreshes it automatically — no user interaction required.
Session lifetime:
DI tokens auto-refresh indefinitely as long as the refresh token remains valid.
A full re-login with credentials (and possibly MFA) is only needed if the refresh token
itself expires or is revoked.
The containing directory is restricted to mode 0700. Treat the token file
like a password: the refresh token can provide persistent account access. Avoid
putting a Garmin password in shell history or a long-lived environment variable;
prefer getpass() or another interactive secret prompt.
login() tries several authentication strategies in order (mobile, SSO widget,
web portal — each with and without TLS impersonation) and only declares success
when the resulting token is actually accepted by the API. If a strategy obtains
a token the API later rejects (a region/account-specific condition — see
#369), the
library transparently falls through to the next strategy. Set
Garmin(..., verify_login=False) to restore the legacy "first token wins"
behavior.
MFA in a web app or service: with return_on_mfa=True, login() returns
("needs_mfa", client_state) instead of prompting. client_state is
JSON-serializable, so you can store it while the user fetches the code and
finish the login later, on a new Garmin instance, after a restart or on
another server:
import json
from garminconnect import Garmin
garmin = Garmin(email, password, return_on_mfa=True)
status, client_state = garmin.login()
if status == "needs_mfa":
saved = json.dumps(client_state) # keep until the user enters the code
# Later, possibly in another process (use the same is_cn setting):
garmin = Garmin()
garmin.resume_login(json.loads(saved), mfa_code)
client_state contains Garmin session cookies, so store it as securely as a
password and delete it once the login finishes.
Cached-token gotcha & self-healing: when a tokenstore is supplied,
login() loads those tokens before the strategy chain and short-circuits if
they load — so stale/poisoned cached tokens used to fail every run. The library
now detects this: if cached tokens are rejected by the API, it discards them and
performs a fresh credential login automatically. To force a clean slate yourself
(e.g. between a failed resume and a retry), call:
g.logout() # clears in-memory auth + cached tokens (uses GARMINTOKENS)
g.logout(tokenstore) # or pass an explicit path
logout() removes only the local garmin_tokens.json file and preserves its
directory and unrelated files. It does not revoke a token that has already
been issued by Garmin. Revoke account access from Garmin's account/security
settings if a token may have been copied or exposed.
What running it locally does
This is an unofficial client for Garmin's web services; it does not pair with
the Garmin Connect phone app or connect directly to a watch. When you call
login(), your credentials and MFA code are sent over HTTPS to Garmin's login
service. The library receives an access/refresh token pair and, when a token
store is supplied, caches it locally for later sessions. Subsequent API methods
send that token to Garmin and can read or change the same account data that the
selected method targets.
The library does not automatically download an entire account. The demo writes
responses, activity downloads, and health reports only when you select those
actions. Demo exports are stored under your_data/ with owner-only directory
and file permissions. Run the project in a dedicated virtual environment, read
the method you plan to call, and start with read-only methods. Upload, edit,
delete, schedule, hydration, weigh-in, menstrual, and jet lag trip write methods can change Garmin account data.
🧪 Testing
The default suite is credential-free and excludes live-account integration tests:
pdm run test # Run all tests
pdm run testcov # Run tests with coverage report
To explicitly run live integration tests, use a test account if possible. This
can create local VCR recordings and includes methods that may mutate the account:
VCR recordings are ignored by Git because Garmin responses contain sensitive
health, activity, location, and account data. Do not commit them.
📦 Publishing
For package maintainers: releases are published to PyPI by GitHub Actions with
trusted publishing, so no PyPI
token is needed or stored anywhere.
Bump version in pyproject.toml and update CHANGELOG.md, then merge to master.
Create a GitHub release with the tag X.Y.Z (for example 0.3.21) matching that version.
Publishing the release runs publish.yml: it
checks that the tag matches the package version, runs the tests, builds the
package and uploads it to PyPI.
🤝 Contributing
We welcome contributions! Here's how you can help:
Report Issues: Bug reports and feature requests via GitHub issues
Submit PRs: Code improvements, new features, documentation updates
Testing: Help test new features and report compatibility issues
Documentation: Improve examples, add use cases, fix typos
Before contributing, read CONTRIBUTING.md. It covers the dev setup, the checks CI runs, and how to add an API method. Release notes are in CHANGELOG.md.
import os
from getpass import getpass
from datetime import date
from garminconnect import Garmin
# First run: logs in and saves tokens to ~/.garminconnect
# Subsequent runs: loads saved tokens and auto-refreshes
client = Garmin(
os.getenv("GARMIN_EMAIL"),
getpass("Garmin password: "),
prompt_mfa=lambda: input("MFA code: "),
)
client.login("~/.garminconnect")
# Get today's stats
today = date.today().isoformat()
stats = client.get_stats(today)
# Get heart rate data
hr_data = client.get_heart_rates(today)
print(f"Resting HR: {hr_data.get('restingHeartRate', 'n/a')}")
Typed Workouts (Pydantic Models)
The library includes optional typed workout models for creating type-safe workout definitions:
pip install garminconnect[workout]
from garminconnect.workout import (
RunningWorkout,
WorkoutSegment,
PaceTarget,
create_warmup_step,
create_interval_step,
create_targeted_interval_step,
create_distance_interval_step,
create_cooldown_step,
create_repeat_group,
pace_to_mps,
)
easy_pace = PaceTarget(
lower_limit=pace_to_mps(6, 11, "km"), upper_limit=pace_to_mps(6, 0, "km")
)
# Create a structured running workout
workout = RunningWorkout(
workoutName="Easy Run",
estimatedDurationInSecs=900,
workoutSegments=[
WorkoutSegment(
segmentOrder=1,
sportType={"sportTypeId": 1, "sportTypeKey": "running"},
workoutSteps=[
create_warmup_step(300.0),
create_interval_step( # No intensity target
duration_seconds=400.0,
step_order=2,
),
create_targeted_interval_step( # With target pace
duration_seconds=200.0,
step_order=3,
target=easy_pace,
),
],
)
],
)
# Upload and optionally schedule it
result = client.upload_running_workout(workout)
client.schedule_workout(result["workoutId"], "2026-03-20")
# Edit it in place - keeps its id, so any schedules pointing at it stay valid
workout_data = client.get_workout_by_id(result["workoutId"])
workout_data["workoutName"] = "Easy Run (revised)"
client.update_workout(result["workoutId"], workout_data)
# Delete a workout or remove it from the calendar
client.delete_workout(workout_id)
client.unschedule_workout(scheduled_workout_id)
# Push a workout to a device - defaults to the last workout / last used device
client.push_workout_to_device(result["workoutId"], device_id)
Swimming CSS targets:SwimCssOffsetTarget represents a signed offset from
Critical Swim Speed, rather than an absolute pace range. Supply it as the
secondary target; the primary target can be omitted (Garmin no.target):
Positive offsets are slower than CSS; negative offsets are faster. The offset
is serialized as secondaryTargetValueOne, with secondaryTargetValueTwo=0.
The time-based targeted helper also accepts secondary-only targets. These
helpers retain their existing interval step/end-condition behavior; swimming
stroke, rest, and pool settings are configured separately.
Available workout classes:RunningWorkout, CyclingWorkout, SwimmingWorkout, StrengthWorkout, MultiSportWorkout, FitnessEquipmentWorkout. Garmin has no walking or hiking workout sport type, so upload_walking_workout() and upload_hiking_workout() raise ValueError; the sport types Garmin accepts are listed by get_workout_types()["workoutSportTypes"].
Strength workouts are usually rep-based. Build each exercise with create_strength_set(category, step_order, sets, reps, rest_seconds, exercise_name="", weight_kg=None, description=None) and identify exercises with a category / exercise pair from the bundled catalog in garminconnect.exercises (1,527 exercises across 47 categories, with resolve(name) and find(term) helpers):
For exercises done for time, such as planks or carries, use create_strength_timed_set (or create_strength_timed_step for a single step); it takes duration_seconds instead of reps. Every strength helper also accepts an optional description, a per-step note such as a form cue:
from garminconnect.workout import create_strength_timed_set
plank = create_strength_timed_set(
"PLANK",
step_order=1,
sets=3,
duration_seconds=45,
rest_seconds=30,
exercise_name="PLANK",
description="Squeeze glutes, keep a neutral spine",
)
Use create_distance_interval_step(600.0, step_order=1) for interval steps that should end after a distance in meters instead of after a duration.
Golf
The library supports reading Garmin Golf scorecards, shot-level data, club statistics, and golf user statistics.
# List recent golf scorecards
summary = client.get_golf_summary(limit=10)
scorecard_id = summary["scorecardSummaries"][0]["id"]
# Get the full scorecard details
scorecard = client.get_golf_scorecard(scorecard_id)
# Get shot-by-shot data
# - Omit hole_numbers to receive every hole (recommended for holes 10-18).
# - Single-digit holes work as a comma- or dash-separated list, e.g. "1,2,3".
# Commas are normalized to dashes because Garmin only accepts '-' as the
# separator.
# - Double-digit holes (10-18) cannot be fetched with a filter at all; the
# API either drops them or returns an empty response. If you request holes
# 10-18, the library falls back to returning all 18 holes.
shots = client.get_golf_shot_data(scorecard_id)
shots = client.get_golf_shot_data(scorecard_id, hole_numbers="1,2,3")
# Club and player statistics
club_stats = client.get_golf_club_stats()
user_stats = client.get_golf_user_stats()
Jet Lag Adviser
The library can list, create, replace, and delete Jet Lag Adviser trips. Garmin does not geocode a location: give each place its UTC offset on that date, and give each time as the local time at that place, without an offset.
Each flight is one origin and destination, so you can include legs as part of a trip or not. Garmin accepts any legs, including a leg that changes no timezone and a trip in the past, which the web page does not allow. Garmin says it deletes a trip by itself after the trip ends.
flights = [
{
"originLocation": "Portland, OR, United States",
"originTimezone": "-07:00",
"originTimestamp": "2027-10-04T15:20:00.00",
"destinationLocation": "Melbourne, VIC, Australia",
"destinationTimezone": "+11:00",
"destinationTimestamp": "2027-10-06T06:45:00.00",
},
]
start_date = "2027-10-04"
trip = client.add_jetlag_trip(start_date, "2027-10-09", flights)
# A PUT replaces the whole trip: send every flight, and keep each flightId
client.update_jetlag_trip(trip["tripId"], start_date, "2027-10-12", trip["flights"])
client.delete_jetlag_trip(trip["tripId"])
Activity Photos
Photos attached to an activity are available inside the get_activity()
response at metadataDTO.activityImages; the get_activity_images()
helper returns that list directly:
# [{imageId, url, photoDate}, ...] or [] when the activity has no photos
images = client.get_activity_images(activity_id)
The url values are presigned S3 links that expire after 24 hours, so
download the images promptly instead of storing the URLs. The hasImages
flag in get_activities() results is not a reliable indicator that an
activity has photos attached.
Additional Resources
Simple Example: example.py - Getting started guide