AI Workout Generator API:
The Complete Developer Guide (2026)
One call to /v2/workout/generate returns a complete, structured workout session — warm-up, exercises with sets, reps, rest and effort, supersets or circuits, and a cool-down — personalised by goal, duration, fitness level, equipment and joints to avoid. This guide covers everything from basic integration through production-scale patterns: caching, rate limiting, deduplication, mobile proxying, and quota optimisation.
verified Published by the WorkoutX team — builders of the exercise API used by fitness app developers. Learn more
A complete developer guide on using the `/v2/workout/generate` API endpoint to deliver structured training plans dynamically. Learn to filter by equipment, pick splits and formats, protect joints, render blocks and supersets, and prevent repeat workouts with exclusion logic.
What Is a Workout Generator API?
A workout generator API is a server-side endpoint that accepts user preferences and returns a fully structured training session — exercises, sets, reps, rest periods, and ordering — without the client needing to implement any fitness programming logic. You send parameters, you get a workout back.
This sounds simple, but the engineering value is significant. Building even a basic workout planner from scratch means maintaining an exercise database, writing split logic, implementing equipment filters, handling progressive overload principles, and making sure compound movements are sequenced before isolation work. That's weeks of domain-specific development that has nothing to do with your actual app's differentiator.
The workout generator API pattern delegates all of that to a purpose-built service. Your frontend stays lean; the exercise programming logic lives server-side where it can be iterated independently of your app releases.
Static Exercise Database vs. Dynamic Workout Generation
Most exercise APIs return a static list: you query exercises by body part, equipment, or muscle, and you get back raw data. That's a valid use case — browseable exercise libraries, search features, informational content. But it puts the workout programming burden entirely on your app.
A workout generator API is different. It doesn't just return exercises; it returns a programme: an ordered sequence of movements with specific training prescriptions, calibrated to a goal and duration. The distinction matters for user retention — a static database can be downloaded once and cached forever, while a generator produces a fresh session on every call. Users keep opening the app because the workout changes.
Available on: Growth ($39/month) and Scale ($79/month) plans, Enterprise, and the legacy Pro and Ultra plans. Each call to /v2/workout/generate counts as one API request. View pricing →
Diagram: Static exercise database vs. dynamic workout generation API flow
alt="Static exercise database API vs AI workout generator API comparison diagram"
How the Generator Works
The WorkoutX generator is a rule-based expert engine. It's not a large language model and there's no machine learning involved: it's fitness programming logic encoded as a server-side engine, which makes it fast, hallucination-free, and consistently structured. Every request runs five steps:
-
Build the exercise pool — the v2 exercise library, in the requested
model(male or female), is narrowed to exercises the user can do: the listedequipment(body weight is always allowed), a level window aroundlevel(an advanced exercise never goes to a beginner), and minus anything inexclude. WithavoidJoints, movements that load those joints heavily are removed and moderate ones are marked for a gentler prescription. -
Pick a template of movement patterns — the
splitis a list of slots by movement pattern rather than body part: a full-body day asks for a squat, a horizontal press, a hip hinge and a pull before any accessories, a push day for a horizontal press, an overhead press and a fly.bodyFocusbuilds a custom template from the body parts you name instead. -
Fill each slot — each slot gets the best scoring exercise for its pattern: well-known compound lifts lead, the equipment suits the role, the work is spread across muscles, and two versions of the same movement never appear in one session. A little seeded randomness keeps sessions varied; the same
seedgives the same session. -
Prescribe and fit to the duration — sets, reps or a duration, rest, effort (
rir), tempo and load come from the goal, the exercise's role and the level. Every exercise first gets its minimum sets; more sets go to the most important lifts while the time budget allows. -
Format, warm-up and cool-down — exercises are grouped into straight sets, supersets of opposing muscle groups, or one circuit (
format), with a warm-up of easy cardio and dynamic mobility, ramp-up sets before the first main lift, and stretches for the muscles trained.
Diagram: Request → exercise pool → pattern template → slot filling → prescription and duration fit → warm-up, blocks, cool-down
alt="AI workout generator API request filtering and generation pipeline diagram"
The Duration Model
One detail worth understanding for UI purposes: duration is the whole session, warm-up and cool-down included, and estimatedDurationMinutes (next to targetDurationMinutes) is a calculation, not a guarantee. It counts about 3.5 seconds per rep, the prescribed rest, a transition between exercises, ramp-up sets, and the warm-up and cool-down items. Real workout duration varies with how long your users actually rest: supersets and circuits pack more work into the same time, while strength sessions with 3-minute rests fit fewer exercises.
Display this value as "approximately X minutes" in your UI, not as a precise countdown. Users who follow rest periods strictly may finish early; users who chat between sets will run over.
Endpoint Reference
GET https://api.workoutxapp.com/v2/workout/generate
Authentication: X-WorkoutX-Key: wx_your_key_here (header only; v2 rejects keys in the URL)
Plan required: Growth or Scale (or Enterprise, or legacy Pro/Ultra)
Quota cost: 1 request per call
All parameters are optional. Omitting them produces a sensible 45-minute intermediate muscle gain full-body session.
| Parameter | Type | Default | Options / Range |
|---|---|---|---|
goal | string | muscle_gain | muscle_gain · strength · fat_loss · endurance · mobility · general_fitness |
duration | integer | 45 | 15–120 minutes, warm-up and cool-down included. Sets and exercise count are fitted to it. |
level | string | intermediate | beginner · intermediate · advanced |
split | string | full_body | full_body · full_body_b · full_body_c · upper · upper_b · lower · lower_b · push · push_b · pull · pull_b · legs · legs_b · core · conditioning · mobility (v1's push_pull_legs and upper_lower still work). Default conditioning for fat_loss and endurance. |
equipment | string | full gym | Comma-separated equipment and apparatus, e.g. barbell,dumbbell,bench (also cable, kettlebell, band, leverage machine, pull-up bar, box…), or a preset: gym, home (body weight, dumbbell, kettlebell, band, bench), bodyweight. Body weight is always allowed. |
bodyFocus | string | — | Comma-separated: chest, back, shoulders, arms, biceps, triceps, forearms, legs, quads, hamstrings, glutes, hips, calves, core, abs, obliques, cardio, mobility. Overrides split. |
avoidJoints | string | — | Comma-separated: knee · shoulder · lumbar_spine · elbow · wrist · hip · ankle. Leaves out high-stress movements and prescribes moderate ones lighter. General guidance, not medical advice. |
format | string | auto | auto · straight · superset · circuit. Auto: circuit for fat_loss and endurance, straight sets for strength and mobility, otherwise supersets up to 60 minutes. |
exclude | string | — | Comma-separated v2 exercise IDs to skip (user dislikes / recently done), e.g. ex_SAWOOH. Excluding one also excludes its other-model clip. |
seed | string | random | Same seed + same params = the same workout. The response always includes the seed used. |
model | string | male | male · female — which model the exercise videos show (a movement filmed with only the other model is used in that model) |
lang | string | en | tr · de · es · fr · zh-SG · zh-HK — translates the exercises; the rest of the plan stays in English |
Response Schema
{
"goal": "muscle_gain",
"level": "intermediate",
"model": "female",
"seed": "doc1",
"split": "full_body",
"format": "superset",
"targetDurationMinutes": 45,
"estimatedDurationMinutes": 41,
"equipment": ["bench", "body weight", "dumbbell"],
"summary": {
"totalExercises": 5,
"workingSets": 15,
"patterns": ["squat", "push_horizontal", "hinge", "pull_horizontal", "push_vertical"],
"muscles": [{ "group": "Quads", "sets": 7.5 }, /* ... */]
},
"warmup": {
"minutes": 6,
"rampUp": "Before Dumbbell Front Squat: 2 ramp-up sets at about 50% × 10 and 75% × 5 of your working weight.",
"items": [
{ "durationSeconds": 240, "perSide": false,
"note": "Easy pace: raise your heart rate and body temperature.",
"exercise": { "id": "ex_L4EMF6", "name": "Walking", /* full v2 exercise with media */ } }
// ... dynamic mobility items
]
},
"exercises": [
{
"order": 1,
"block": "A",
"role": "main",
"pattern": "squat",
"sets": 3,
"reps": "6-8",
"perSide": false,
"restSeconds": 120,
"rir": 2,
"tempo": "3-0-1-0",
"load": "70–80% of 1RM",
"cue": "(the exercise's first form tip)",
"rationale": "Main lift: squat for the quadriceps and glutes.",
"alternatives": [
{ "id": "ex_KNIBLJ", "name": "Bodyweight Squat", "equipment": "Body Weight", "model": "male" }
// ... light objects, no media
],
"exercise": {
"id": "ex_TFXRNX",
"name": "Dumbbell Front Squat",
"model": "male",
"target": "Quads",
"equipment": "Dumbbell",
"media": {
"expiresAt": "...",
"mp4": "https://…/m/v1/ex_TFXRNX/mp4-720.mp4?…",
"poster": "https://…/m/v1/ex_TFXRNX/poster.jpg?…"
}
// ... plus the other v2 exercise fields (instructions, tips, muscles, met)
}
},
// ... B: main press, C: hip hinge, then a superset:
{ "order": 4, "block": "D1", "role": "secondary", "sets": 3, "reps": "8-10", "restSeconds": 15, /* ... Dumbbells Bent Over Row */ },
{ "order": 5, "block": "D2", "role": "secondary", "sets": 3, "reps": "8-10", "restSeconds": 90, /* ... Dumbbell Push Press */ }
],
"cooldown": {
"minutes": 2,
"items": [ { "durationSeconds": 30, "note": "Stretch for the quads; breathe slowly, no bouncing.", "exercise": { /* ... */ } } /* ... */ ]
}
}
Heads up: Every exercise in exercises, warmup.items and cooldown.items is a full v2 exercise with a media object (mp4, poster, expiresAt); alternatives are light and carry no media. Each exercise has either reps or durationSeconds, and circuit stations add rounds. The links are signed, so your backend can pass them to the client and the browser can play them without your API key. They expire after 24–25 hours: store exercise ids (for history and exclude), not media links. See Media in v2 for details.
Quickstart
The simplest possible call. No parameters — you get a sensible 45-minute intermediate full-body muscle gain session:
curl 'https://api.workoutxapp.com/v2/workout/generate' \ -H "X-WorkoutX-Key: wx_your_key_here"
A more targeted call — 30-minute beginner fat loss circuit, bodyweight only, with the female model in the videos:
curl 'https://api.workoutxapp.com/v2/workout/generate?goal=fat_loss&duration=30&level=beginner&equipment=bodyweight&model=female' \ -H "X-WorkoutX-Key: wx_your_key_here"
Advanced push day with specific equipment (list the bench too, or bench presses are left out) and excluded exercises:
curl 'https://api.workoutxapp.com/v2/workout/generate?goal=strength&duration=60&level=advanced&split=push&equipment=barbell,dumbbell,bench&exclude=ex_SAWOOH,ex_2OSXDM' \ -H "X-WorkoutX-Key: wx_your_key_here"
Knee-friendly lower-body session with supersets:
curl 'https://api.workoutxapp.com/v2/workout/generate?goal=muscle_gain&duration=45&split=lower&avoidJoints=knee&format=superset' \ -H "X-WorkoutX-Key: wx_your_key_here"
avoidJoints leaves out movements that load the knee heavily, prescribes moderate ones with lighter loads and higher reps (with a joint-care note), and adds a line to notes. It is general guidance, not medical advice: tell users with pain or an injury to check with a professional.
JavaScript Integration
Here's a production-grade generateWorkout() function with proper error handling, retry logic, and structured response typing. This is what you'd actually ship — not a minimal snippet that ignores 403s and network errors.
const API_KEY = process.env.WORKOUTX_API_KEY; // never hardcode in client-side code const BASE = 'https://api.workoutxapp.com/v2'; /** * Generate a workout plan. Call this from your backend — do not expose * your API key in client-side JavaScript or mobile app bundles. * * @param {Object} opts * @param {string} opts.goal - muscle_gain | strength | fat_loss | endurance | mobility | general_fitness * @param {number} opts.duration - 15–120 minutes, warm-up and cool-down included * @param {string} opts.level - beginner | intermediate | advanced * @param {string} opts.split - full_body | upper | lower | push | pull | legs (+ _b variants) | core | conditioning | mobility * @param {string[]} opts.equipment - ['barbell','dumbbell','bench',...] or a preset: ['home'] | ['bodyweight'] | ['gym'] * @param {string[]} opts.bodyFocus - overrides split — ['chest','back',...] * @param {string[]} opts.avoidJoints - ['knee','lumbar_spine',...] — general guidance, not medical advice * @param {string} opts.format - auto | straight | superset | circuit (default: auto) * @param {string[]} opts.exclude - v2 exercise IDs to skip — ['ex_SAWOOH','ex_2OSXDM'] * @param {string} opts.seed - same seed + params = same workout * @param {string} opts.model - male | female (default: male) * @param {number} retries - max retries on network errors (default: 2) * @returns {Promise<Object>} */ async function generateWorkout(opts = {}, retries = 2) { // Send only what's set: the API's defaults depend on the goal (e.g. the split) const params = new URLSearchParams(); for (const key of ['goal', 'duration', 'level', 'split', 'format', 'seed', 'model']) { if (opts[key] != null) params.set(key, opts[key]); } for (const key of ['equipment', 'bodyFocus', 'avoidJoints', 'exclude']) { if (opts[key]?.length) params.set(key, opts[key].join(',')); } for (let attempt = 0; attempt <= retries; attempt++) { try { const res = await fetch(`${BASE}/workout/generate?${params}`, { headers: { 'X-WorkoutX-Key': API_KEY }, signal: AbortSignal.timeout(8000), // 8s timeout — safe for mobile }); if (res.status === 403) { // Plan gate — no point retrying throw { code: 'PLAN_REQUIRED', message: 'Workout Generator requires the Growth or Scale plan', status: 403 }; } if (res.status === 429) { // Rate limited — respect Retry-After if present const retryAfter = parseInt(res.headers.get('Retry-After')) || 60; if (attempt < retries) { await new Promise(r => setTimeout(r, retryAfter * 1000)); continue; } throw { code: 'RATE_LIMITED', message: 'Rate limit hit — retry later', retryAfter, status: 429 }; } if (res.status === 422) { // Invalid params — don't retry, surface the message const body = await res.json(); throw { code: 'INVALID_PARAMS', message: body.message, status: 422 }; } if (!res.ok) { if (attempt < retries) { await new Promise(r => setTimeout(r, 500 * (attempt + 1))); // linear backoff continue; } throw { code: 'API_ERROR', message: `Unexpected status: ${res.status}`, status: res.status }; } return res.json(); } catch (err) { if (err.code) throw err; // structured error from above — rethrow if (attempt < retries) { await new Promise(r => setTimeout(r, 500 * (attempt + 1))); continue; } throw { code: 'NETWORK_ERROR', message: err.message, original: err }; } } }
Rendering the Workout
function renderWorkout(workout, containerId) { const container = document.getElementById(containerId); if (!container) return; const header = ` <div class="workout-header"> <h2>Today's Workout</h2> <p>${workout.goal.replace(/_/g,' ')} · ${workout.level} · ~${workout.estimatedDurationMinutes} min</p> <p>${workout.summary.totalExercises} exercises · ${workout.summary.workingSets} sets · ${workout.format}</p> ${(workout.notes || []).map(n => `<p class="note">${n}</p>`).join('')} </div> `; // Warm-up and cool-down items are exercises too, with their own media const steps = (title, part) => ` <h3>${title} · ${part.minutes} min</h3> <ul>${part.items.map(i => `<li>${i.exercise.name} · ${i.durationSeconds}s${i.perSide ? ' per side' : ''}</li>`).join('')}</ul> `; const cards = workout.exercises.map(item => { const ex = item.exercise; // ex.media links are signed, so the browser can load them without your API key. const video = ex.media ? `<video src="${ex.media.mp4}" poster="${ex.media.poster}" autoplay loop muted playsinline width="120" height="144"></video>` : ''; // reps or durationSeconds; circuit stations also have rounds const amount = item.reps ? `${item.reps} reps` : `${item.durationSeconds}s`; const sets = item.rounds ? `${item.rounds} rounds × ${amount}` : `${item.sets} sets × ${amount}`; return ` <div class="exercise-card ${item.role}" data-exercise-id="${ex.id}"> <span class="block">${item.block}</span> <!-- C1 + C2 = superset --> ${video} <div class="details"> <h3>${ex.name}</h3> <p class="prescription"> <strong>${sets}${item.perSide ? ' per side' : ''}</strong> · ${item.restSeconds}s rest ${item.rir != null ? ` · ${item.rir} reps in reserve` : ''} </p> <p class="why">${item.rationale}</p> ${item.note ? `<p class="note">${item.note}</p>` : ''} ${item.alternatives.length ? `<button data-swap="${item.alternatives[0].id}">Swap: ${item.alternatives[0].name}</button>` : ''} </div> </div> `; }).join(''); container.innerHTML = header + steps('Warm-up', workout.warmup) + cards + steps('Cool-down', workout.cooldown); } // Usage document.getElementById('generate-btn') .addEventListener('click', async () => { const btn = document.getElementById('generate-btn'); btn.textContent = 'Generating...'; btn.disabled = true; try { // In production, call this through your backend route (see Mobile proxy below) const workout = await generateWorkout({ goal: document.getElementById('goal').value, duration: +document.getElementById('duration').value, level: document.getElementById('level').value, split: document.getElementById('split').value, equipment: selectedEquipment, // from your equipment picker state avoidJoints: userProfile.jointsToProtect, // e.g. ['knee'] exclude: getRecentExerciseIds(), // from localStorage or DB }); renderWorkout(workout, 'workout-result'); saveCompletedExercises(workout.exercises.map(e => e.exercise.id)); } catch (err) { if (err.code === 'PLAN_REQUIRED') showUpgradeModal(); else if (err.code === 'RATE_LIMITED') showRateLimitMessage(err.retryAfter); else console.error('Workout generation failed:', err); } finally { btn.textContent = 'Regenerate Workout'; btn.disabled = false; } });
For a swap button, fetch the alternative the user picks with GET /v2/exercises/{id} (alternatives carry no media) and put it in place of the original, keeping the prescription.
Python Integration
For server-side generation — useful in Flask/FastAPI backends, scheduled workout delivery, or batch plan generation for multiple users:
import os, time import requests from requests.exceptions import HTTPError, Timeout, ConnectionError API_KEY = os.environ['WORKOUTX_API_KEY'] # load from env, never hardcode BASE_URL = 'https://api.workoutxapp.com/v2' TIMEOUT = 8 # seconds def generate_workout( goal='muscle_gain', duration=45, level='intermediate', split=None, # None = the goal's default equipment=None, body_focus=None, avoid_joints=None, # e.g. ['knee'] — general guidance, not medical advice fmt=None, # 'straight' | 'superset' | 'circuit'; None = auto exclude=None, seed=None, max_retries=2, ): """ Generate a workout plan via the WorkoutX API. Raises: PermissionError: Plan upgrade required (403) ValueError: Invalid parameters (422) RuntimeError: Rate limited or server error """ params = {'goal': goal, 'duration': duration, 'level': level} if split: params['split'] = split if fmt: params['format'] = fmt if seed: params['seed'] = seed if equipment: params['equipment'] = ','.join(equipment) if body_focus: params['bodyFocus'] = ','.join(body_focus) if avoid_joints: params['avoidJoints'] = ','.join(avoid_joints) if exclude: params['exclude'] = ','.join(exclude) headers = {'X-WorkoutX-Key': API_KEY} for attempt in range(max_retries + 1): try: r = requests.get( f'{BASE_URL}/workout/generate', headers=headers, params=params, timeout=TIMEOUT, ) if r.status_code == 403: raise PermissionError('Workout Generator requires the Growth or Scale plan') if r.status_code == 422: body = r.json() raise ValueError(f"Invalid params: {body.get('message', r.text)}") if r.status_code == 429: retry_after = int(r.headers.get('Retry-After', 60)) if attempt < max_retries: time.sleep(retry_after) continue raise RuntimeError(f'Rate limited. Retry after {retry_after}s') r.raise_for_status() return r.json() except (Timeout, ConnectionError) as e: if attempt < max_retries: time.sleep(0.5 * (attempt + 1)) continue raise RuntimeError(f'Network error after {max_retries + 1} attempts: {e}') # ── Example usage ────────────────────────────────────────────────────────── # 30-min beginner fat loss, bodyweight only (format auto = a circuit) workout = generate_workout( goal='fat_loss', duration=30, level='beginner', equipment=['bodyweight'] ) print(f"{workout['format']}: {workout['summary']['totalExercises']} exercises (~{workout['estimatedDurationMinutes']} min)") for item in workout['warmup']['items']: print(f" warm-up: {item['exercise']['name']} {item['durationSeconds']}s") for item in workout['exercises']: ex = item['exercise'] amount = item.get('reps') or f"{item['durationSeconds']}s" # reps or a duration rounds = item.get('rounds') or item['sets'] # circuit stations have rounds print(f" {item['block']}. {ex['name']} — {rounds}×{amount} | {item['restSeconds']}s rest") # 60-min advanced push day with exclusion done_this_week = ['ex_SAWOOH', 'ex_2OSXDM'] # v2 exercise ids push_day = generate_workout( goal='strength', duration=60, level='advanced', split='push', equipment=['barbell', 'dumbbell', 'bench'], exclude=done_this_week )
Production Patterns
Getting the API responding locally is straightforward. Making it work well at scale — or even just for a small app with real users — involves a handful of non-obvious decisions.
Mobile Apps: Always Proxy Through Your Backend
If you're building an iOS or Android app (React Native, Flutter, Swift, Kotlin), do not call the WorkoutX API directly from the mobile client. Any API key embedded in a mobile binary can be extracted from the compiled app package — it's a well-known attack vector.
The correct architecture is a thin backend route on your own server that:
- Authenticates your user (your own auth)
- Validates the request parameters
- Forwards the request to WorkoutX with your server-side API key
- Returns the response to the mobile client
This also lets you add your own rate limiting per user, log workout generation events, inject custom business logic (e.g. enforce the user's subscription tier before forwarding), and cache responses when appropriate.
Architecture diagram: Mobile app → your backend proxy → WorkoutX API
alt="Mobile fitness app backend API proxy architecture diagram for workout generator"
// Your backend: POST /workout/generate // Client sends user prefs, server holds the API key app.post('/workout/generate', requireAuth, async (req, res) => { const { goal, duration, level, split, format, equipment, avoidJoints, exclude } = req.body; // Validate user's subscription before forwarding if (!req.user.hasFeature('workoutGenerator')) { return res.status(403).json({ error: 'Upgrade required' }); } const params = new URLSearchParams(); for (const [k, v] of Object.entries({ goal, duration, level, split, format })) if (v != null) params.set(k, v); if (equipment?.length) params.set('equipment', equipment.join(',')); if (avoidJoints?.length) params.set('avoidJoints', avoidJoints.join(',')); if (exclude?.length) params.set('exclude', exclude.join(',')); try { const upstream = await fetch( `https://api.workoutxapp.com/v2/workout/generate?${params}`, { headers: { 'X-WorkoutX-Key': process.env.WORKOUTX_API_KEY } } ); if (!upstream.ok) { const body = await upstream.json().catch(() => ({})); return res.status(upstream.status).json(body); } const workout = await upstream.json(); res.json(workout); } catch (err) { res.status(502).json({ error: 'Upstream unavailable' }); } });
Caching: When to Cache, When Not To
The short answer: don't cache workout responses for reuse. The value of the generator is freshness — the same user hitting "Generate" twice in a row should see different exercises.
That said, there's a reasonable caching pattern for "today's workout": generate once when the user opens the app for the day, cache the result with a TTL that expires at midnight local time, and serve the cached version for the rest of the day. This avoids repeated quota hits for users who open and close the app multiple times, while still ensuring a fresh workout each day.
const cache = new Map(); // replace with Redis in production function getDailyCacheKey(userId, params) { const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD return `workout:${userId}:${today}:${params.goal}:${params.split}`; } function msUntilMidnight() { const now = new Date(); const midnight = new Date(now).setHours(24, 0, 0, 0); return midnight - now; } async function getTodaysWorkout(userId, params) { const key = getDailyCacheKey(userId, params); const cached = cache.get(key); if (cached) return { workout: cached, fromCache: true }; const workout = await generateWorkout(params); cache.set(key, workout); setTimeout(() => cache.delete(key), msUntilMidnight()); // auto-expire at midnight return { workout, fromCache: false }; }
The "Regenerate" button — which calls the API again with the same or slightly modified params — should bypass this cache intentionally. That's the whole point of regeneration.
Preventing Workout Repetition
The generator randomises on every call, but with a large enough exercise exclusion list you can guarantee variety across sessions. Store the IDs of exercises a user has seen in the last 7–14 days, then pass them as exclude. Each slot then gets the next best exercise for the same movement pattern. If the list covers every option for a slot (likely with little equipment), that slot is left out rather than repeating an exercise, so keep the list short on small setups.
A practical implementation using localStorage for a client-side or React Native app:
const HISTORY_KEY = 'wx_exercise_history'; const MAX_DAYS = 14; function loadHistory() { try { return JSON.parse(localStorage.getItem(HISTORY_KEY) || '[]'); } catch { return []; } } function saveHistory(entries) { // Prune entries older than MAX_DAYS const cutoff = Date.now() - MAX_DAYS * 24 * 60 * 60 * 1000; const fresh = entries.filter(e => e.ts > cutoff); localStorage.setItem(HISTORY_KEY, JSON.stringify(fresh)); } export function getRecentExerciseIds() { return loadHistory().map(e => e.id); } export function markExercisesAsDone(exerciseIds) { const history = loadHistory(); const now = Date.now(); exerciseIds.forEach(id => history.push({ id, ts: now })); saveHistory(history); } // After workout completes: markExercisesAsDone(workout.exercises.map(e => e.exercise.id));
Quota Optimisation
If you're on the Growth plan (25,000 requests/month), each workout generation costs one request. A user who generates once per day uses 30 requests per month — meaning you can support ~833 daily-active users on a single Growth key. The Scale plan (100,000 requests/month) scales to ~3,333 DAU at the same usage rate.
A few patterns that reduce wasted requests:
- Daily cache per user — generate once per day per user, cache until midnight (see above). Users who reopen the app multiple times don't cost multiple requests.
- Debounce the Regenerate button — add a short cooldown (2–5 seconds) between successive regenerate calls. Power users tapping rapidly would otherwise consume their own session quota quickly.
- Don't generate on app cold start — only call the API when the user actively navigates to the workout tab, not on every app launch.
- Use the
excludeparam efficiently — passing the full 14-day history every call adds URL length but doesn't change quota cost. Trim to the last 7 days in production to keep URLs short.
Use Cases and Common Patterns
"Today's Workout" Feature
The highest-ROI integration. Call /v2/workout/generate when the user opens the workout tab. Because the response is freshly randomised (and you're using the exclude param for deduplication), users see a different routine every day without you building any session history logic beyond a simple localStorage array.
Regenerate Button
A "Shuffle" or "Don't like this workout" button that calls the endpoint again with the same base parameters. This is the highest-engagement pattern — users who dislike a particular exercise selection can instantly get a variation. Add a small loading state (the response comes back in under 100ms, but UX polish matters) and debounce rapid taps.
Home vs. Gym Mode
Let users toggle between equipment profiles. Pass the corresponding equipment array — a preset or a list of equipment and apparatus — and the generator handles the filtering, no exercise knowledge required on your side. Body weight is always allowed, so you never need to list it.
const EQUIPMENT_MODES = { bodyweight: ['bodyweight'], // preset: body weight only home: ['home'], // preset: body weight, dumbbell, kettlebell, band, bench minimal: ['dumbbell', 'band'], crossfit: ['barbell', 'kettlebell', 'pull-up bar', 'box'], gym: [], // omitting equipment = a full gym (same as ['gym']) }; const workout = await generateWorkout({ equipment: EQUIPMENT_MODES[userProfile.gymMode] || [], });
PPL / Upper-Lower Programme
For users following a structured split programme, let them select today's session. The generator handles exercise selection per split, and the _b variants lead with other lifts so the second push, pull or leg day of the week isn't a repeat — you just need a day picker:
// 6-day PPL split — auto-pick based on day of week const PPL_SCHEDULE = { Monday: 'push', Tuesday: 'pull', Wednesday: 'legs', Thursday: 'push_b', Friday: 'pull_b', Saturday: 'legs_b', Sunday: 'mobility' }; const today = new Date().toLocaleDateString('en-US', { weekday: 'long' }); const split = PPL_SCHEDULE[today] || 'full_body'; const workout = await generateWorkout({ split, goal: userProfile.goal });
For a whole plan with the progression built in, the Scale plan adds /v2/workout/program: a weekly schedule chosen from the goal and daysPerWeek, 2–16 weeks with deload weeks, accessory rotation each block and weekly volume per muscle group. See Workouts & programs in the docs.
Offline & Sync Considerations
If your app supports offline mode (common in mobile fitness apps where users work out in areas with poor connectivity), generate the workout while the user is online and cache it locally for offline playback. The exercise videos still need a connection to load: media links are streaming-only and expire after 24–25 hours, and downloading the files isn't permitted on any plan. Show the exercise names, instructions and prescriptions offline, and play the animations when the device is back online.
A practical pattern: when the user opens the app with a connection, silently pre-generate tomorrow's workout in the background and store it. If they open the app offline the next day, serve the pre-generated plan.
Rate Limits and Error Handling
The WorkoutX API enforces both per-minute rate limits and monthly quota limits. Understanding both helps you design your integration to avoid user-facing errors.
Per-Minute Rate Limits
The Growth plan allows 300 requests/minute; Scale allows 600/minute. For a workout generator called once per user action, you'd need to be serving multiple simultaneous users to hit these limits. That said, if you're generating workouts server-side in a batch job (e.g., pre-generating plans for all users nightly), you could hit the per-minute limit.
When you hit the rate limit, the API returns 429 Too Many Requests with a Retry-After header in seconds. Your client code should respect this — the production JS and Python examples above both implement this correctly.
Monthly Quota
Quota usage is tracked in the response headers: X-Quota-Remaining, X-Quota-Limit, and X-Quota-Reset. Log these in development to understand your usage pattern before going to production.
const res = await fetch(`${BASE}/workout/generate`, { headers: { ... } }); const remaining = res.headers.get('X-Quota-Remaining'); const limit = res.headers.get('X-Quota-Limit'); const reset = res.headers.get('X-Quota-Reset'); // Unix timestamp // Warn if under 10% remaining if (+remaining / +limit < 0.1) { console.warn(`Low quota: ${remaining}/${limit} remaining. Resets at ${new Date(+reset * 1000).toISOString()}`); }
Error codes summary
| Status | Code | Retry? | Action |
|---|---|---|---|
401 | Unauthorized | No | Invalid or missing API key |
403 | Plan Required | No | Upgrade to Growth or Scale |
422 | Invalid Params | No | Fix request parameters |
429 | Rate Limited | Yes, after Retry-After | Respect Retry-After header |
5xx | Server Error | Yes, with backoff | Exponential backoff, max 3 attempts |
Goal Presets: The Training Science
Each goal maps to a training prescription by role: the main lifts, secondary lifts and accessories of a session get different sets, reps, rest and effort. These aren't arbitrary numbers — they follow established strength, hypertrophy and conditioning programming:
| Goal | Main lifts | Secondary | Accessories | Format (auto) |
|---|---|---|---|---|
strength | 5 × 3-5, 180s rest, 80–87% of 1RM | 4 × 5-6, 150s, 75–80% of 1RM | 3 × 8-10, 90s | Straight sets |
muscle_gain | 4 × 6-8, 120s, 70–80% of 1RM, tempo 3-0-1-0 | 3 × 8-10, 90s | 3 × 10-15, 60s | Supersets up to 60 min |
general_fitness | 3 × 8-10, 90s | 3 × 10-12, 75s | 2 × 12-15, 60s | Supersets up to 60 min |
fat_loss | Circuit: 3–4 rounds, 30–45s work and 15–30s rest per station by level; rep stations 12-15 | Circuit | ||
endurance | Circuit: 3–4 rounds, 40–50s work and 10–20s rest per station by level; rep stations 15-20 | Circuit | ||
mobility | Mobility drills, yoga poses and stretches: 2–3 sets of 30–45s holds | Straight sets | ||
The level adjusts this: beginners do one set fewer on main and secondary lifts, stop further from failure and get no %1RM; advanced lifters add an accessory set and train closer to failure. Each exercise carries its effort target as rir (reps in reserve). The numbers above are the prescription before the session is fitted to duration, which can lower or raise set counts, and circuits add rounds while they fit. In every split template the main lifts come first, so the primary movements are performed fresh, not after the stabiliser muscles are fatigued from curls.
Workout Splits Reference
Each split is a template of movement patterns. The main lifts lead, then secondary lifts, accessories and core; slots that don't fit the time are skipped, so short sessions keep the main lifts.
| Split | Leads with | Best For |
|---|---|---|
full_body | Squat, horizontal press, hip hinge, pull | Beginners, 2–3 day/week programmes |
full_body_b | Hip hinge, overhead press, row | Second full-body day of the week |
full_body_c | Single-leg or front/goblet squat, incline or dumbbell press, vertical pull | Third full-body day |
upper / upper_b | Horizontal press and row / overhead press and vertical pull | Upper/lower split — 4 day/week |
lower / lower_b | Squat focus / hip hinge focus | Upper/lower split — leg days |
push / push_b | Horizontal and overhead press, fly, triceps | PPL split — push days |
pull / pull_b | Vertical pull and row, rear delts, biceps | PPL split — pull days |
legs / legs_b | Squat and hinge / hinge and single-leg | PPL split — leg days |
core | Stability, flexion and rotation, back extension | Core sessions and finishers |
conditioning | Full-body circuit: squat/lunge, press, cardio, hinge, row, jumps | Default for fat_loss and endurance |
mobility | Dynamic mobility, yoga poses, stretches, balance | Recovery days; always used for goal=mobility |
The v1 names push_pull_legs and upper_lower still work and map to full_body and upper.
Personalisation Strategies
The generator's twelve parameters give you more personalisation surface than it might first appear. Here are patterns used in production fitness apps:
Mapping User Profiles to Parameters
Most fitness apps collect a user profile on onboarding: goal, experience level, available equipment, preferred session length. Map these directly to generator parameters. No processing needed — the API parameters are designed to match exactly what users say about themselves.
function profileToWorkoutParams(user) { return { goal: user.fitnessGoal, // 'muscle_gain' | 'fat_loss' | ... level: user.experienceLevel, // 'beginner' | 'intermediate' | 'advanced' duration: user.preferredDuration, // 30 | 45 | 60 equipment: user.availableEquipment, // ['barbell','dumbbell'] or [] split: user.currentProgramSplit, // 'push' | 'pull' | 'full_body' | ... avoidJoints: user.jointsToProtect, // ['knee'] or [] — general guidance, not medical advice format: user.prefersCircuits ? 'circuit' : 'auto', exclude: getRecentExerciseIds(user.id), }; }
Progressive Overload Hints
The API doesn't track individual user load progression (weight on the bar, logged reps) — that's your app's domain. Each session gives users what they need to progress: a rep range, an effort target (rir) and, on main lifts, a load as a percentage of 1RM. You can also use the level parameter for a basic progression model: start users on beginner, promote to intermediate after 4–6 weeks of consistent activity, and to advanced after 6 months. This changes the exercise pool and the prescription. For planned progression over weeks — effort rising through each block, deload weeks, accessory rotation and a test week for strength — use /v2/workout/program on the Scale plan.
WorkoutX vs. Static Exercise APIs
There are a handful of free and paid exercise APIs available (ExerciseDB on RapidAPI being the most popular). They're different tools for different use cases — it's worth understanding the trade-offs.
Static Database APIs
Free exercise database APIs return a list of exercises you can filter by body part or equipment. They're perfect for:
- Searchable exercise libraries in your app
- Exercise detail pages with animations and instructions
- Reference content (SEO-driven exercise guides)
The limitation: you get raw data, not a programme. You have to write the "which exercises should I do today?" logic yourself — picking exercises, ordering them, assigning sets/reps/rest. Most developers underestimate how much domain knowledge that requires.
The second limitation: static exercise data can be downloaded once and cached indefinitely. A developer who needs your exercise database can download it in a single paginated API crawl and never call your API again. This is a common pattern that makes exercise data APIs difficult to monetise beyond a one-time purchase.
Why a Generator API Is Different
A workout generator API is inherently stateful per call — the randomisation, the duration calculation, the compound-first ordering, the exclusion logic. The response cannot be pre-downloaded and cached, because its value is in the freshness of the selection. Every call is genuinely different. This makes it a better product both for your users (variety) and for API monetisation (sustained usage).
WorkoutX approach: Use the exercise list endpoint for your exercise library and detail pages (search, browse, reference content), and /v2/workout/generate for active workout sessions. The two complement each other — one is static data, the other is a dynamic service.
Frequently Asked Questions
Is this actually AI, or just filtering?
It's a rule-based expert engine, not a large language model, and it doesn't use machine learning. It applies exercise science principles — movement-pattern templates, main lifts before accessories, goal- and level-specific prescriptions, supersets of opposing muscle groups, joint-aware exercise choice — encoded as deterministic server-side logic. Fast, consistent, and free of hallucinations. The "AI" framing reflects the decision-making (which exercise fits each slot, how many sets fit the time, what to swap in), not the technology stack.
What happens if no exercises match my equipment filter?
Equipment is never ignored. Body weight is always allowed, and each slot takes the best exercise that fits, so most setups fill every slot. A slot with no fitting exercise is left out, and with avoidJoints a gentler movement pattern stands in where one is ruled out. If nothing fits at all, exercises comes back empty and notes says to add equipment or remove joint restrictions — check for that case in your UI.
Can I cache the response?
You can, but cache strategically. Caching for the duration of a user's workout session (to support offline mid-workout) is sensible. Caching for multiple days removes the variety that makes the generator valuable. See the caching section above for a daily-cache pattern that balances quota efficiency with freshness.
Is it safe to call from a mobile app?
No — always proxy through your backend. Embedding an API key in a mobile binary is a security risk. See the mobile proxy section for the recommended architecture.
Does each call count as one request?
Yes. One call to /v2/workout/generate = one request against your monthly quota, regardless of how many exercises are in the response.
Can I use bodyFocus and split together?
bodyFocus overrides split entirely. If you pass both, bodyFocus takes precedence, split is ignored and the response says "split": "custom". Use split for named programmes (PPL, upper/lower), and bodyFocus when you need to target specific muscle groups that don't map to a standard split. With goal=mobility, bodyFocus picks the muscles to stretch.
Next Steps
Ready to ship a workout generator in your app?
Want to put the generator behind a chat interface instead? Our guide on how to build a fitness GPT with an exercise API walks through the Custom GPT Actions setup and a Claude tool-calling example.
- Get your API key — sign up free, upgrade to Growth for workout generation
- Workouts & programs documentation — parameter reference and response shapes
- Authentication guide — API key setup and header format
- Rate limits & quotas — per-plan limits and header reference
- Similar and alternatives endpoints —
GET /v2/exercises/{id}/similarand/alternativesshow substitutions when a user can't do a specific movement - How to Build a Workout App from Scratch — architecture guide covering auth, exercise data, workout logging, and progress tracking
Quick test: The endpoint responds in under 100ms on cold requests. Try it with curl using your API key — a complete workout plan comes back before you can blink. No warmup, no infrastructure, no ML setup.
Related Developer Resources
How to Build a Workout App
Full architecture guide — auth, data, logging, progress tracking
Best Exercise APIs in 2026
Comparison of exercise database and workout planner APIs
Exercise API in React
Step-by-step tutorial — hooks, components, video rendering
Top 10 Exercise Databases
Ranked roundup of exercise database APIs for fitness apps
Similar Exercises API
Find substitutions for any exercise — same muscle, different equipment
Add the AI Workout Generator to your app
Available on Growth ($39/month) and Scale ($79/month). Upgrade your existing key or sign up in 30 seconds.