feat: Initial commit of FitTrack_GarminSync project

This commit is contained in:
2025-10-10 12:20:48 -07:00
parent d0e29fbeb4
commit 18f9f6fa18
229 changed files with 21035 additions and 42 deletions

4
.env Normal file
View File

@@ -0,0 +1,4 @@
GARMIN_CONNECT_EMAIL="stuart.stent@gmail.com"
GARMIN_CONNECT_PASSWORD="Stainless7?Lisp?Strangle"
DATABASE_URL="sqlite:///./garmin_sync.db"
API_PORT=8001

View File

@@ -34,7 +34,6 @@ Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --inclu
- TASKS = FEATURE_DIR/tasks.md
Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command).
For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
### 2. Load Artifacts (Progressive Disclosure)

View File

@@ -36,7 +36,6 @@ You **MUST** consider the user input before proceeding (if not empty).
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS list.
- All file paths must be absolute.
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Clarify intent (dynamic)**: Derive up to THREE initial contextual clarifying questions (no pre-baked catalog). They MUST:
- Be generated from the user's phrasing + extracted signals from spec/plan/tasks

View File

@@ -26,7 +26,6 @@ Execution steps:
- `FEATURE_SPEC`
- (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.)
- If JSON parsing fails, abort and instruct user to re-run `/speckit.specify` or verify feature branch environment.
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked).

View File

@@ -15,7 +15,7 @@ You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute.
2. **Check checklists status** (if FEATURE_DIR/checklists/ exists):
- Scan all checklist files in the checklists/ directory

View File

@@ -15,7 +15,7 @@ You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. **Setup**: Run `.specify/scripts/bash/setup-plan.sh --json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, SPECS_DIR, BRANCH. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
1. **Setup**: Run `.specify/scripts/bash/setup-plan.sh --json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, SPECS_DIR, BRANCH.
2. **Load context**: Read FEATURE_SPEC and `.specify.specify/memory/constitution.md`. Load IMPL_PLAN template (already copied).

View File

@@ -20,7 +20,7 @@ The text the user typed after `/speckit.specify` in the triggering message **is*
Given that feature description, do this:
1. Run the script `.specify/scripts/bash/create-new-feature.sh --json "{{args}}"` from repo root and parse its JSON output for BRANCH_NAME and SPEC_FILE. All file paths must be absolute.
**IMPORTANT** You must only ever run this script once. The JSON is provided in the terminal as output - always refer to it to get the actual content you're looking for. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
**IMPORTANT** You must only ever run this script once. The JSON is provided in the terminal as output - always refer to it to get the actual content you're looking for.
2. Load `.specify/templates/spec-template.md` to understand required sections.
3. Follow this execution flow:

View File

@@ -15,7 +15,7 @@ You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute.
2. **Load design documents**: Read from FEATURE_DIR:
- **Required**: plan.md (tech stack, libraries, structure), spec.md (user stories with priorities)

View File

@@ -0,0 +1,2 @@
project_name: central-db-client
package_name: central_db_client

View File

@@ -0,0 +1,25 @@
# FitTrack_GarminSync Development Guidelines
Auto-generated from all feature plans. Last updated: 2025-10-09
## Active Technologies
- (002-intialspecv2)
## Project Structure
```
backend/
frontend/
tests/
```
## Commands
# Add commands for
## Code Style
: Follow standard conventions
## Recent Changes
- 002-intialspecv2: Added
<!-- MANUAL ADDITIONS START -->
<!-- MANUAL ADDITIONS END -->

View File

@@ -0,0 +1,184 @@
---
description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Goal
Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. This command MUST run only after `/tasks` has successfully produced a complete `tasks.md`.
## Operating Constraints
**STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually).
**Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is **non-negotiable** within this analysis scope. Constitution conflicts are automatically CRITICAL and require adjustment of the spec, plan, or tasks—not dilution, reinterpretation, or silent ignoring of the principle. If a principle itself needs to change, that must occur in a separate, explicit constitution update outside `/analyze`.
## Execution Steps
### 1. Initialize Analysis Context
Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths:
- SPEC = FEATURE_DIR/spec.md
- PLAN = FEATURE_DIR/plan.md
- TASKS = FEATURE_DIR/tasks.md
Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command).
For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
### 2. Load Artifacts (Progressive Disclosure)
Load only the minimal necessary context from each artifact:
**From spec.md:**
- Overview/Context
- Functional Requirements
- Non-Functional Requirements
- User Stories
- Edge Cases (if present)
**From plan.md:**
- Architecture/stack choices
- Data Model references
- Phases
- Technical constraints
**From tasks.md:**
- Task IDs
- Descriptions
- Phase grouping
- Parallel markers [P]
- Referenced file paths
**From constitution:**
- Load `.specify/memory/constitution.md` for principle validation
### 3. Build Semantic Models
Create internal representations (do not include raw artifacts in output):
- **Requirements inventory**: Each functional + non-functional requirement with a stable key (derive slug based on imperative phrase; e.g., "User can upload file" → `user-can-upload-file`)
- **User story/action inventory**: Discrete user actions with acceptance criteria
- **Task coverage mapping**: Map each task to one or more requirements or stories (inference by keyword / explicit reference patterns like IDs or key phrases)
- **Constitution rule set**: Extract principle names and MUST/SHOULD normative statements
### 4. Detection Passes (Token-Efficient Analysis)
Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary.
#### A. Duplication Detection
- Identify near-duplicate requirements
- Mark lower-quality phrasing for consolidation
#### B. Ambiguity Detection
- Flag vague adjectives (fast, scalable, secure, intuitive, robust) lacking measurable criteria
- Flag unresolved placeholders (TODO, TKTK, ???, `<placeholder>`, etc.)
#### C. Underspecification
- Requirements with verbs but missing object or measurable outcome
- User stories missing acceptance criteria alignment
- Tasks referencing files or components not defined in spec/plan
#### D. Constitution Alignment
- Any requirement or plan element conflicting with a MUST principle
- Missing mandated sections or quality gates from constitution
#### E. Coverage Gaps
- Requirements with zero associated tasks
- Tasks with no mapped requirement/story
- Non-functional requirements not reflected in tasks (e.g., performance, security)
#### F. Inconsistency
- Terminology drift (same concept named differently across files)
- Data entities referenced in plan but absent in spec (or vice versa)
- Task ordering contradictions (e.g., integration tasks before foundational setup tasks without dependency note)
- Conflicting requirements (e.g., one requires Next.js while other specifies Vue)
### 5. Severity Assignment
Use this heuristic to prioritize findings:
- **CRITICAL**: Violates constitution MUST, missing core spec artifact, or requirement with zero coverage that blocks baseline functionality
- **HIGH**: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion
- **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case
- **LOW**: Style/wording improvements, minor redundancy not affecting execution order
### 6. Produce Compact Analysis Report
Output a Markdown report (no file writes) with the following structure:
## Specification Analysis Report
| ID | Category | Severity | Location(s) | Summary | Recommendation |
|----|----------|----------|-------------|---------|----------------|
| A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version |
(Add one row per finding; generate stable IDs prefixed by category initial.)
**Coverage Summary Table:**
| Requirement Key | Has Task? | Task IDs | Notes |
|-----------------|-----------|----------|-------|
**Constitution Alignment Issues:** (if any)
**Unmapped Tasks:** (if any)
**Metrics:**
- Total Requirements
- Total Tasks
- Coverage % (requirements with >=1 task)
- Ambiguity Count
- Duplication Count
- Critical Issues Count
### 7. Provide Next Actions
At end of report, output a concise Next Actions block:
- If CRITICAL issues exist: Recommend resolving before `/implement`
- If only LOW/MEDIUM: User may proceed, but provide improvement suggestions
- Provide explicit command suggestions: e.g., "Run /specify with refinement", "Run /plan to adjust architecture", "Manually edit tasks.md to add coverage for 'performance-metrics'"
### 8. Offer Remediation
Ask the user: "Would you like me to suggest concrete remediation edits for the top N issues?" (Do NOT apply them automatically.)
## Operating Principles
### Context Efficiency
- **Minimal high-signal tokens**: Focus on actionable findings, not exhaustive documentation
- **Progressive disclosure**: Load artifacts incrementally; don't dump all content into analysis
- **Token-efficient output**: Limit findings table to 50 rows; summarize overflow
- **Deterministic results**: Rerunning without changes should produce consistent IDs and counts
### Analysis Guidelines
- **NEVER modify files** (this is read-only analysis)
- **NEVER hallucinate missing sections** (if absent, report them accurately)
- **Prioritize constitution violations** (these are always CRITICAL)
- **Use examples over exhaustive rules** (cite specific instances, not generic patterns)
- **Report zero issues gracefully** (emit success report with coverage statistics)
## Context
$ARGUMENTS

View File

@@ -0,0 +1,287 @@
---
description: Generate a custom checklist for the current feature based on user requirements.
---
## Checklist Purpose: "Unit Tests for English"
**CRITICAL CONCEPT**: Checklists are **UNIT TESTS FOR REQUIREMENTS WRITING** - they validate the quality, clarity, and completeness of requirements in a given domain.
**NOT for verification/testing**:
- ❌ NOT "Verify the button clicks correctly"
- ❌ NOT "Test error handling works"
- ❌ NOT "Confirm the API returns 200"
- ❌ NOT checking if code/implementation matches the spec
**FOR requirements quality validation**:
- ✅ "Are visual hierarchy requirements defined for all card types?" (completeness)
- ✅ "Is 'prominent display' quantified with specific sizing/positioning?" (clarity)
- ✅ "Are hover state requirements consistent across all interactive elements?" (consistency)
- ✅ "Are accessibility requirements defined for keyboard navigation?" (coverage)
- ✅ "Does the spec define what happens when logo image fails to load?" (edge cases)
**Metaphor**: If your spec is code written in English, the checklist is its unit test suite. You're testing whether the requirements are well-written, complete, unambiguous, and ready for implementation - NOT whether the implementation works.
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Execution Steps
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS list.
- All file paths must be absolute.
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Clarify intent (dynamic)**: Derive up to THREE initial contextual clarifying questions (no pre-baked catalog). They MUST:
- Be generated from the user's phrasing + extracted signals from spec/plan/tasks
- Only ask about information that materially changes checklist content
- Be skipped individually if already unambiguous in `$ARGUMENTS`
- Prefer precision over breadth
Generation algorithm:
1. Extract signals: feature domain keywords (e.g., auth, latency, UX, API), risk indicators ("critical", "must", "compliance"), stakeholder hints ("QA", "review", "security team"), and explicit deliverables ("a11y", "rollback", "contracts").
2. Cluster signals into candidate focus areas (max 4) ranked by relevance.
3. Identify probable audience & timing (author, reviewer, QA, release) if not explicit.
4. Detect missing dimensions: scope breadth, depth/rigor, risk emphasis, exclusion boundaries, measurable acceptance criteria.
5. Formulate questions chosen from these archetypes:
- Scope refinement (e.g., "Should this include integration touchpoints with X and Y or stay limited to local module correctness?")
- Risk prioritization (e.g., "Which of these potential risk areas should receive mandatory gating checks?")
- Depth calibration (e.g., "Is this a lightweight pre-commit sanity list or a formal release gate?")
- Audience framing (e.g., "Will this be used by the author only or peers during PR review?")
- Boundary exclusion (e.g., "Should we explicitly exclude performance tuning items this round?")
- Scenario class gap (e.g., "No recovery flows detected—are rollback / partial failure paths in scope?")
Question formatting rules:
- If presenting options, generate a compact table with columns: Option | Candidate | Why It Matters
- Limit to AE options maximum; omit table if a free-form answer is clearer
- Never ask the user to restate what they already said
- Avoid speculative categories (no hallucination). If uncertain, ask explicitly: "Confirm whether X belongs in scope."
Defaults when interaction impossible:
- Depth: Standard
- Audience: Reviewer (PR) if code-related; Author otherwise
- Focus: Top 2 relevance clusters
Output the questions (label Q1/Q2/Q3). After answers: if ≥2 scenario classes (Alternate / Exception / Recovery / Non-Functional domain) remain unclear, you MAY ask up to TWO more targeted followups (Q4/Q5) with a one-line justification each (e.g., "Unresolved recovery path risk"). Do not exceed five total questions. Skip escalation if user explicitly declines more.
3. **Understand user request**: Combine `$ARGUMENTS` + clarifying answers:
- Derive checklist theme (e.g., security, review, deploy, ux)
- Consolidate explicit must-have items mentioned by user
- Map focus selections to category scaffolding
- Infer any missing context from spec/plan/tasks (do NOT hallucinate)
4. **Load feature context**: Read from FEATURE_DIR:
- spec.md: Feature requirements and scope
- plan.md (if exists): Technical details, dependencies
- tasks.md (if exists): Implementation tasks
**Context Loading Strategy**:
- Load only necessary portions relevant to active focus areas (avoid full-file dumping)
- Prefer summarizing long sections into concise scenario/requirement bullets
- Use progressive disclosure: add follow-on retrieval only if gaps detected
- If source docs are large, generate interim summary items instead of embedding raw text
5. **Generate checklist** - Create "Unit Tests for Requirements":
- Create `FEATURE_DIR/checklists/` directory if it doesn't exist
- Generate unique checklist filename:
- Use short, descriptive name based on domain (e.g., `ux.md`, `api.md`, `security.md`)
- Format: `[domain].md`
- If file exists, append to existing file
- Number items sequentially starting from CHK001
- Each `/speckit.checklist` run creates a NEW file (never overwrites existing checklists)
**CORE PRINCIPLE - Test the Requirements, Not the Implementation**:
Every checklist item MUST evaluate the REQUIREMENTS THEMSELVES for:
- **Completeness**: Are all necessary requirements present?
- **Clarity**: Are requirements unambiguous and specific?
- **Consistency**: Do requirements align with each other?
- **Measurability**: Can requirements be objectively verified?
- **Coverage**: Are all scenarios/edge cases addressed?
**Category Structure** - Group items by requirement quality dimensions:
- **Requirement Completeness** (Are all necessary requirements documented?)
- **Requirement Clarity** (Are requirements specific and unambiguous?)
- **Requirement Consistency** (Do requirements align without conflicts?)
- **Acceptance Criteria Quality** (Are success criteria measurable?)
- **Scenario Coverage** (Are all flows/cases addressed?)
- **Edge Case Coverage** (Are boundary conditions defined?)
- **Non-Functional Requirements** (Performance, Security, Accessibility, etc. - are they specified?)
- **Dependencies & Assumptions** (Are they documented and validated?)
- **Ambiguities & Conflicts** (What needs clarification?)
**HOW TO WRITE CHECKLIST ITEMS - "Unit Tests for English"**:
**WRONG** (Testing implementation):
- "Verify landing page displays 3 episode cards"
- "Test hover states work on desktop"
- "Confirm logo click navigates home"
**CORRECT** (Testing requirements quality):
- "Are the exact number and layout of featured episodes specified?" [Completeness]
- "Is 'prominent display' quantified with specific sizing/positioning?" [Clarity]
- "Are hover state requirements consistent across all interactive elements?" [Consistency]
- "Are keyboard navigation requirements defined for all interactive UI?" [Coverage]
- "Is the fallback behavior specified when logo image fails to load?" [Edge Cases]
- "Are loading states defined for asynchronous episode data?" [Completeness]
- "Does the spec define visual hierarchy for competing UI elements?" [Clarity]
**ITEM STRUCTURE**:
Each item should follow this pattern:
- Question format asking about requirement quality
- Focus on what's WRITTEN (or not written) in the spec/plan
- Include quality dimension in brackets [Completeness/Clarity/Consistency/etc.]
- Reference spec section `[Spec §X.Y]` when checking existing requirements
- Use `[Gap]` marker when checking for missing requirements
**EXAMPLES BY QUALITY DIMENSION**:
Completeness:
- "Are error handling requirements defined for all API failure modes? [Gap]"
- "Are accessibility requirements specified for all interactive elements? [Completeness]"
- "Are mobile breakpoint requirements defined for responsive layouts? [Gap]"
Clarity:
- "Is 'fast loading' quantified with specific timing thresholds? [Clarity, Spec §NFR-2]"
- "Are 'related episodes' selection criteria explicitly defined? [Clarity, Spec §FR-5]"
- "Is 'prominent' defined with measurable visual properties? [Ambiguity, Spec §FR-4]"
Consistency:
- "Do navigation requirements align across all pages? [Consistency, Spec §FR-10]"
- "Are card component requirements consistent between landing and detail pages? [Consistency]"
Coverage:
- "Are requirements defined for zero-state scenarios (no episodes)? [Coverage, Edge Case]"
- "Are concurrent user interaction scenarios addressed? [Coverage, Gap]"
- "Are requirements specified for partial data loading failures? [Coverage, Exception Flow]"
Measurability:
- "Are visual hierarchy requirements measurable/testable? [Acceptance Criteria, Spec §FR-1]"
- "Can 'balanced visual weight' be objectively verified? [Measurability, Spec §FR-2]"
**Scenario Classification & Coverage** (Requirements Quality Focus):
- Check if requirements exist for: Primary, Alternate, Exception/Error, Recovery, Non-Functional scenarios
- For each scenario class, ask: "Are [scenario type] requirements complete, clear, and consistent?"
- If scenario class missing: "Are [scenario type] requirements intentionally excluded or missing? [Gap]"
- Include resilience/rollback when state mutation occurs: "Are rollback requirements defined for migration failures? [Gap]"
**Traceability Requirements**:
- MINIMUM: ≥80% of items MUST include at least one traceability reference
- Each item should reference: spec section `[Spec §X.Y]`, or use markers: `[Gap]`, `[Ambiguity]`, `[Conflict]`, `[Assumption]`
- If no ID system exists: "Is a requirement & acceptance criteria ID scheme established? [Traceability]"
**Surface & Resolve Issues** (Requirements Quality Problems):
Ask questions about the requirements themselves:
- Ambiguities: "Is the term 'fast' quantified with specific metrics? [Ambiguity, Spec §NFR-1]"
- Conflicts: "Do navigation requirements conflict between §FR-10 and §FR-10a? [Conflict]"
- Assumptions: "Is the assumption of 'always available podcast API' validated? [Assumption]"
- Dependencies: "Are external podcast API requirements documented? [Dependency, Gap]"
- Missing definitions: "Is 'visual hierarchy' defined with measurable criteria? [Gap]"
**Content Consolidation**:
- Soft cap: If raw candidate items > 40, prioritize by risk/impact
- Merge near-duplicates checking the same requirement aspect
- If >5 low-impact edge cases, create one item: "Are edge cases X, Y, Z addressed in requirements? [Coverage]"
**🚫 ABSOLUTELY PROHIBITED** - These make it an implementation test, not a requirements test:
- ❌ Any item starting with "Verify", "Test", "Confirm", "Check" + implementation behavior
- ❌ References to code execution, user actions, system behavior
- ❌ "Displays correctly", "works properly", "functions as expected"
- ❌ "Click", "navigate", "render", "load", "execute"
- ❌ Test cases, test plans, QA procedures
- ❌ Implementation details (frameworks, APIs, algorithms)
**✅ REQUIRED PATTERNS** - These test requirements quality:
- ✅ "Are [requirement type] defined/specified/documented for [scenario]?"
- ✅ "Is [vague term] quantified/clarified with specific criteria?"
- ✅ "Are requirements consistent between [section A] and [section B]?"
- ✅ "Can [requirement] be objectively measured/verified?"
- ✅ "Are [edge cases/scenarios] addressed in requirements?"
- ✅ "Does the spec define [missing aspect]?"
6. **Structure Reference**: Generate the checklist following the canonical template in `.specify/templates/checklist-template.md` for title, meta section, category headings, and ID formatting. If template is unavailable, use: H1 title, purpose/created meta lines, `##` category sections containing `- [ ] CHK### <requirement item>` lines with globally incrementing IDs starting at CHK001.
7. **Report**: Output full path to created checklist, item count, and remind user that each run creates a new file. Summarize:
- Focus areas selected
- Depth level
- Actor/timing
- Any explicit user-specified must-have items incorporated
**Important**: Each `/speckit.checklist` command invocation creates a checklist file using short, descriptive names unless file already exists. This allows:
- Multiple checklists of different types (e.g., `ux.md`, `test.md`, `security.md`)
- Simple, memorable filenames that indicate checklist purpose
- Easy identification and navigation in the `checklists/` folder
To avoid clutter, use descriptive types and clean up obsolete checklists when done.
## Example Checklist Types & Sample Items
**UX Requirements Quality:** `ux.md`
Sample items (testing the requirements, NOT the implementation):
- "Are visual hierarchy requirements defined with measurable criteria? [Clarity, Spec §FR-1]"
- "Is the number and positioning of UI elements explicitly specified? [Completeness, Spec §FR-1]"
- "Are interaction state requirements (hover, focus, active) consistently defined? [Consistency]"
- "Are accessibility requirements specified for all interactive elements? [Coverage, Gap]"
- "Is fallback behavior defined when images fail to load? [Edge Case, Gap]"
- "Can 'prominent display' be objectively measured? [Measurability, Spec §FR-4]"
**API Requirements Quality:** `api.md`
Sample items:
- "Are error response formats specified for all failure scenarios? [Completeness]"
- "Are rate limiting requirements quantified with specific thresholds? [Clarity]"
- "Are authentication requirements consistent across all endpoints? [Consistency]"
- "Are retry/timeout requirements defined for external dependencies? [Coverage, Gap]"
- "Is versioning strategy documented in requirements? [Gap]"
**Performance Requirements Quality:** `performance.md`
Sample items:
- "Are performance requirements quantified with specific metrics? [Clarity]"
- "Are performance targets defined for all critical user journeys? [Coverage]"
- "Are performance requirements under different load conditions specified? [Completeness]"
- "Can performance requirements be objectively measured? [Measurability]"
- "Are degradation requirements defined for high-load scenarios? [Edge Case, Gap]"
**Security Requirements Quality:** `security.md`
Sample items:
- "Are authentication requirements specified for all protected resources? [Coverage]"
- "Are data protection requirements defined for sensitive information? [Completeness]"
- "Is the threat model documented and requirements aligned to it? [Traceability]"
- "Are security requirements consistent with compliance obligations? [Consistency]"
- "Are security failure/breach response requirements defined? [Gap, Exception Flow]"
## Anti-Examples: What NOT To Do
**❌ WRONG - These test implementation, not requirements:**
```markdown
- [ ] CHK001 - Verify landing page displays 3 episode cards [Spec §FR-001]
- [ ] CHK002 - Test hover states work correctly on desktop [Spec §FR-003]
- [ ] CHK003 - Confirm logo click navigates to home page [Spec §FR-010]
- [ ] CHK004 - Check that related episodes section shows 3-5 items [Spec §FR-005]
```
**✅ CORRECT - These test requirements quality:**
```markdown
- [ ] CHK001 - Are the number and layout of featured episodes explicitly specified? [Completeness, Spec §FR-001]
- [ ] CHK002 - Are hover state requirements consistently defined for all interactive elements? [Consistency, Spec §FR-003]
- [ ] CHK003 - Are navigation requirements clear for all clickable brand elements? [Clarity, Spec §FR-010]
- [ ] CHK004 - Is the selection criteria for related episodes documented? [Gap, Spec §FR-005]
- [ ] CHK005 - Are loading state requirements defined for asynchronous episode data? [Gap]
- [ ] CHK006 - Can "visual hierarchy" requirements be objectively measured? [Measurability, Spec §FR-001]
```
**Key Differences:**
- Wrong: Tests if the system works correctly
- Correct: Tests if the requirements are written correctly
- Wrong: Verification of behavior
- Correct: Validation of requirement quality
- Wrong: "Does it do X?"
- Correct: "Is X clearly specified?"

View File

@@ -0,0 +1,163 @@
---
description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
Goal: Detect and reduce ambiguity or missing decision points in the active feature specification and record the clarifications directly in the spec file.
Note: This clarification workflow is expected to run (and be completed) BEFORE invoking `/speckit.plan`. If the user explicitly states they are skipping clarification (e.g., exploratory spike), you may proceed, but must warn that downstream rework risk increases.
Execution steps:
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --paths-only` from repo root **once** (combined `--json --paths-only` mode / `-Json -PathsOnly`). Parse minimal JSON payload fields:
- `FEATURE_DIR`
- `FEATURE_SPEC`
- (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.)
- If JSON parsing fails, abort and instruct user to re-run `/speckit.specify` or verify feature branch environment.
- For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked).
Functional Scope & Behavior:
- Core user goals & success criteria
- Explicit out-of-scope declarations
- User roles / personas differentiation
Domain & Data Model:
- Entities, attributes, relationships
- Identity & uniqueness rules
- Lifecycle/state transitions
- Data volume / scale assumptions
Interaction & UX Flow:
- Critical user journeys / sequences
- Error/empty/loading states
- Accessibility or localization notes
Non-Functional Quality Attributes:
- Performance (latency, throughput targets)
- Scalability (horizontal/vertical, limits)
- Reliability & availability (uptime, recovery expectations)
- Observability (logging, metrics, tracing signals)
- Security & privacy (authN/Z, data protection, threat assumptions)
- Compliance / regulatory constraints (if any)
Integration & External Dependencies:
- External services/APIs and failure modes
- Data import/export formats
- Protocol/versioning assumptions
Edge Cases & Failure Handling:
- Negative scenarios
- Rate limiting / throttling
- Conflict resolution (e.g., concurrent edits)
Constraints & Tradeoffs:
- Technical constraints (language, storage, hosting)
- Explicit tradeoffs or rejected alternatives
Terminology & Consistency:
- Canonical glossary terms
- Avoided synonyms / deprecated terms
Completion Signals:
- Acceptance criteria testability
- Measurable Definition of Done style indicators
Misc / Placeholders:
- TODO markers / unresolved decisions
- Ambiguous adjectives ("robust", "intuitive") lacking quantification
For each category with Partial or Missing status, add a candidate question opportunity unless:
- Clarification would not materially change implementation or validation strategy
- Information is better deferred to planning phase (note internally)
3. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints:
- Maximum of 10 total questions across the whole session.
- Each question must be answerable with EITHER:
* A short multiplechoice selection (25 distinct, mutually exclusive options), OR
* A one-word / shortphrase answer (explicitly constrain: "Answer in <=5 words").
- Only include questions whose answers materially impact architecture, data modeling, task decomposition, test design, UX behavior, operational readiness, or compliance validation.
- Ensure category coverage balance: attempt to cover the highest impact unresolved categories first; avoid asking two low-impact questions when a single high-impact area (e.g., security posture) is unresolved.
- Exclude questions already answered, trivial stylistic preferences, or plan-level execution details (unless blocking correctness).
- Favor clarifications that reduce downstream rework risk or prevent misaligned acceptance tests.
- If more than 5 categories remain unresolved, select the top 5 by (Impact * Uncertainty) heuristic.
4. Sequential questioning loop (interactive):
- Present EXACTLY ONE question at a time.
- For multiplechoice questions render options as a Markdown table:
| Option | Description |
|--------|-------------|
| A | <Option A description> |
| B | <Option B description> |
| C | <Option C description> | (add D/E as needed up to 5)
| Short | Provide a different short answer (<=5 words) | (Include only if free-form alternative is appropriate)
- For shortanswer style (no meaningful discrete options), output a single line after the question: `Format: Short answer (<=5 words)`.
- After the user answers:
* Validate the answer maps to one option or fits the <=5 word constraint.
* If ambiguous, ask for a quick disambiguation (count still belongs to same question; do not advance).
* Once satisfactory, record it in working memory (do not yet write to disk) and move to the next queued question.
- Stop asking further questions when:
* All critical ambiguities resolved early (remaining queued items become unnecessary), OR
* User signals completion ("done", "good", "no more"), OR
* You reach 5 asked questions.
- Never reveal future queued questions in advance.
- If no valid questions exist at start, immediately report no critical ambiguities.
5. Integration after EACH accepted answer (incremental update approach):
- Maintain in-memory representation of the spec (loaded once at start) plus the raw file contents.
- For the first integrated answer in this session:
* Ensure a `## Clarifications` section exists (create it just after the highest-level contextual/overview section per the spec template if missing).
* Under it, create (if not present) a `### Session YYYY-MM-DD` subheading for today.
- Append a bullet line immediately after acceptance: `- Q: <question> → A: <final answer>`.
- Then immediately apply the clarification to the most appropriate section(s):
* Functional ambiguity → Update or add a bullet in Functional Requirements.
* User interaction / actor distinction → Update User Stories or Actors subsection (if present) with clarified role, constraint, or scenario.
* Data shape / entities → Update Data Model (add fields, types, relationships) preserving ordering; note added constraints succinctly.
* Non-functional constraint → Add/modify measurable criteria in Non-Functional / Quality Attributes section (convert vague adjective to metric or explicit target).
* Edge case / negative flow → Add a new bullet under Edge Cases / Error Handling (or create such subsection if template provides placeholder for it).
* Terminology conflict → Normalize term across spec; retain original only if necessary by adding `(formerly referred to as "X")` once.
- If the clarification invalidates an earlier ambiguous statement, replace that statement instead of duplicating; leave no obsolete contradictory text.
- Save the spec file AFTER each integration to minimize risk of context loss (atomic overwrite).
- Preserve formatting: do not reorder unrelated sections; keep heading hierarchy intact.
- Keep each inserted clarification minimal and testable (avoid narrative drift).
6. Validation (performed after EACH write plus final pass):
- Clarifications session contains exactly one bullet per accepted answer (no duplicates).
- Total asked (accepted) questions ≤ 5.
- Updated sections contain no lingering vague placeholders the new answer was meant to resolve.
- No contradictory earlier statement remains (scan for now-invalid alternative choices removed).
- Markdown structure valid; only allowed new headings: `## Clarifications`, `### Session YYYY-MM-DD`.
- Terminology consistency: same canonical term used across all updated sections.
7. Write the updated spec back to `FEATURE_SPEC`.
8. Report completion (after questioning loop ends or early termination):
- Number of questions asked & answered.
- Path to updated spec.
- Sections touched (list names).
- Coverage summary table listing each taxonomy category with Status: Resolved (was Partial/Missing and addressed), Deferred (exceeds question quota or better suited for planning), Clear (already sufficient), Outstanding (still Partial/Missing but low impact).
- If any Outstanding or Deferred remain, recommend whether to proceed to `/speckit.plan` or run `/speckit.clarify` again later post-plan.
- Suggested next command.
Behavior rules:
- If no meaningful ambiguities found (or all potential questions would be low-impact), respond: "No critical ambiguities detected worth formal clarification." and suggest proceeding.
- If spec file missing, instruct user to run `/speckit.specify` first (do not create a new spec here).
- Never exceed 5 total asked questions (clarification retries for a single question do not count as new questions).
- Avoid speculative tech stack questions unless the absence blocks functional clarity.
- Respect user early termination signals ("stop", "done", "proceed").
- If no questions asked due to full coverage, output a compact coverage summary (all categories Clear) then suggest advancing.
- If quota reached with unresolved high-impact categories remaining, explicitly flag them under Deferred with rationale.
Context for prioritization: $ARGUMENTS

View File

@@ -0,0 +1,77 @@
---
description: Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
You are updating the project constitution at `.specify/memory/constitution.md`. This file is a TEMPLATE containing placeholder tokens in square brackets (e.g. `[PROJECT_NAME]`, `[PRINCIPLE_1_NAME]`). Your job is to (a) collect/derive concrete values, (b) fill the template precisely, and (c) propagate any amendments across dependent artifacts.
Follow this execution flow:
1. Load the existing constitution template at `.specify/memory/constitution.md`.
- Identify every placeholder token of the form `[ALL_CAPS_IDENTIFIER]`.
**IMPORTANT**: The user might require less or more principles than the ones used in the template. If a number is specified, respect that - follow the general template. You will update the doc accordingly.
2. Collect/derive values for placeholders:
- If user input (conversation) supplies a value, use it.
- Otherwise infer from existing repo context (README, docs, prior constitution versions if embedded).
- For governance dates: `RATIFICATION_DATE` is the original adoption date (if unknown ask or mark TODO), `LAST_AMENDED_DATE` is today if changes are made, otherwise keep previous.
- `CONSTITUTION_VERSION` must increment according to semantic versioning rules:
* MAJOR: Backward incompatible governance/principle removals or redefinitions.
* MINOR: New principle/section added or materially expanded guidance.
* PATCH: Clarifications, wording, typo fixes, non-semantic refinements.
- If version bump type ambiguous, propose reasoning before finalizing.
3. Draft the updated constitution content:
- Replace every placeholder with concrete text (no bracketed tokens left except intentionally retained template slots that the project has chosen not to define yet—explicitly justify any left).
- Preserve heading hierarchy and comments can be removed once replaced unless they still add clarifying guidance.
- Ensure each Principle section: succinct name line, paragraph (or bullet list) capturing nonnegotiable rules, explicit rationale if not obvious.
- Ensure Governance section lists amendment procedure, versioning policy, and compliance review expectations.
4. Consistency propagation checklist (convert prior checklist into active validations):
- Read `.specify/templates/plan-template.md` and ensure any "Constitution Check" or rules align with updated principles.
- Read `.specify/templates/spec-template.md` for scope/requirements alignment—update if constitution adds/removes mandatory sections or constraints.
- Read `.specify/templates/tasks-template.md` and ensure task categorization reflects new or removed principle-driven task types (e.g., observability, versioning, testing discipline).
- Read each command file in `.specify/templates/commands/*.md` (including this one) to verify no outdated references (agent-specific names like CLAUDE only) remain when generic guidance is required.
- Read any runtime guidance docs (e.g., `README.md`, `docs/quickstart.md`, or agent-specific guidance files if present). Update references to principles changed.
5. Produce a Sync Impact Report (prepend as an HTML comment at top of the constitution file after update):
- Version change: old → new
- List of modified principles (old title → new title if renamed)
- Added sections
- Removed sections
- Templates requiring updates (✅ updated / ⚠ pending) with file paths
- Follow-up TODOs if any placeholders intentionally deferred.
6. Validation before final output:
- No remaining unexplained bracket tokens.
- Version line matches report.
- Dates ISO format YYYY-MM-DD.
- Principles are declarative, testable, and free of vague language ("should" → replace with MUST/SHOULD rationale where appropriate).
7. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite).
8. Output a final summary to the user with:
- New version and bump rationale.
- Any files flagged for manual follow-up.
- Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`).
Formatting & Style Requirements:
- Use Markdown headings exactly as in the template (do not demote/promote levels).
- Wrap long rationale lines to keep readability (<100 chars ideally) but do not hard enforce with awkward breaks.
- Keep a single blank line between sections.
- Avoid trailing whitespace.
If the user supplies partial updates (e.g., only one principle revision), still perform validation and version decision steps.
If critical info missing (e.g., ratification date truly unknown), insert `TODO(<FIELD_NAME>): explanation` and include in the Sync Impact Report under deferred items.
Do not create a new template; always operate on the existing `.specify/memory/constitution.md` file.

View File

@@ -0,0 +1,89 @@
---
description: Execute the implementation plan by processing and executing all tasks defined in tasks.md
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Check checklists status** (if FEATURE_DIR/checklists/ exists):
- Scan all checklist files in the checklists/ directory
- For each checklist, count:
* Total items: All lines matching `- [ ]` or `- [X]` or `- [x]`
* Completed items: Lines matching `- [X]` or `- [x]`
* Incomplete items: Lines matching `- [ ]`
- Create a status table:
```
| Checklist | Total | Completed | Incomplete | Status |
|-----------|-------|-----------|------------|--------|
| ux.md | 12 | 12 | 0 | ✓ PASS |
| test.md | 8 | 5 | 3 | ✗ FAIL |
| security.md | 6 | 6 | 0 | ✓ PASS |
```
- Calculate overall status:
* **PASS**: All checklists have 0 incomplete items
* **FAIL**: One or more checklists have incomplete items
- **If any checklist is incomplete**:
* Display the table with incomplete item counts
* **STOP** and ask: "Some checklists are incomplete. Do you want to proceed with implementation anyway? (yes/no)"
* Wait for user response before continuing
* If user says "no" or "wait" or "stop", halt execution
* If user says "yes" or "proceed" or "continue", proceed to step 3
- **If all checklists are complete**:
* Display the table showing all checklists passed
* Automatically proceed to step 3
3. Load and analyze the implementation context:
- **REQUIRED**: Read tasks.md for the complete task list and execution plan
- **REQUIRED**: Read plan.md for tech stack, architecture, and file structure
- **IF EXISTS**: Read data-model.md for entities and relationships
- **IF EXISTS**: Read contracts/ for API specifications and test requirements
- **IF EXISTS**: Read research.md for technical decisions and constraints
- **IF EXISTS**: Read quickstart.md for integration scenarios
4. Parse tasks.md structure and extract:
- **Task phases**: Setup, Tests, Core, Integration, Polish
- **Task dependencies**: Sequential vs parallel execution rules
- **Task details**: ID, description, file paths, parallel markers [P]
- **Execution flow**: Order and dependency requirements
5. Execute implementation following the task plan:
- **Phase-by-phase execution**: Complete each phase before moving to the next
- **Respect dependencies**: Run sequential tasks in order, parallel tasks [P] can run together
- **Follow TDD approach**: Execute test tasks before their corresponding implementation tasks
- **File-based coordination**: Tasks affecting the same files must run sequentially
- **Validation checkpoints**: Verify each phase completion before proceeding
6. Implementation execution rules:
- **Setup first**: Initialize project structure, dependencies, configuration
- **Tests before code**: If you need to write tests for contracts, entities, and integration scenarios
- **Core development**: Implement models, services, CLI commands, endpoints
- **Integration work**: Database connections, middleware, logging, external services
- **Polish and validation**: Unit tests, performance optimization, documentation
7. Progress tracking and error handling:
- Report progress after each completed task
- Halt execution if any non-parallel task fails
- For parallel tasks [P], continue with successful tasks, report failed ones
- Provide clear error messages with context for debugging
- Suggest next steps if implementation cannot proceed
- **IMPORTANT** For completed tasks, make sure to mark the task off as [X] in the tasks file.
8. Completion validation:
- Verify all required tasks are completed
- Check that implemented features match the original specification
- Validate that tests pass and coverage meets requirements
- Confirm the implementation follows the technical plan
- Report final status with summary of completed work
Note: This command assumes a complete task breakdown exists in tasks.md. If tasks are incomplete or missing, suggest running `/tasks` first to regenerate the task list.

View File

@@ -0,0 +1,80 @@
---
description: Execute the implementation planning workflow using the plan template to generate design artifacts.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. **Setup**: Run `.specify/scripts/bash/setup-plan.sh --json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, SPECS_DIR, BRANCH. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Load context**: Read FEATURE_SPEC and `.specify.specify/memory/constitution.md`. Load IMPL_PLAN template (already copied).
3. **Execute plan workflow**: Follow the structure in IMPL_PLAN template to:
- Fill Technical Context (mark unknowns as "NEEDS CLARIFICATION")
- Fill Constitution Check section from constitution
- Evaluate gates (ERROR if violations unjustified)
- Phase 0: Generate research.md (resolve all NEEDS CLARIFICATION)
- Phase 1: Generate data-model.md, contracts/, quickstart.md
- Phase 1: Update agent context by running the agent script
- Re-evaluate Constitution Check post-design
4. **Stop and report**: Command ends after Phase 2 planning. Report branch, IMPL_PLAN path, and generated artifacts.
## Phases
### Phase 0: Outline & Research
1. **Extract unknowns from Technical Context** above:
- For each NEEDS CLARIFICATION → research task
- For each dependency → best practices task
- For each integration → patterns task
2. **Generate and dispatch research agents**:
```
For each unknown in Technical Context:
Task: "Research {unknown} for {feature context}"
For each technology choice:
Task: "Find best practices for {tech} in {domain}"
```
3. **Consolidate findings** in `research.md` using format:
- Decision: [what was chosen]
- Rationale: [why chosen]
- Alternatives considered: [what else evaluated]
**Output**: research.md with all NEEDS CLARIFICATION resolved
### Phase 1: Design & Contracts
**Prerequisites:** `research.md` complete
1. **Extract entities from feature spec** → `data-model.md`:
- Entity name, fields, relationships
- Validation rules from requirements
- State transitions if applicable
2. **Generate API contracts** from functional requirements:
- For each user action → endpoint
- Use standard REST/GraphQL patterns
- Output OpenAPI/GraphQL schema to `/contracts/`
3. **Agent context update**:
- Run `.specify/scripts/bash/update-agent-context.sh kilocode`
- These scripts detect which AI agent is in use
- Update the appropriate agent-specific context file
- Add only new technology from current plan
- Preserve manual additions between markers
**Output**: data-model.md, /contracts/*, quickstart.md, agent-specific file
## Key rules
- Use absolute paths
- ERROR on gate failures or unresolved clarifications

View File

@@ -0,0 +1,208 @@
---
description: Create or update the feature specification from a natural language feature description.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
The text the user typed after `/speckit.specify` in the triggering message **is** the feature description. Assume you always have it available in this conversation even if `$ARGUMENTS` appears literally below. Do not ask the user to repeat it unless they provided an empty command.
Given that feature description, do this:
1. Run the script `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS"` from repo root and parse its JSON output for BRANCH_NAME and SPEC_FILE. All file paths must be absolute.
**IMPORTANT** You must only ever run this script once. The JSON is provided in the terminal as output - always refer to it to get the actual content you're looking for. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. Load `.specify/templates/spec-template.md` to understand required sections.
3. Follow this execution flow:
1. Parse user description from Input
If empty: ERROR "No feature description provided"
2. Extract key concepts from description
Identify: actors, actions, data, constraints
3. For unclear aspects:
- Make informed guesses based on context and industry standards
- Only mark with [NEEDS CLARIFICATION: specific question] if:
- The choice significantly impacts feature scope or user experience
- Multiple reasonable interpretations exist with different implications
- No reasonable default exists
- **LIMIT: Maximum 3 [NEEDS CLARIFICATION] markers total**
- Prioritize clarifications by impact: scope > security/privacy > user experience > technical details
4. Fill User Scenarios & Testing section
If no clear user flow: ERROR "Cannot determine user scenarios"
5. Generate Functional Requirements
Each requirement must be testable
Use reasonable defaults for unspecified details (document assumptions in Assumptions section)
6. Define Success Criteria
Create measurable, technology-agnostic outcomes
Include both quantitative metrics (time, performance, volume) and qualitative measures (user satisfaction, task completion)
Each criterion must be verifiable without implementation details
7. Identify Key Entities (if data involved)
8. Return: SUCCESS (spec ready for planning)
4. Write the specification to SPEC_FILE using the template structure, replacing placeholders with concrete details derived from the feature description (arguments) while preserving section order and headings.
5. **Specification Quality Validation**: After writing the initial spec, validate it against quality criteria:
a. **Create Spec Quality Checklist**: Generate a checklist file at `FEATURE_DIR/checklists/requirements.md` using the checklist template structure with these validation items:
```markdown
# Specification Quality Checklist: [FEATURE NAME]
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: [DATE]
**Feature**: [Link to spec.md]
## Content Quality
- [ ] No implementation details (languages, frameworks, APIs)
- [ ] Focused on user value and business needs
- [ ] Written for non-technical stakeholders
- [ ] All mandatory sections completed
## Requirement Completeness
- [ ] No [NEEDS CLARIFICATION] markers remain
- [ ] Requirements are testable and unambiguous
- [ ] Success criteria are measurable
- [ ] Success criteria are technology-agnostic (no implementation details)
- [ ] All acceptance scenarios are defined
- [ ] Edge cases are identified
- [ ] Scope is clearly bounded
- [ ] Dependencies and assumptions identified
## Feature Readiness
- [ ] All functional requirements have clear acceptance criteria
- [ ] User scenarios cover primary flows
- [ ] Feature meets measurable outcomes defined in Success Criteria
- [ ] No implementation details leak into specification
## Notes
- Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan`
```
b. **Run Validation Check**: Review the spec against each checklist item:
- For each item, determine if it passes or fails
- Document specific issues found (quote relevant spec sections)
c. **Handle Validation Results**:
- **If all items pass**: Mark checklist complete and proceed to step 6
- **If items fail (excluding [NEEDS CLARIFICATION])**:
1. List the failing items and specific issues
2. Update the spec to address each issue
3. Re-run validation until all items pass (max 3 iterations)
4. If still failing after 3 iterations, document remaining issues in checklist notes and warn user
- **If [NEEDS CLARIFICATION] markers remain**:
1. Extract all [NEEDS CLARIFICATION: ...] markers from the spec
2. **LIMIT CHECK**: If more than 3 markers exist, keep only the 3 most critical (by scope/security/UX impact) and make informed guesses for the rest
3. For each clarification needed (max 3), present options to user in this format:
```markdown
## Question [N]: [Topic]
**Context**: [Quote relevant spec section]
**What we need to know**: [Specific question from NEEDS CLARIFICATION marker]
**Suggested Answers**:
| Option | Answer | Implications |
|--------|--------|--------------|
| A | [First suggested answer] | [What this means for the feature] |
| B | [Second suggested answer] | [What this means for the feature] |
| C | [Third suggested answer] | [What this means for the feature] |
| Custom | Provide your own answer | [Explain how to provide custom input] |
**Your choice**: _[Wait for user response]_
```
4. **CRITICAL - Table Formatting**: Ensure markdown tables are properly formatted:
- Use consistent spacing with pipes aligned
- Each cell should have spaces around content: `| Content |` not `|Content|`
- Header separator must have at least 3 dashes: `|--------|`
- Test that the table renders correctly in markdown preview
5. Number questions sequentially (Q1, Q2, Q3 - max 3 total)
6. Present all questions together before waiting for responses
7. Wait for user to respond with their choices for all questions (e.g., "Q1: A, Q2: Custom - [details], Q3: B")
8. Update the spec by replacing each [NEEDS CLARIFICATION] marker with the user's selected or provided answer
9. Re-run validation after all clarifications are resolved
d. **Update Checklist**: After each validation iteration, update the checklist file with current pass/fail status
6. Report completion with branch name, spec file path, checklist results, and readiness for the next phase (`/speckit.clarify` or `/speckit.plan`).
**NOTE:** The script creates and checks out the new branch and initializes the spec file before writing.
## General Guidelines
## Quick Guidelines
- Focus on **WHAT** users need and **WHY**.
- Avoid HOW to implement (no tech stack, APIs, code structure).
- Written for business stakeholders, not developers.
- DO NOT create any checklists that are embedded in the spec. That will be a separate command.
### Section Requirements
- **Mandatory sections**: Must be completed for every feature
- **Optional sections**: Include only when relevant to the feature
- When a section doesn't apply, remove it entirely (don't leave as "N/A")
### For AI Generation
When creating this spec from a user prompt:
1. **Make informed guesses**: Use context, industry standards, and common patterns to fill gaps
2. **Document assumptions**: Record reasonable defaults in the Assumptions section
3. **Limit clarifications**: Maximum 3 [NEEDS CLARIFICATION] markers - use only for critical decisions that:
- Significantly impact feature scope or user experience
- Have multiple reasonable interpretations with different implications
- Lack any reasonable default
4. **Prioritize clarifications**: scope > security/privacy > user experience > technical details
5. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item
6. **Common areas needing clarification** (only if no reasonable default exists):
- Feature scope and boundaries (include/exclude specific use cases)
- User types and permissions (if multiple conflicting interpretations possible)
- Security/compliance requirements (when legally/financially significant)
**Examples of reasonable defaults** (don't ask about these):
- Data retention: Industry-standard practices for the domain
- Performance targets: Standard web/mobile app expectations unless specified
- Error handling: User-friendly messages with appropriate fallbacks
- Authentication method: Standard session-based or OAuth2 for web apps
- Integration patterns: RESTful APIs unless specified otherwise
### Success Criteria Guidelines
Success criteria must be:
1. **Measurable**: Include specific metrics (time, percentage, count, rate)
2. **Technology-agnostic**: No mention of frameworks, languages, databases, or tools
3. **User-focused**: Describe outcomes from user/business perspective, not system internals
4. **Verifiable**: Can be tested/validated without knowing implementation details
**Good examples**:
- "Users can complete checkout in under 3 minutes"
- "System supports 10,000 concurrent users"
- "95% of searches return results in under 1 second"
- "Task completion rate improves by 40%"
**Bad examples** (implementation-focused):
- "API response time is under 200ms" (too technical, use "Users see results instantly")
- "Database can handle 1000 TPS" (implementation detail, use user-facing metric)
- "React components render efficiently" (framework-specific)
- "Redis cache hit rate above 80%" (technology-specific)

View File

@@ -0,0 +1,111 @@
---
description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts.
---
## User Input
```text
$ARGUMENTS
```
You **MUST** consider the user input before proceeding (if not empty).
## Outline
1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Load design documents**: Read from FEATURE_DIR:
- **Required**: plan.md (tech stack, libraries, structure), spec.md (user stories with priorities)
- **Optional**: data-model.md (entities), contracts/ (API endpoints), research.md (decisions), quickstart.md (test scenarios)
- Note: Not all projects have all documents. Generate tasks based on what's available.
3. **Execute task generation workflow** (follow the template structure):
- Load plan.md and extract tech stack, libraries, project structure
- **Load spec.md and extract user stories with their priorities (P1, P2, P3, etc.)**
- If data-model.md exists: Extract entities → map to user stories
- If contracts/ exists: Each file → map endpoints to user stories
- If research.md exists: Extract decisions → generate setup tasks
- **Generate tasks ORGANIZED BY USER STORY**:
- Setup tasks (shared infrastructure needed by all stories)
- **Foundational tasks (prerequisites that must complete before ANY user story can start)**
- For each user story (in priority order P1, P2, P3...):
- Group all tasks needed to complete JUST that story
- Include models, services, endpoints, UI components specific to that story
- Mark which tasks are [P] parallelizable
- If tests requested: Include tests specific to that story
- Polish/Integration tasks (cross-cutting concerns)
- **Tests are OPTIONAL**: Only generate test tasks if explicitly requested in the feature spec or user asks for TDD approach
- Apply task rules:
- Different files = mark [P] for parallel
- Same file = sequential (no [P])
- If tests requested: Tests before implementation (TDD order)
- Number tasks sequentially (T001, T002...)
- Generate dependency graph showing user story completion order
- Create parallel execution examples per user story
- Validate task completeness (each user story has all needed tasks, independently testable)
4. **Generate tasks.md**: Use `.specify.specify/templates/tasks-template.md` as structure, fill with:
- Correct feature name from plan.md
- Phase 1: Setup tasks (project initialization)
- Phase 2: Foundational tasks (blocking prerequisites for all user stories)
- Phase 3+: One phase per user story (in priority order from spec.md)
- Each phase includes: story goal, independent test criteria, tests (if requested), implementation tasks
- Clear [Story] labels (US1, US2, US3...) for each task
- [P] markers for parallelizable tasks within each story
- Checkpoint markers after each story phase
- Final Phase: Polish & cross-cutting concerns
- Numbered tasks (T001, T002...) in execution order
- Clear file paths for each task
- Dependencies section showing story completion order
- Parallel execution examples per story
- Implementation strategy section (MVP first, incremental delivery)
5. **Report**: Output path to generated tasks.md and summary:
- Total task count
- Task count per user story
- Parallel opportunities identified
- Independent test criteria for each story
- Suggested MVP scope (typically just User Story 1)
Context for task generation: $ARGUMENTS
The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without additional context.
## Task Generation Rules
**IMPORTANT**: Tests are optional. Only generate test tasks if the user explicitly requested testing or TDD approach in the feature specification.
**CRITICAL**: Tasks MUST be organized by user story to enable independent implementation and testing.
1. **From User Stories (spec.md)** - PRIMARY ORGANIZATION:
- Each user story (P1, P2, P3...) gets its own phase
- Map all related components to their story:
- Models needed for that story
- Services needed for that story
- Endpoints/UI needed for that story
- If tests requested: Tests specific to that story
- Mark story dependencies (most stories should be independent)
2. **From Contracts**:
- Map each contract/endpoint → to the user story it serves
- If tests requested: Each contract → contract test task [P] before implementation in that story's phase
3. **From Data Model**:
- Map each entity → to the user story(ies) that need it
- If entity serves multiple stories: Put in earliest story or Setup phase
- Relationships → service layer tasks in appropriate story phase
4. **From Setup/Infrastructure**:
- Shared infrastructure → Setup phase (Phase 1)
- Foundational/blocking tasks → Foundational phase (Phase 2)
- Examples: Database schema setup, authentication framework, core libraries, base configurations
- These MUST complete before any user story can be implemented
- Story-specific setup → within that story's phase
5. **Ordering**:
- Phase 1: Setup (project initialization)
- Phase 2: Foundational (blocking prerequisites - must complete before user stories)
- Phase 3+: User Stories in priority order (P1, P2, P3...)
- Within each story: Tests (if requested) → Models → Services → Endpoints → Integration
- Final Phase: Polish & Cross-Cutting Concerns
- Each user story phase should be a complete, independently testable increment

View File

@@ -1,50 +1,198 @@
# [PROJECT_NAME] Constitution
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
<!--
Version change: None → 1.0.0
List of modified principles:
- Python Modernization (New)
- Virtual Environment Isolation (New)
- Test-Driven Development (New)
- Containerization Standards (New)
Added sections:
- Project Structure Standards
- Service-Specific Standards
- Development Workflow & Quality Gates
- Dependency Management
- API Standards
- Code Quality Standards
- Git Standards
- Deployment Standards
- Monitoring and Observability
Removed sections:
- None (placeholders replaced or removed as per YAML content)
Templates requiring updates:
- .specify/templates/plan-template.md ⚠ pending
- .specify/templates/spec-template.md ⚠ pending
- .specify/templates/tasks-template.md ⚠ pending
Follow-up TODOs:
- Ensure all `MUST` and `SHOULD` statements are clear and testable.
-->
# FitTrack_GarminSync Constitution
## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### I. Python Modernization
All projects MUST use Python 3.13 or newer.
Type hints MUST be used throughout all code.
Dataclasses SHOULD be preferred over traditional classes for data structures.
Pathlib MUST be used for all file path operations.
### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### II. Virtual Environment Isolation
All projects MUST use Python virtual environments.
Virtual environments MUST be named `.venv` in the project root.
Dependencies MUST be pinned in `requirements.txt`.
Development dependencies MUST be separate from production dependencies.
### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### III. Test-Driven Development
All new features MUST include tests before implementation.
Test coverage MUST be maintained at 80% minimum.
Pytest MUST be used as the primary testing framework.
Unit tests, integration tests, and API tests MUST be separated.
### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### IV. Containerization Standards
Docker Compose V3 syntax MUST be used exclusively.
The command `docker compose` MUST be used, not `docker-compose`.
Multi-stage builds MUST be used for production containers.
Health checks MUST be included in all service definitions.
### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
## Project Structure Standards
## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
Root requirements file MUST be present.
Virtual environment MUST be located at `.venv`.
[SECTION_2_CONTENT]
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
### Test Structure
Unit tests MUST be located in `tests/unit/`.
Integration tests MUST be located in `tests/integration/`.
API tests MUST be located in `tests/api/`.
Test fixtures MUST be located in `tests/fixtures/`.
## [SECTION_3_NAME]
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
### Source Structure
Main module MUST be located in `src/`.
API routes MUST be located in `src/api/`.
Models MUST be located in `src/models/`.
Services MUST be located in `src/services/`.
[SECTION_3_CONTENT]
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
## Service-Specific Standards
### centraldb_service
Database MUST be PostgreSQL 15+ or SQLite.
ORM MUST be SQLAlchemy 2.0+.
Migrations MUST use Alembic.
API framework MUST be FastAPI.
### garminsync_service
Asynchronous processing SHOULD be implemented where appropriate.
File handling MUST support FIT/TCX/GPX parsing.
OAuth flows MUST support Garmin Connect and Fitbit.
### reportgenerator_service
CPU intensive operations SHOULD be optimized.
Chart generation MUST use Matplotlib/Plotly.
Supported file formats MUST include PNG, PDF, HTML.
### llmcoach_service
LLM providers SHOULD include OpenAI, Anthropic, and Local options.
Prompt management MUST use structured templates.
Conversation storage MUST integrate with CentralDB.
### web_interface
Frontend framework MUST be React/Next.js.
### cli_interface
CLI framework MUST be Click or Typer.
Configuration MUST use YAML config files.
Output formats MUST include JSON, table, CSV.
## Development Workflow & Quality Gates
### Pre-commit Hooks
Pre-commit hooks MUST include:
- `black --check .`
- `flake8`
- `mypy .`
- `pytest`
### Testing
Unit tests MUST be run with `pytest tests/unit -v`.
Integration tests MUST be run with `pytest tests/integration -v`.
API tests MUST be run with `pytest tests/api -v`.
Test coverage MUST be reported with `pytest --cov=src --cov-report=html`.
### Container Commands
Development containers MUST be run with `docker compose -f docker-compose.dev.yml up`.
Production containers MUST be run with `docker compose -f docker-compose.prod.yml up -d`.
Testing containers MUST be run with `docker compose -f docker-compose.test.yml up --abort-on-container-exit`.
## Dependency Management
### Requirements Files
Dependency files MUST include:
- `requirements.txt` (Production dependencies)
- `requirements-dev.txt` (Development dependencies)
- `requirements-test.txt` (Testing dependencies)
Version pinning MUST specify exact versions in production.
Security scanning MUST include `safety check` and `bandit -r src/`.
## API Standards
API framework MUST be FastAPI.
API documentation MUST be auto-generated OpenAPI/Swagger.
API versioning MUST use URL path versioning (e.g., `/api/v1/`).
Error handling MUST provide structured error responses.
Rate limiting SHOULD be Redis-based.
## Code Quality Standards
### Formatting
Code formatting tool MUST be Black.
Maximum line length MUST be 88 characters.
Black configuration file MUST be `pyproject.toml`.
### Linting
Linting tool MUST be Flake8.
Maximum complexity SHOULD be 10.
### Type Checking
Type checking tool MUST be Mypy.
Mypy MUST be run in strict mode.
### Import Sorting
Import sorting tool MUST be Isort.
## Git Standards
### Branch Naming
Feature branches MUST follow the pattern `feature/description`.
Bugfix branches MUST follow the pattern `fix/description`.
Hotfix branches MUST follow the pattern `hotfix/description`.
Release branches MUST follow the pattern `release/version`.
### Commit Messages
Commit messages MUST follow conventional commits format.
Allowed commit types include: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`.
Protected branches MUST include `main` and `develop`.
## Deployment Standards
### Environments
Development environment MUST use `docker compose` on the local machine.
Production environment MUST use HashiCorp Nomad.
### Health Checks
Liveness probes MUST be at `/health/live`.
Readiness probes MUST be at `/health/ready`.
Startup probes MUST be at `/health/start`.
## Monitoring and Observability
### Logging
Logging format MUST be JSON structured logs.
Logging level MUST be INFO (DEBUG in development).
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
This Constitution supersedes all other practices.
Amendments require documentation, approval, and a migration plan.
All Pull Requests and code reviews MUST verify compliance with these principles.
Any deviation from these principles or introduction of complexity MUST be justified with a clear rationale.
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
**Version**: 1.0.0 | **Ratified**: 2024-01-15 | **Last Amended**: 2025-10-09

14
backend/Dockerfile Normal file
View File

@@ -0,0 +1,14 @@
FROM python:3.13-slim-bookworm
WORKDIR /app
ENV PYTHONUNBUFFERED 1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8001
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8001"]

37
backend/Makefile Normal file
View File

@@ -0,0 +1,37 @@
PYTHON = python3
PIP = $(PYTHON) -m pip
VENV_DIR = .venv
API_PORT = 8001
SHELL = /bin/bash
.PHONY: all install lint format test run
all: install lint test
install:
@echo "Installing dependencies..."
$(PYTHON) -m venv $(VENV_DIR)
source $(VENV_DIR)/bin/activate && $(PIP) install -e .
lint:
@echo "Running linter (ruff check)..."
source $(VENV_DIR)/bin/activate && ruff check src/
format:
@echo "Running formatter (ruff format)..."
source $(VENV_DIR)/bin/activate && ruff format src/
test:
@echo "Running tests (pytest)..."
source $(VENV_DIR)/bin/activate && export PYTHONPATH=$(CURDIR):$(CURDIR)/src && pytest
run:
@echo "Starting FastAPI application..."
source $(VENV_DIR)/bin/activate && uvicorn src.main:app --host 0.0.0.0 --port ${API_PORT} --reload
clean:
@echo "Cleaning up..."
rm -rf $(VENV_DIR)
find . -type f -name "*.pyc" -delete
find . -type d -name "__pycache__" -delete
rm -rf .pytest_cache .ruff_cache

10
backend/entrypoint.sh Executable file
View File

@@ -0,0 +1,10 @@
#!/bin/bash
# Exit immediately if a command exits with a non-zero status.
set -e
# Run database migrations (if any)
# alembic upgrade head
# Start the FastAPI application
exec uvicorn src.main:app --host 0.0.0.0 --port ${API_PORT:-8001}

41
backend/pyproject.toml Normal file
View File

@@ -0,0 +1,41 @@
[project]
name = "garmin_sync_backend"
version = "0.1.0"
description = "Backend service for GarminSync"
dependencies = [
"fastapi",
"uvicorn",
"garth",
"garminconnect",
"passlib[bcrypt]",
"python-jose[jwt]",
"pydantic-settings",
"limits",
"httpx",
"tenacity",
]
requires-python = ">=3.10"
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
line-length = 120
target-version = "py310"
[tool.ruff.lint]
select = ["E", "F", "W", "I"] # Error, Flake8, Warnings, Isort
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
line-ending = "auto"
[tool.pytest.ini_options]
pythonpath = ["src"]
asyncio_mode = "auto"

108
backend/requirements.txt Normal file
View File

@@ -0,0 +1,108 @@
#
# This file is autogenerated by pip-compile with Python 3.13
# by the following command:
#
# pip-compile --output-file=requirements.txt pyproject.toml
#
annotated-types==0.7.0
# via pydantic
anyio==4.11.0
# via
# httpx
# starlette
bcrypt==5.0.0
# via passlib
certifi==2025.10.5
# via
# httpcore
# httpx
# requests
charset-normalizer==3.4.3
# via requests
click==8.3.0
# via uvicorn
deprecated==1.2.18
# via limits
ecdsa==0.19.1
# via python-jose
fastapi==0.118.2
# via garmin_sync_backend (pyproject.toml)
garminconnect==0.2.30
# via garmin_sync_backend (pyproject.toml)
garth==0.5.17
# via
# garmin_sync_backend (pyproject.toml)
# garminconnect
h11==0.16.0
# via
# httpcore
# uvicorn
httpcore==1.0.9
# via httpx
httpx==0.28.1
# via garmin_sync_backend (pyproject.toml)
idna==3.10
# via
# anyio
# httpx
# requests
itsdangerous==2.2.0
limits==5.6.0
# via garmin_sync_backend (pyproject.toml)
oauthlib==3.3.1
# via requests-oauthlib
packaging==25.0
# via limits
passlib[bcrypt]==1.7.4
# via garmin_sync_backend (pyproject.toml)
pyasn1==0.6.1
# via
# python-jose
# rsa
pydantic==2.12.0
# via
# fastapi
# garth
# pydantic-settings
pydantic-core==2.41.1
# via pydantic
pydantic-settings==2.11.0
# via garmin_sync_backend (pyproject.toml)
python-dotenv==1.1.1
# via pydantic-settings
python-jose[jwt]==3.5.0
# via garmin_sync_backend (pyproject.toml)
python-multipart==0.0.9
requests==2.32.5
# via
# garth
# requests-oauthlib
requests-oauthlib==2.0.0
# via garth
rsa==4.9.1
# via python-jose
six==1.17.0
# via ecdsa
sniffio==1.3.1
# via anyio
starlette==0.48.0
# via fastapi
tenacity==9.1.2
# via garmin_sync_backend (pyproject.toml)
typing-extensions==4.15.0
# via
# fastapi
# limits
# pydantic
# pydantic-core
# typing-inspection
typing-inspection==0.4.2
# via
# pydantic
# pydantic-settings
urllib3==2.5.0
# via requests
uvicorn==0.37.0
# via garmin_sync_backend (pyproject.toml)
wrapt==1.17.3
# via deprecated

BIN
backend/sql_app.db Normal file

Binary file not shown.

0
backend/src/__init__.py Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,81 @@
from typing import Optional, List
from uuid import UUID, uuid4
from datetime import date, datetime
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from ..dependencies import (
get_garmin_activity_service,
get_garmin_workout_service,
get_sync_status_service,
get_current_user,
)
from ..services.garmin_activity_service import GarminActivityService
from ..services.garmin_health_service import GarminHealthService
from ..services.garmin_workout_service import GarminWorkoutService
from ..services.sync_status_service import SyncStatusService
from ..jobs import job_store, SyncJob
from ..schemas import ActivitySyncRequest, WorkoutUploadRequest, User
router = APIRouter()
@router.post("/garmin/activities", response_model=SyncJob, status_code=202)
async def trigger_garmin_activity_sync(
request: ActivitySyncRequest,
background_tasks: BackgroundTasks,
garmin_activity_service: GarminActivityService = Depends(get_garmin_activity_service),
current_user: User = Depends(get_current_user),
):
"""
Trigger Garmin Connect Activity Synchronization
"""
job = job_store.create_job()
background_tasks.add_task(
garmin_activity_service.sync_activities_in_background,
job.id,
request.force_resync,
request.start_date,
request.end_date
)
return job
@router.post("/garmin/workouts", response_model=SyncJob, status_code=202)
async def upload_garmin_workout(
request: WorkoutUploadRequest,
background_tasks: BackgroundTasks,
garmin_workout_service: GarminWorkoutService = Depends(get_garmin_workout_service),
current_user: User = Depends(get_current_user),
):
"""
Upload a workout to Garmin Connect
"""
job = job_store.create_job()
background_tasks.add_task(
garmin_workout_service.upload_workout_in_background,
job.id,
request.workout_id,
)
return job
@router.get("/status", response_model=List[SyncJob], status_code=200)
async def get_sync_status(
job_id: Optional[UUID] = None,
limit: int = 10,
offset: int = 0,
sync_status_service: SyncStatusService = Depends(get_sync_status_service),
current_user: User = Depends(get_current_user),
):
"""
Retrieve the status of synchronization jobs.
"""
sync_jobs = sync_status_service.get_sync_jobs(
job_id=job_id,
limit=limit,
offset=offset
)
return sync_jobs

View File

@@ -0,0 +1,23 @@
__pycache__/
build/
dist/
*.egg-info/
.pytest_cache/
# pyenv
.python-version
# Environments
.env
.venv
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# JetBrains
.idea/
/coverage.xml
/.coverage

View File

@@ -0,0 +1,124 @@
# fit-track-central-db-api-client
A client library for accessing FitTrack CentralDB API
## Usage
First, create a client:
```python
from fit_track_central_db_api_client import Client
client = Client(base_url="https://api.example.com")
```
If the endpoints you're going to hit require authentication, use `AuthenticatedClient` instead:
```python
from fit_track_central_db_api_client import AuthenticatedClient
client = AuthenticatedClient(base_url="https://api.example.com", token="SuperSecretToken")
```
Now call your endpoint and use your models:
```python
from fit_track_central_db_api_client.models import MyDataModel
from fit_track_central_db_api_client.api.my_tag import get_my_data_model
from fit_track_central_db_api_client.types import Response
with client as client:
my_data: MyDataModel = get_my_data_model.sync(client=client)
# or if you need more info (e.g. status_code)
response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)
```
Or do the same thing with an async version:
```python
from fit_track_central_db_api_client.models import MyDataModel
from fit_track_central_db_api_client.api.my_tag import get_my_data_model
from fit_track_central_db_api_client.types import Response
async with client as client:
my_data: MyDataModel = await get_my_data_model.asyncio(client=client)
response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client)
```
By default, when you're calling an HTTPS API it will attempt to verify that SSL is working correctly. Using certificate verification is highly recommended most of the time, but sometimes you may need to authenticate to a server (especially an internal server) using a custom certificate bundle.
```python
client = AuthenticatedClient(
base_url="https://internal_api.example.com",
token="SuperSecretToken",
verify_ssl="/path/to/certificate_bundle.pem",
)
```
You can also disable certificate validation altogether, but beware that **this is a security risk**.
```python
client = AuthenticatedClient(
base_url="https://internal_api.example.com",
token="SuperSecretToken",
verify_ssl=False
)
```
Things to know:
1. Every path/method combo becomes a Python module with four functions:
1. `sync`: Blocking request that returns parsed data (if successful) or `None`
1. `sync_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful.
1. `asyncio`: Like `sync` but async instead of blocking
1. `asyncio_detailed`: Like `sync_detailed` but async instead of blocking
1. All path/query params, and bodies become method arguments.
1. If your endpoint had any tags on it, the first tag will be used as a module name for the function (my_tag above)
1. Any endpoint which did not have a tag will be in `fit_track_central_db_api_client.api.default`
## Advanced customizations
There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx.Client` or `httpx.AsyncClient` (depending on your use-case):
```python
from fit_track_central_db_api_client import Client
def log_request(request):
print(f"Request event hook: {request.method} {request.url} - Waiting for response")
def log_response(response):
request = response.request
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")
client = Client(
base_url="https://api.example.com",
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
)
# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()
```
You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url):
```python
import httpx
from fit_track_central_db_api_client import Client
client = Client(
base_url="https://api.example.com",
)
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030"))
```
## Building / publishing this package
This project uses [Poetry](https://python-poetry.org/) to manage dependencies and packaging. Here are the basics:
1. Update the metadata in pyproject.toml (e.g. authors, version)
1. If you're using a private repository, configure it with Poetry
1. `poetry config repositories.<your-repository-name> <url-to-your-repository>`
1. `poetry config http-basic.<your-repository-name> <username> <password>`
1. Publish the client with `poetry publish --build -r <your-repository-name>` or, if for public PyPI, just `poetry publish --build`
If you want to install this client into another project without publishing it (e.g. for development) then:
1. If that project **is using Poetry**, you can simply do `poetry add <path-to-this-client>` from that project
1. If that project is not using Poetry:
1. Build a wheel with `poetry build -f wheel`
1. Install that wheel from the other project `pip install <path-to-wheel>`

View File

@@ -0,0 +1,8 @@
"""A client library for accessing FitTrack CentralDB API"""
from .client import AuthenticatedClient, Client
__all__ = (
"AuthenticatedClient",
"Client",
)

View File

@@ -0,0 +1 @@
"""Contains methods for accessing the API"""

View File

@@ -0,0 +1 @@
"""Contains endpoint functions for accessing the API"""

View File

@@ -0,0 +1,179 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.analysis_artifact import AnalysisArtifact
from ...models.analysis_artifact_create import AnalysisArtifactCreate
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
activity_id: int,
*,
body: AnalysisArtifactCreate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": f"/activities/{activity_id}/analysis",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[AnalysisArtifact, HTTPValidationError]]:
if response.status_code == 201:
response_201 = AnalysisArtifact.from_dict(response.json())
return response_201
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[AnalysisArtifact, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: AnalysisArtifactCreate,
) -> Response[Union[AnalysisArtifact, HTTPValidationError]]:
"""Create Analysis Artifact
Args:
activity_id (int):
body (AnalysisArtifactCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[AnalysisArtifact, HTTPValidationError]]
"""
kwargs = _get_kwargs(
activity_id=activity_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: AnalysisArtifactCreate,
) -> Optional[Union[AnalysisArtifact, HTTPValidationError]]:
"""Create Analysis Artifact
Args:
activity_id (int):
body (AnalysisArtifactCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[AnalysisArtifact, HTTPValidationError]
"""
return sync_detailed(
activity_id=activity_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: AnalysisArtifactCreate,
) -> Response[Union[AnalysisArtifact, HTTPValidationError]]:
"""Create Analysis Artifact
Args:
activity_id (int):
body (AnalysisArtifactCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[AnalysisArtifact, HTTPValidationError]]
"""
kwargs = _get_kwargs(
activity_id=activity_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: AnalysisArtifactCreate,
) -> Optional[Union[AnalysisArtifact, HTTPValidationError]]:
"""Create Analysis Artifact
Args:
activity_id (int):
body (AnalysisArtifactCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[AnalysisArtifact, HTTPValidationError]
"""
return (
await asyncio_detailed(
activity_id=activity_id,
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,166 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.coaching_session import CoachingSession
from ...models.coaching_session_create import CoachingSessionCreate
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
*,
body: CoachingSessionCreate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": "/coaching/sessions",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[CoachingSession, HTTPValidationError]]:
if response.status_code == 201:
response_201 = CoachingSession.from_dict(response.json())
return response_201
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[CoachingSession, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: CoachingSessionCreate,
) -> Response[Union[CoachingSession, HTTPValidationError]]:
"""Create Coaching Session
Args:
body (CoachingSessionCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[CoachingSession, HTTPValidationError]]
"""
kwargs = _get_kwargs(
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
body: CoachingSessionCreate,
) -> Optional[Union[CoachingSession, HTTPValidationError]]:
"""Create Coaching Session
Args:
body (CoachingSessionCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[CoachingSession, HTTPValidationError]
"""
return sync_detailed(
client=client,
body=body,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: CoachingSessionCreate,
) -> Response[Union[CoachingSession, HTTPValidationError]]:
"""Create Coaching Session
Args:
body (CoachingSessionCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[CoachingSession, HTTPValidationError]]
"""
kwargs = _get_kwargs(
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
body: CoachingSessionCreate,
) -> Optional[Union[CoachingSession, HTTPValidationError]]:
"""Create Coaching Session
Args:
body (CoachingSessionCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[CoachingSession, HTTPValidationError]
"""
return (
await asyncio_detailed(
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,166 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.health_metric import HealthMetric
from ...models.health_metric_create import HealthMetricCreate
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
*,
body: HealthMetricCreate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": "/health_metrics",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
if response.status_code == 201:
response_201 = HealthMetric.from_dict(response.json())
return response_201
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, HealthMetric]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: HealthMetricCreate,
) -> Response[Union[HTTPValidationError, HealthMetric]]:
"""Create Health Metric
Args:
body (HealthMetricCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, HealthMetric]]
"""
kwargs = _get_kwargs(
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
body: HealthMetricCreate,
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
"""Create Health Metric
Args:
body (HealthMetricCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, HealthMetric]
"""
return sync_detailed(
client=client,
body=body,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: HealthMetricCreate,
) -> Response[Union[HTTPValidationError, HealthMetric]]:
"""Create Health Metric
Args:
body (HealthMetricCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, HealthMetric]]
"""
kwargs = _get_kwargs(
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
body: HealthMetricCreate,
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
"""Create Health Metric
Args:
body (HealthMetricCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, HealthMetric]
"""
return (
await asyncio_detailed(
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,166 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.user import User
from ...models.user_create import UserCreate
from ...types import Response
def _get_kwargs(
*,
body: UserCreate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": "/users",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, User]]:
if response.status_code == 201:
response_201 = User.from_dict(response.json())
return response_201
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, User]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: UserCreate,
) -> Response[Union[HTTPValidationError, User]]:
"""Create User
Args:
body (UserCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, User]]
"""
kwargs = _get_kwargs(
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
body: UserCreate,
) -> Optional[Union[HTTPValidationError, User]]:
"""Create User
Args:
body (UserCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, User]
"""
return sync_detailed(
client=client,
body=body,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: UserCreate,
) -> Response[Union[HTTPValidationError, User]]:
"""Create User
Args:
body (UserCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, User]]
"""
kwargs = _get_kwargs(
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
body: UserCreate,
) -> Optional[Union[HTTPValidationError, User]]:
"""Create User
Args:
body (UserCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, User]
"""
return (
await asyncio_detailed(
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,166 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.workout_plan import WorkoutPlan
from ...models.workout_plan_create import WorkoutPlanCreate
from ...types import Response
def _get_kwargs(
*,
body: WorkoutPlanCreate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": "/workout_plans",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
if response.status_code == 201:
response_201 = WorkoutPlan.from_dict(response.json())
return response_201
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: WorkoutPlanCreate,
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
"""Create Workout Plan
Args:
body (WorkoutPlanCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, WorkoutPlan]]
"""
kwargs = _get_kwargs(
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
body: WorkoutPlanCreate,
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
"""Create Workout Plan
Args:
body (WorkoutPlanCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, WorkoutPlan]
"""
return sync_detailed(
client=client,
body=body,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: WorkoutPlanCreate,
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
"""Create Workout Plan
Args:
body (WorkoutPlanCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, WorkoutPlan]]
"""
kwargs = _get_kwargs(
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
body: WorkoutPlanCreate,
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
"""Create Workout Plan
Args:
body (WorkoutPlanCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, WorkoutPlan]
"""
return (
await asyncio_detailed(
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,155 @@
from http import HTTPStatus
from typing import Any, Optional, Union, cast
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
metric_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "delete",
"url": f"/health_metrics/{metric_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Any, HTTPValidationError]]:
if response.status_code == 204:
response_204 = cast(Any, None)
return response_204
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Any, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Delete Health Metric
Args:
metric_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
metric_id=metric_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Delete Health Metric
Args:
metric_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return sync_detailed(
metric_id=metric_id,
client=client,
).parsed
async def asyncio_detailed(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Delete Health Metric
Args:
metric_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
metric_id=metric_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Delete Health Metric
Args:
metric_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return (
await asyncio_detailed(
metric_id=metric_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,155 @@
from http import HTTPStatus
from typing import Any, Optional, Union, cast
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
user_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "delete",
"url": f"/users/{user_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Any, HTTPValidationError]]:
if response.status_code == 204:
response_204 = cast(Any, None)
return response_204
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Any, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Delete User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Delete User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return sync_detailed(
user_id=user_id,
client=client,
).parsed
async def asyncio_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Delete User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Delete User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return (
await asyncio_detailed(
user_id=user_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,155 @@
from http import HTTPStatus
from typing import Any, Optional, Union, cast
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
plan_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "delete",
"url": f"/workout_plans/{plan_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Any, HTTPValidationError]]:
if response.status_code == 204:
response_204 = cast(Any, None)
return response_204
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Any, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Delete Workout Plan
Args:
plan_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
plan_id=plan_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Delete Workout Plan
Args:
plan_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return sync_detailed(
plan_id=plan_id,
client=client,
).parsed
async def asyncio_detailed(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Delete Workout Plan
Args:
plan_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
plan_id=plan_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Delete Workout Plan
Args:
plan_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return (
await asyncio_detailed(
plan_id=plan_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,155 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
activity_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/activities/{activity_id}/file",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Any, HTTPValidationError]]:
if response.status_code == 200:
response_200 = response.json()
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Any, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Download Activity File
Args:
activity_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
activity_id=activity_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Download Activity File
Args:
activity_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return sync_detailed(
activity_id=activity_id,
client=client,
).parsed
async def asyncio_detailed(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Download Activity File
Args:
activity_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
activity_id=activity_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Download Activity File
Args:
activity_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return (
await asyncio_detailed(
activity_id=activity_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,157 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.activity import Activity
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
activity_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/activities/{activity_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Activity, HTTPValidationError]]:
if response.status_code == 200:
response_200 = Activity.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Activity, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Activity, HTTPValidationError]]:
"""Get Activity By Id
Args:
activity_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Activity, HTTPValidationError]]
"""
kwargs = _get_kwargs(
activity_id=activity_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Activity, HTTPValidationError]]:
"""Get Activity By Id
Args:
activity_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Activity, HTTPValidationError]
"""
return sync_detailed(
activity_id=activity_id,
client=client,
).parsed
async def asyncio_detailed(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Activity, HTTPValidationError]]:
"""Get Activity By Id
Args:
activity_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Activity, HTTPValidationError]]
"""
kwargs = _get_kwargs(
activity_id=activity_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
activity_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Activity, HTTPValidationError]]:
"""Get Activity By Id
Args:
activity_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Activity, HTTPValidationError]
"""
return (
await asyncio_detailed(
activity_id=activity_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,132 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.activity import Activity
from ...types import Response
def _get_kwargs() -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": "/activities",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[list["Activity"]]:
if response.status_code == 200:
response_200 = []
_response_200 = response.json()
for response_200_item_data in _response_200:
response_200_item = Activity.from_dict(response_200_item_data)
response_200.append(response_200_item)
return response_200
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[list["Activity"]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
) -> Response[list["Activity"]]:
"""Get All Activities
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[list['Activity']]
"""
kwargs = _get_kwargs()
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[list["Activity"]]:
"""Get All Activities
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
list['Activity']
"""
return sync_detailed(
client=client,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
) -> Response[list["Activity"]]:
"""Get All Activities
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[list['Activity']]
"""
kwargs = _get_kwargs()
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[list["Activity"]]:
"""Get All Activities
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
list['Activity']
"""
return (
await asyncio_detailed(
client=client,
)
).parsed

View File

@@ -0,0 +1,132 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.coaching_session import CoachingSession
from ...types import Response
def _get_kwargs() -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": "/coaching/sessions",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[list["CoachingSession"]]:
if response.status_code == 200:
response_200 = []
_response_200 = response.json()
for response_200_item_data in _response_200:
response_200_item = CoachingSession.from_dict(response_200_item_data)
response_200.append(response_200_item)
return response_200
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[list["CoachingSession"]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
) -> Response[list["CoachingSession"]]:
"""Get All Coaching Sessions
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[list['CoachingSession']]
"""
kwargs = _get_kwargs()
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[list["CoachingSession"]]:
"""Get All Coaching Sessions
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
list['CoachingSession']
"""
return sync_detailed(
client=client,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
) -> Response[list["CoachingSession"]]:
"""Get All Coaching Sessions
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[list['CoachingSession']]
"""
kwargs = _get_kwargs()
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[list["CoachingSession"]]:
"""Get All Coaching Sessions
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
list['CoachingSession']
"""
return (
await asyncio_detailed(
client=client,
)
).parsed

View File

@@ -0,0 +1,157 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.health_metric import HealthMetric
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
metric_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/health_metrics/{metric_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
if response.status_code == 200:
response_200 = HealthMetric.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, HealthMetric]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, HealthMetric]]:
"""Read Health Metric
Args:
metric_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, HealthMetric]]
"""
kwargs = _get_kwargs(
metric_id=metric_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
"""Read Health Metric
Args:
metric_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, HealthMetric]
"""
return sync_detailed(
metric_id=metric_id,
client=client,
).parsed
async def asyncio_detailed(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, HealthMetric]]:
"""Read Health Metric
Args:
metric_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, HealthMetric]]
"""
kwargs = _get_kwargs(
metric_id=metric_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
"""Read Health Metric
Args:
metric_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, HealthMetric]
"""
return (
await asyncio_detailed(
metric_id=metric_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,162 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.health_metric import HealthMetric
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
user_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/users/{user_id}/health_metrics",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, list["HealthMetric"]]]:
if response.status_code == 200:
response_200 = []
_response_200 = response.json()
for response_200_item_data in _response_200:
response_200_item = HealthMetric.from_dict(response_200_item_data)
response_200.append(response_200_item)
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, list["HealthMetric"]]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, list["HealthMetric"]]]:
"""Read Health Metrics By User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, list['HealthMetric']]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, list["HealthMetric"]]]:
"""Read Health Metrics By User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, list['HealthMetric']]
"""
return sync_detailed(
user_id=user_id,
client=client,
).parsed
async def asyncio_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, list["HealthMetric"]]]:
"""Read Health Metrics By User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, list['HealthMetric']]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, list["HealthMetric"]]]:
"""Read Health Metrics By User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, list['HealthMetric']]
"""
return (
await asyncio_detailed(
user_id=user_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,157 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.user import User
from ...types import Response
def _get_kwargs(
user_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/users/{user_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, User]]:
if response.status_code == 200:
response_200 = User.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, User]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, User]]:
"""Read User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, User]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, User]]:
"""Read User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, User]
"""
return sync_detailed(
user_id=user_id,
client=client,
).parsed
async def asyncio_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, User]]:
"""Read User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, User]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, User]]:
"""Read User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, User]
"""
return (
await asyncio_detailed(
user_id=user_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,185 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.user import User
from ...types import UNSET, Response, Unset
def _get_kwargs(
*,
skip: Union[Unset, int] = 0,
limit: Union[Unset, int] = 100,
) -> dict[str, Any]:
params: dict[str, Any] = {}
params["skip"] = skip
params["limit"] = limit
params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
_kwargs: dict[str, Any] = {
"method": "get",
"url": "/users",
"params": params,
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, list["User"]]]:
if response.status_code == 200:
response_200 = []
_response_200 = response.json()
for response_200_item_data in _response_200:
response_200_item = User.from_dict(response_200_item_data)
response_200.append(response_200_item)
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, list["User"]]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
skip: Union[Unset, int] = 0,
limit: Union[Unset, int] = 100,
) -> Response[Union[HTTPValidationError, list["User"]]]:
"""Read Users
Args:
skip (Union[Unset, int]): Default: 0.
limit (Union[Unset, int]): Default: 100.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, list['User']]]
"""
kwargs = _get_kwargs(
skip=skip,
limit=limit,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
skip: Union[Unset, int] = 0,
limit: Union[Unset, int] = 100,
) -> Optional[Union[HTTPValidationError, list["User"]]]:
"""Read Users
Args:
skip (Union[Unset, int]): Default: 0.
limit (Union[Unset, int]): Default: 100.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, list['User']]
"""
return sync_detailed(
client=client,
skip=skip,
limit=limit,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
skip: Union[Unset, int] = 0,
limit: Union[Unset, int] = 100,
) -> Response[Union[HTTPValidationError, list["User"]]]:
"""Read Users
Args:
skip (Union[Unset, int]): Default: 0.
limit (Union[Unset, int]): Default: 100.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, list['User']]]
"""
kwargs = _get_kwargs(
skip=skip,
limit=limit,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
skip: Union[Unset, int] = 0,
limit: Union[Unset, int] = 100,
) -> Optional[Union[HTTPValidationError, list["User"]]]:
"""Read Users
Args:
skip (Union[Unset, int]): Default: 0.
limit (Union[Unset, int]): Default: 100.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, list['User']]
"""
return (
await asyncio_detailed(
client=client,
skip=skip,
limit=limit,
)
).parsed

View File

@@ -0,0 +1,157 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.workout_plan import WorkoutPlan
from ...types import Response
def _get_kwargs(
plan_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/workout_plans/{plan_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
if response.status_code == 200:
response_200 = WorkoutPlan.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
"""Read Workout Plan
Args:
plan_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, WorkoutPlan]]
"""
kwargs = _get_kwargs(
plan_id=plan_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
"""Read Workout Plan
Args:
plan_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, WorkoutPlan]
"""
return sync_detailed(
plan_id=plan_id,
client=client,
).parsed
async def asyncio_detailed(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
"""Read Workout Plan
Args:
plan_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, WorkoutPlan]]
"""
kwargs = _get_kwargs(
plan_id=plan_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
"""Read Workout Plan
Args:
plan_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, WorkoutPlan]
"""
return (
await asyncio_detailed(
plan_id=plan_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,162 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.workout_plan import WorkoutPlan
from ...types import Response
def _get_kwargs(
user_id: int,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/users/{user_id}/workout_plans",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, list["WorkoutPlan"]]]:
if response.status_code == 200:
response_200 = []
_response_200 = response.json()
for response_200_item_data in _response_200:
response_200_item = WorkoutPlan.from_dict(response_200_item_data)
response_200.append(response_200_item)
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, list["WorkoutPlan"]]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, list["WorkoutPlan"]]]:
"""Read Workout Plans By User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, list['WorkoutPlan']]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, list["WorkoutPlan"]]]:
"""Read Workout Plans By User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, list['WorkoutPlan']]
"""
return sync_detailed(
user_id=user_id,
client=client,
).parsed
async def asyncio_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, list["WorkoutPlan"]]]:
"""Read Workout Plans By User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, list['WorkoutPlan']]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, list["WorkoutPlan"]]]:
"""Read Workout Plans By User
Args:
user_id (int):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, list['WorkoutPlan']]
"""
return (
await asyncio_detailed(
user_id=user_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,179 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.health_metric import HealthMetric
from ...models.health_metric_update import HealthMetricUpdate
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
metric_id: int,
*,
body: HealthMetricUpdate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "put",
"url": f"/health_metrics/{metric_id}",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
if response.status_code == 200:
response_200 = HealthMetric.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, HealthMetric]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: HealthMetricUpdate,
) -> Response[Union[HTTPValidationError, HealthMetric]]:
"""Update Health Metric
Args:
metric_id (int):
body (HealthMetricUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, HealthMetric]]
"""
kwargs = _get_kwargs(
metric_id=metric_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: HealthMetricUpdate,
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
"""Update Health Metric
Args:
metric_id (int):
body (HealthMetricUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, HealthMetric]
"""
return sync_detailed(
metric_id=metric_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: HealthMetricUpdate,
) -> Response[Union[HTTPValidationError, HealthMetric]]:
"""Update Health Metric
Args:
metric_id (int):
body (HealthMetricUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, HealthMetric]]
"""
kwargs = _get_kwargs(
metric_id=metric_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
metric_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: HealthMetricUpdate,
) -> Optional[Union[HTTPValidationError, HealthMetric]]:
"""Update Health Metric
Args:
metric_id (int):
body (HealthMetricUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, HealthMetric]
"""
return (
await asyncio_detailed(
metric_id=metric_id,
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,179 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.user import User
from ...models.user_update import UserUpdate
from ...types import Response
def _get_kwargs(
user_id: int,
*,
body: UserUpdate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "put",
"url": f"/users/{user_id}",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, User]]:
if response.status_code == 200:
response_200 = User.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, User]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: UserUpdate,
) -> Response[Union[HTTPValidationError, User]]:
"""Update User
Args:
user_id (int):
body (UserUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, User]]
"""
kwargs = _get_kwargs(
user_id=user_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: UserUpdate,
) -> Optional[Union[HTTPValidationError, User]]:
"""Update User
Args:
user_id (int):
body (UserUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, User]
"""
return sync_detailed(
user_id=user_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: UserUpdate,
) -> Response[Union[HTTPValidationError, User]]:
"""Update User
Args:
user_id (int):
body (UserUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, User]]
"""
kwargs = _get_kwargs(
user_id=user_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
user_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: UserUpdate,
) -> Optional[Union[HTTPValidationError, User]]:
"""Update User
Args:
user_id (int):
body (UserUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, User]
"""
return (
await asyncio_detailed(
user_id=user_id,
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,179 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.workout_plan import WorkoutPlan
from ...models.workout_plan_update import WorkoutPlanUpdate
from ...types import Response
def _get_kwargs(
plan_id: int,
*,
body: WorkoutPlanUpdate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "put",
"url": f"/workout_plans/{plan_id}",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
if response.status_code == 200:
response_200 = WorkoutPlan.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: WorkoutPlanUpdate,
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
"""Update Workout Plan
Args:
plan_id (int):
body (WorkoutPlanUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, WorkoutPlan]]
"""
kwargs = _get_kwargs(
plan_id=plan_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: WorkoutPlanUpdate,
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
"""Update Workout Plan
Args:
plan_id (int):
body (WorkoutPlanUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, WorkoutPlan]
"""
return sync_detailed(
plan_id=plan_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: WorkoutPlanUpdate,
) -> Response[Union[HTTPValidationError, WorkoutPlan]]:
"""Update Workout Plan
Args:
plan_id (int):
body (WorkoutPlanUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, WorkoutPlan]]
"""
kwargs = _get_kwargs(
plan_id=plan_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
plan_id: int,
*,
client: Union[AuthenticatedClient, Client],
body: WorkoutPlanUpdate,
) -> Optional[Union[HTTPValidationError, WorkoutPlan]]:
"""Update Workout Plan
Args:
plan_id (int):
body (WorkoutPlanUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, WorkoutPlan]
"""
return (
await asyncio_detailed(
plan_id=plan_id,
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,164 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.activity import Activity
from ...models.body_upload_activity_activities_post import BodyUploadActivityActivitiesPost
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
*,
body: BodyUploadActivityActivitiesPost,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": "/activities",
}
_kwargs["files"] = body.to_multipart()
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Activity, HTTPValidationError]]:
if response.status_code == 201:
response_201 = Activity.from_dict(response.json())
return response_201
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Activity, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: BodyUploadActivityActivitiesPost,
) -> Response[Union[Activity, HTTPValidationError]]:
"""Upload Activity
Args:
body (BodyUploadActivityActivitiesPost):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Activity, HTTPValidationError]]
"""
kwargs = _get_kwargs(
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
body: BodyUploadActivityActivitiesPost,
) -> Optional[Union[Activity, HTTPValidationError]]:
"""Upload Activity
Args:
body (BodyUploadActivityActivitiesPost):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Activity, HTTPValidationError]
"""
return sync_detailed(
client=client,
body=body,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: BodyUploadActivityActivitiesPost,
) -> Response[Union[Activity, HTTPValidationError]]:
"""Upload Activity
Args:
body (BodyUploadActivityActivitiesPost):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Activity, HTTPValidationError]]
"""
kwargs = _get_kwargs(
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
body: BodyUploadActivityActivitiesPost,
) -> Optional[Union[Activity, HTTPValidationError]]:
"""Upload Activity
Args:
body (BodyUploadActivityActivitiesPost):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Activity, HTTPValidationError]
"""
return (
await asyncio_detailed(
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1 @@
"""Contains endpoint functions for accessing the API"""

View File

@@ -0,0 +1,80 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...types import Response
def _get_kwargs() -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": "/",
}
return _kwargs
def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Any]:
if response.status_code == 200:
return None
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Any]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Any]:
"""Read Root
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any]
"""
kwargs = _get_kwargs()
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Any]:
"""Read Root
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Any]
"""
kwargs = _get_kwargs()
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)

View File

@@ -0,0 +1 @@
"""Contains endpoint functions for accessing the API"""

View File

@@ -0,0 +1,166 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.token import Token
from ...models.token_create import TokenCreate
from ...types import Response
def _get_kwargs(
*,
body: TokenCreate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "post",
"url": "/tokens/",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, Token]]:
if response.status_code == 201:
response_201 = Token.from_dict(response.json())
return response_201
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, Token]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: TokenCreate,
) -> Response[Union[HTTPValidationError, Token]]:
"""Create Token Api
Args:
body (TokenCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, Token]]
"""
kwargs = _get_kwargs(
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
*,
client: Union[AuthenticatedClient, Client],
body: TokenCreate,
) -> Optional[Union[HTTPValidationError, Token]]:
"""Create Token Api
Args:
body (TokenCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, Token]
"""
return sync_detailed(
client=client,
body=body,
).parsed
async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
body: TokenCreate,
) -> Response[Union[HTTPValidationError, Token]]:
"""Create Token Api
Args:
body (TokenCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, Token]]
"""
kwargs = _get_kwargs(
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
body: TokenCreate,
) -> Optional[Union[HTTPValidationError, Token]]:
"""Create Token Api
Args:
body (TokenCreate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, Token]
"""
return (
await asyncio_detailed(
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,155 @@
from http import HTTPStatus
from typing import Any, Optional, Union, cast
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...types import Response
def _get_kwargs(
user_id: str,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "delete",
"url": f"/tokens/{user_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Any, HTTPValidationError]]:
if response.status_code == 204:
response_204 = cast(Any, None)
return response_204
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[Any, HTTPValidationError]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Delete Token Api
Args:
user_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Delete Token Api
Args:
user_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return sync_detailed(
user_id=user_id,
client=client,
).parsed
async def asyncio_detailed(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[Any, HTTPValidationError]]:
"""Delete Token Api
Args:
user_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[Any, HTTPValidationError]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[Any, HTTPValidationError]]:
"""Delete Token Api
Args:
user_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[Any, HTTPValidationError]
"""
return (
await asyncio_detailed(
user_id=user_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,157 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.token import Token
from ...types import Response
def _get_kwargs(
user_id: str,
) -> dict[str, Any]:
_kwargs: dict[str, Any] = {
"method": "get",
"url": f"/tokens/{user_id}",
}
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, Token]]:
if response.status_code == 200:
response_200 = Token.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, Token]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, Token]]:
"""Get Token Api
Args:
user_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, Token]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, Token]]:
"""Get Token Api
Args:
user_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, Token]
"""
return sync_detailed(
user_id=user_id,
client=client,
).parsed
async def asyncio_detailed(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
) -> Response[Union[HTTPValidationError, Token]]:
"""Get Token Api
Args:
user_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, Token]]
"""
kwargs = _get_kwargs(
user_id=user_id,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
) -> Optional[Union[HTTPValidationError, Token]]:
"""Get Token Api
Args:
user_id (str):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, Token]
"""
return (
await asyncio_detailed(
user_id=user_id,
client=client,
)
).parsed

View File

@@ -0,0 +1,179 @@
from http import HTTPStatus
from typing import Any, Optional, Union
import httpx
from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.http_validation_error import HTTPValidationError
from ...models.token import Token
from ...models.token_update import TokenUpdate
from ...types import Response
def _get_kwargs(
user_id: str,
*,
body: TokenUpdate,
) -> dict[str, Any]:
headers: dict[str, Any] = {}
_kwargs: dict[str, Any] = {
"method": "put",
"url": f"/tokens/{user_id}",
}
_kwargs["json"] = body.to_dict()
headers["Content-Type"] = "application/json"
_kwargs["headers"] = headers
return _kwargs
def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[HTTPValidationError, Token]]:
if response.status_code == 200:
response_200 = Token.from_dict(response.json())
return response_200
if response.status_code == 422:
response_422 = HTTPValidationError.from_dict(response.json())
return response_422
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None
def _build_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Response[Union[HTTPValidationError, Token]]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)
def sync_detailed(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
body: TokenUpdate,
) -> Response[Union[HTTPValidationError, Token]]:
"""Update Token Api
Args:
user_id (str):
body (TokenUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, Token]]
"""
kwargs = _get_kwargs(
user_id=user_id,
body=body,
)
response = client.get_httpx_client().request(
**kwargs,
)
return _build_response(client=client, response=response)
def sync(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
body: TokenUpdate,
) -> Optional[Union[HTTPValidationError, Token]]:
"""Update Token Api
Args:
user_id (str):
body (TokenUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, Token]
"""
return sync_detailed(
user_id=user_id,
client=client,
body=body,
).parsed
async def asyncio_detailed(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
body: TokenUpdate,
) -> Response[Union[HTTPValidationError, Token]]:
"""Update Token Api
Args:
user_id (str):
body (TokenUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Response[Union[HTTPValidationError, Token]]
"""
kwargs = _get_kwargs(
user_id=user_id,
body=body,
)
response = await client.get_async_httpx_client().request(**kwargs)
return _build_response(client=client, response=response)
async def asyncio(
user_id: str,
*,
client: Union[AuthenticatedClient, Client],
body: TokenUpdate,
) -> Optional[Union[HTTPValidationError, Token]]:
"""Update Token Api
Args:
user_id (str):
body (TokenUpdate):
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.
Returns:
Union[HTTPValidationError, Token]
"""
return (
await asyncio_detailed(
user_id=user_id,
client=client,
body=body,
)
).parsed

View File

@@ -0,0 +1,268 @@
import ssl
from typing import Any, Optional, Union
import httpx
from attrs import define, evolve, field
@define
class Client:
"""A class for keeping track of data related to the API
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
``cookies``: A dictionary of cookies to be sent with every request
``headers``: A dictionary of headers to be sent with every request
``timeout``: The maximum amount of a time a request can take. API functions will raise
httpx.TimeoutException if this is exceeded.
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
but can be set to False for testing purposes.
``follow_redirects``: Whether or not to follow redirects. Default value is False.
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
Attributes:
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
argument to the constructor.
"""
raise_on_unexpected_status: bool = field(default=False, kw_only=True)
_base_url: str = field(alias="base_url")
_cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
_headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
_timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True, alias="timeout")
_verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True, alias="verify_ssl")
_follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
_httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
_client: Optional[httpx.Client] = field(default=None, init=False)
_async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
def with_headers(self, headers: dict[str, str]) -> "Client":
"""Get a new client matching this one with additional headers"""
if self._client is not None:
self._client.headers.update(headers)
if self._async_client is not None:
self._async_client.headers.update(headers)
return evolve(self, headers={**self._headers, **headers})
def with_cookies(self, cookies: dict[str, str]) -> "Client":
"""Get a new client matching this one with additional cookies"""
if self._client is not None:
self._client.cookies.update(cookies)
if self._async_client is not None:
self._async_client.cookies.update(cookies)
return evolve(self, cookies={**self._cookies, **cookies})
def with_timeout(self, timeout: httpx.Timeout) -> "Client":
"""Get a new client matching this one with a new timeout (in seconds)"""
if self._client is not None:
self._client.timeout = timeout
if self._async_client is not None:
self._async_client.timeout = timeout
return evolve(self, timeout=timeout)
def set_httpx_client(self, client: httpx.Client) -> "Client":
"""Manually set the underlying httpx.Client
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
"""
self._client = client
return self
def get_httpx_client(self) -> httpx.Client:
"""Get the underlying httpx.Client, constructing a new one if not previously set"""
if self._client is None:
self._client = httpx.Client(
base_url=self._base_url,
cookies=self._cookies,
headers=self._headers,
timeout=self._timeout,
verify=self._verify_ssl,
follow_redirects=self._follow_redirects,
**self._httpx_args,
)
return self._client
def __enter__(self) -> "Client":
"""Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
self.get_httpx_client().__enter__()
return self
def __exit__(self, *args: Any, **kwargs: Any) -> None:
"""Exit a context manager for internal httpx.Client (see httpx docs)"""
self.get_httpx_client().__exit__(*args, **kwargs)
def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client":
"""Manually the underlying httpx.AsyncClient
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
"""
self._async_client = async_client
return self
def get_async_httpx_client(self) -> httpx.AsyncClient:
"""Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
if self._async_client is None:
self._async_client = httpx.AsyncClient(
base_url=self._base_url,
cookies=self._cookies,
headers=self._headers,
timeout=self._timeout,
verify=self._verify_ssl,
follow_redirects=self._follow_redirects,
**self._httpx_args,
)
return self._async_client
async def __aenter__(self) -> "Client":
"""Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
await self.get_async_httpx_client().__aenter__()
return self
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
"""Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
await self.get_async_httpx_client().__aexit__(*args, **kwargs)
@define
class AuthenticatedClient:
"""A Client which has been authenticated for use on secured endpoints
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
``cookies``: A dictionary of cookies to be sent with every request
``headers``: A dictionary of headers to be sent with every request
``timeout``: The maximum amount of a time a request can take. API functions will raise
httpx.TimeoutException if this is exceeded.
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
but can be set to False for testing purposes.
``follow_redirects``: Whether or not to follow redirects. Default value is False.
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
Attributes:
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
argument to the constructor.
token: The token to use for authentication
prefix: The prefix to use for the Authorization header
auth_header_name: The name of the Authorization header
"""
raise_on_unexpected_status: bool = field(default=False, kw_only=True)
_base_url: str = field(alias="base_url")
_cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
_headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
_timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True, alias="timeout")
_verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True, alias="verify_ssl")
_follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
_httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
_client: Optional[httpx.Client] = field(default=None, init=False)
_async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
token: str
prefix: str = "Bearer"
auth_header_name: str = "Authorization"
def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":
"""Get a new client matching this one with additional headers"""
if self._client is not None:
self._client.headers.update(headers)
if self._async_client is not None:
self._async_client.headers.update(headers)
return evolve(self, headers={**self._headers, **headers})
def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":
"""Get a new client matching this one with additional cookies"""
if self._client is not None:
self._client.cookies.update(cookies)
if self._async_client is not None:
self._async_client.cookies.update(cookies)
return evolve(self, cookies={**self._cookies, **cookies})
def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":
"""Get a new client matching this one with a new timeout (in seconds)"""
if self._client is not None:
self._client.timeout = timeout
if self._async_client is not None:
self._async_client.timeout = timeout
return evolve(self, timeout=timeout)
def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient":
"""Manually set the underlying httpx.Client
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
"""
self._client = client
return self
def get_httpx_client(self) -> httpx.Client:
"""Get the underlying httpx.Client, constructing a new one if not previously set"""
if self._client is None:
self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
self._client = httpx.Client(
base_url=self._base_url,
cookies=self._cookies,
headers=self._headers,
timeout=self._timeout,
verify=self._verify_ssl,
follow_redirects=self._follow_redirects,
**self._httpx_args,
)
return self._client
def __enter__(self) -> "AuthenticatedClient":
"""Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
self.get_httpx_client().__enter__()
return self
def __exit__(self, *args: Any, **kwargs: Any) -> None:
"""Exit a context manager for internal httpx.Client (see httpx docs)"""
self.get_httpx_client().__exit__(*args, **kwargs)
def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient":
"""Manually the underlying httpx.AsyncClient
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
"""
self._async_client = async_client
return self
def get_async_httpx_client(self) -> httpx.AsyncClient:
"""Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
if self._async_client is None:
self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
self._async_client = httpx.AsyncClient(
base_url=self._base_url,
cookies=self._cookies,
headers=self._headers,
timeout=self._timeout,
verify=self._verify_ssl,
follow_redirects=self._follow_redirects,
**self._httpx_args,
)
return self._async_client
async def __aenter__(self) -> "AuthenticatedClient":
"""Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
await self.get_async_httpx_client().__aenter__()
return self
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
"""Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
await self.get_async_httpx_client().__aexit__(*args, **kwargs)

View File

@@ -0,0 +1,16 @@
"""Contains shared errors types that can be raised from API functions"""
class UnexpectedStatus(Exception):
"""Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True"""
def __init__(self, status_code: int, content: bytes):
self.status_code = status_code
self.content = content
super().__init__(
f"Unexpected status code: {status_code}\n\nResponse content:\n{content.decode(errors='ignore')}"
)
__all__ = ["UnexpectedStatus"]

View File

@@ -0,0 +1,67 @@
"""Contains all the data models used in inputs/outputs"""
from .activity import Activity
from .activity_activity_metadata_type_0 import ActivityActivityMetadataType0
from .analysis_artifact import AnalysisArtifact
from .analysis_artifact_create import AnalysisArtifactCreate
from .analysis_artifact_create_data import AnalysisArtifactCreateData
from .analysis_artifact_data import AnalysisArtifactData
from .body_upload_activity_activities_post import BodyUploadActivityActivitiesPost
from .coaching_session import CoachingSession
from .coaching_session_conversation import CoachingSessionConversation
from .coaching_session_create import CoachingSessionCreate
from .coaching_session_create_conversation import CoachingSessionCreateConversation
from .health_metric import HealthMetric
from .health_metric_create import HealthMetricCreate
from .health_metric_update import HealthMetricUpdate
from .http_validation_error import HTTPValidationError
from .token import Token
from .token_create import TokenCreate
from .token_update import TokenUpdate
from .user import User
from .user_create import UserCreate
from .user_create_preferences_type_0 import UserCreatePreferencesType0
from .user_preferences_type_0 import UserPreferencesType0
from .user_update import UserUpdate
from .user_update_preferences_type_0 import UserUpdatePreferencesType0
from .validation_error import ValidationError
from .workout_plan import WorkoutPlan
from .workout_plan_create import WorkoutPlanCreate
from .workout_plan_create_plan_details import WorkoutPlanCreatePlanDetails
from .workout_plan_plan_details import WorkoutPlanPlanDetails
from .workout_plan_update import WorkoutPlanUpdate
from .workout_plan_update_plan_details_type_0 import WorkoutPlanUpdatePlanDetailsType0
__all__ = (
"Activity",
"ActivityActivityMetadataType0",
"AnalysisArtifact",
"AnalysisArtifactCreate",
"AnalysisArtifactCreateData",
"AnalysisArtifactData",
"BodyUploadActivityActivitiesPost",
"CoachingSession",
"CoachingSessionConversation",
"CoachingSessionCreate",
"CoachingSessionCreateConversation",
"HealthMetric",
"HealthMetricCreate",
"HealthMetricUpdate",
"HTTPValidationError",
"Token",
"TokenCreate",
"TokenUpdate",
"User",
"UserCreate",
"UserCreatePreferencesType0",
"UserPreferencesType0",
"UserUpdate",
"UserUpdatePreferencesType0",
"ValidationError",
"WorkoutPlan",
"WorkoutPlanCreate",
"WorkoutPlanCreatePlanDetails",
"WorkoutPlanPlanDetails",
"WorkoutPlanUpdate",
"WorkoutPlanUpdatePlanDetailsType0",
)

View File

@@ -0,0 +1,125 @@
import datetime
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.activity_activity_metadata_type_0 import ActivityActivityMetadataType0
T = TypeVar("T", bound="Activity")
@_attrs_define
class Activity:
"""
Attributes:
user_id (int):
file_path (str):
id (int):
created_at (datetime.datetime):
activity_metadata (Union['ActivityActivityMetadataType0', None, Unset]):
"""
user_id: int
file_path: str
id: int
created_at: datetime.datetime
activity_metadata: Union["ActivityActivityMetadataType0", None, Unset] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
from ..models.activity_activity_metadata_type_0 import ActivityActivityMetadataType0
user_id = self.user_id
file_path = self.file_path
id = self.id
created_at = self.created_at.isoformat()
activity_metadata: Union[None, Unset, dict[str, Any]]
if isinstance(self.activity_metadata, Unset):
activity_metadata = UNSET
elif isinstance(self.activity_metadata, ActivityActivityMetadataType0):
activity_metadata = self.activity_metadata.to_dict()
else:
activity_metadata = self.activity_metadata
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"user_id": user_id,
"file_path": file_path,
"id": id,
"created_at": created_at,
}
)
if activity_metadata is not UNSET:
field_dict["activity_metadata"] = activity_metadata
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.activity_activity_metadata_type_0 import ActivityActivityMetadataType0
d = dict(src_dict)
user_id = d.pop("user_id")
file_path = d.pop("file_path")
id = d.pop("id")
created_at = isoparse(d.pop("created_at"))
def _parse_activity_metadata(data: object) -> Union["ActivityActivityMetadataType0", None, Unset]:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, dict):
raise TypeError()
activity_metadata_type_0 = ActivityActivityMetadataType0.from_dict(data)
return activity_metadata_type_0
except: # noqa: E722
pass
return cast(Union["ActivityActivityMetadataType0", None, Unset], data)
activity_metadata = _parse_activity_metadata(d.pop("activity_metadata", UNSET))
activity = cls(
user_id=user_id,
file_path=file_path,
id=id,
created_at=created_at,
activity_metadata=activity_metadata,
)
activity.additional_properties = d
return activity
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="ActivityActivityMetadataType0")
@_attrs_define
class ActivityActivityMetadataType0:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
activity_activity_metadata_type_0 = cls()
activity_activity_metadata_type_0.additional_properties = d
return activity_activity_metadata_type_0
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,91 @@
import datetime
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
if TYPE_CHECKING:
from ..models.analysis_artifact_data import AnalysisArtifactData
T = TypeVar("T", bound="AnalysisArtifact")
@_attrs_define
class AnalysisArtifact:
"""
Attributes:
activity_id (int):
data (AnalysisArtifactData):
id (int):
created_at (datetime.datetime):
"""
activity_id: int
data: "AnalysisArtifactData"
id: int
created_at: datetime.datetime
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
activity_id = self.activity_id
data = self.data.to_dict()
id = self.id
created_at = self.created_at.isoformat()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"activity_id": activity_id,
"data": data,
"id": id,
"created_at": created_at,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.analysis_artifact_data import AnalysisArtifactData
d = dict(src_dict)
activity_id = d.pop("activity_id")
data = AnalysisArtifactData.from_dict(d.pop("data"))
id = d.pop("id")
created_at = isoparse(d.pop("created_at"))
analysis_artifact = cls(
activity_id=activity_id,
data=data,
id=id,
created_at=created_at,
)
analysis_artifact.additional_properties = d
return analysis_artifact
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,65 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.analysis_artifact_create_data import AnalysisArtifactCreateData
T = TypeVar("T", bound="AnalysisArtifactCreate")
@_attrs_define
class AnalysisArtifactCreate:
"""
Attributes:
data (AnalysisArtifactCreateData):
"""
data: "AnalysisArtifactCreateData"
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
data = self.data.to_dict()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"data": data,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.analysis_artifact_create_data import AnalysisArtifactCreateData
d = dict(src_dict)
data = AnalysisArtifactCreateData.from_dict(d.pop("data"))
analysis_artifact_create = cls(
data=data,
)
analysis_artifact_create.additional_properties = d
return analysis_artifact_create
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="AnalysisArtifactCreateData")
@_attrs_define
class AnalysisArtifactCreateData:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
analysis_artifact_create_data = cls()
analysis_artifact_create_data.additional_properties = d
return analysis_artifact_create_data
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="AnalysisArtifactData")
@_attrs_define
class AnalysisArtifactData:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
analysis_artifact_data = cls()
analysis_artifact_data.additional_properties = d
return analysis_artifact_data
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,73 @@
from collections.abc import Mapping
from io import BytesIO
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from .. import types
from ..types import File
T = TypeVar("T", bound="BodyUploadActivityActivitiesPost")
@_attrs_define
class BodyUploadActivityActivitiesPost:
"""
Attributes:
file (File):
"""
file: File
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
file = self.file.to_tuple()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"file": file,
}
)
return field_dict
def to_multipart(self) -> types.RequestFiles:
files: types.RequestFiles = []
files.append(("file", self.file.to_tuple()))
for prop_name, prop in self.additional_properties.items():
files.append((prop_name, (None, str(prop).encode(), "text/plain")))
return files
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
file = File(payload=BytesIO(d.pop("file")))
body_upload_activity_activities_post = cls(
file=file,
)
body_upload_activity_activities_post.additional_properties = d
return body_upload_activity_activities_post
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,83 @@
import datetime
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
if TYPE_CHECKING:
from ..models.coaching_session_conversation import CoachingSessionConversation
T = TypeVar("T", bound="CoachingSession")
@_attrs_define
class CoachingSession:
"""
Attributes:
conversation (CoachingSessionConversation):
id (int):
created_at (datetime.datetime):
"""
conversation: "CoachingSessionConversation"
id: int
created_at: datetime.datetime
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
conversation = self.conversation.to_dict()
id = self.id
created_at = self.created_at.isoformat()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"conversation": conversation,
"id": id,
"created_at": created_at,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.coaching_session_conversation import CoachingSessionConversation
d = dict(src_dict)
conversation = CoachingSessionConversation.from_dict(d.pop("conversation"))
id = d.pop("id")
created_at = isoparse(d.pop("created_at"))
coaching_session = cls(
conversation=conversation,
id=id,
created_at=created_at,
)
coaching_session.additional_properties = d
return coaching_session
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="CoachingSessionConversation")
@_attrs_define
class CoachingSessionConversation:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
coaching_session_conversation = cls()
coaching_session_conversation.additional_properties = d
return coaching_session_conversation
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,65 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.coaching_session_create_conversation import CoachingSessionCreateConversation
T = TypeVar("T", bound="CoachingSessionCreate")
@_attrs_define
class CoachingSessionCreate:
"""
Attributes:
conversation (CoachingSessionCreateConversation):
"""
conversation: "CoachingSessionCreateConversation"
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
conversation = self.conversation.to_dict()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"conversation": conversation,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.coaching_session_create_conversation import CoachingSessionCreateConversation
d = dict(src_dict)
conversation = CoachingSessionCreateConversation.from_dict(d.pop("conversation"))
coaching_session_create = cls(
conversation=conversation,
)
coaching_session_create.additional_properties = d
return coaching_session_create
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="CoachingSessionCreateConversation")
@_attrs_define
class CoachingSessionCreateConversation:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
coaching_session_create_conversation = cls()
coaching_session_create_conversation.additional_properties = d
return coaching_session_create_conversation
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,117 @@
import datetime
from collections.abc import Mapping
from typing import Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
from ..types import UNSET, Unset
T = TypeVar("T", bound="HealthMetric")
@_attrs_define
class HealthMetric:
"""
Attributes:
user_id (int):
metric_type (str):
value (float):
id (int):
timestamp (Union[None, Unset, datetime.datetime]):
"""
user_id: int
metric_type: str
value: float
id: int
timestamp: Union[None, Unset, datetime.datetime] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
user_id = self.user_id
metric_type = self.metric_type
value = self.value
id = self.id
timestamp: Union[None, Unset, str]
if isinstance(self.timestamp, Unset):
timestamp = UNSET
elif isinstance(self.timestamp, datetime.datetime):
timestamp = self.timestamp.isoformat()
else:
timestamp = self.timestamp
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"user_id": user_id,
"metric_type": metric_type,
"value": value,
"id": id,
}
)
if timestamp is not UNSET:
field_dict["timestamp"] = timestamp
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
user_id = d.pop("user_id")
metric_type = d.pop("metric_type")
value = d.pop("value")
id = d.pop("id")
def _parse_timestamp(data: object) -> Union[None, Unset, datetime.datetime]:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, str):
raise TypeError()
timestamp_type_0 = isoparse(data)
return timestamp_type_0
except: # noqa: E722
pass
return cast(Union[None, Unset, datetime.datetime], data)
timestamp = _parse_timestamp(d.pop("timestamp", UNSET))
health_metric = cls(
user_id=user_id,
metric_type=metric_type,
value=value,
id=id,
timestamp=timestamp,
)
health_metric.additional_properties = d
return health_metric
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,109 @@
import datetime
from collections.abc import Mapping
from typing import Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
from ..types import UNSET, Unset
T = TypeVar("T", bound="HealthMetricCreate")
@_attrs_define
class HealthMetricCreate:
"""
Attributes:
user_id (int):
metric_type (str):
value (float):
timestamp (Union[None, Unset, datetime.datetime]):
"""
user_id: int
metric_type: str
value: float
timestamp: Union[None, Unset, datetime.datetime] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
user_id = self.user_id
metric_type = self.metric_type
value = self.value
timestamp: Union[None, Unset, str]
if isinstance(self.timestamp, Unset):
timestamp = UNSET
elif isinstance(self.timestamp, datetime.datetime):
timestamp = self.timestamp.isoformat()
else:
timestamp = self.timestamp
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"user_id": user_id,
"metric_type": metric_type,
"value": value,
}
)
if timestamp is not UNSET:
field_dict["timestamp"] = timestamp
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
user_id = d.pop("user_id")
metric_type = d.pop("metric_type")
value = d.pop("value")
def _parse_timestamp(data: object) -> Union[None, Unset, datetime.datetime]:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, str):
raise TypeError()
timestamp_type_0 = isoparse(data)
return timestamp_type_0
except: # noqa: E722
pass
return cast(Union[None, Unset, datetime.datetime], data)
timestamp = _parse_timestamp(d.pop("timestamp", UNSET))
health_metric_create = cls(
user_id=user_id,
metric_type=metric_type,
value=value,
timestamp=timestamp,
)
health_metric_create.additional_properties = d
return health_metric_create
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,123 @@
import datetime
from collections.abc import Mapping
from typing import Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
from ..types import UNSET, Unset
T = TypeVar("T", bound="HealthMetricUpdate")
@_attrs_define
class HealthMetricUpdate:
"""
Attributes:
metric_type (Union[None, Unset, str]):
value (Union[None, Unset, float]):
timestamp (Union[None, Unset, datetime.datetime]):
"""
metric_type: Union[None, Unset, str] = UNSET
value: Union[None, Unset, float] = UNSET
timestamp: Union[None, Unset, datetime.datetime] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
metric_type: Union[None, Unset, str]
if isinstance(self.metric_type, Unset):
metric_type = UNSET
else:
metric_type = self.metric_type
value: Union[None, Unset, float]
if isinstance(self.value, Unset):
value = UNSET
else:
value = self.value
timestamp: Union[None, Unset, str]
if isinstance(self.timestamp, Unset):
timestamp = UNSET
elif isinstance(self.timestamp, datetime.datetime):
timestamp = self.timestamp.isoformat()
else:
timestamp = self.timestamp
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update({})
if metric_type is not UNSET:
field_dict["metric_type"] = metric_type
if value is not UNSET:
field_dict["value"] = value
if timestamp is not UNSET:
field_dict["timestamp"] = timestamp
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
def _parse_metric_type(data: object) -> Union[None, Unset, str]:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(Union[None, Unset, str], data)
metric_type = _parse_metric_type(d.pop("metric_type", UNSET))
def _parse_value(data: object) -> Union[None, Unset, float]:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(Union[None, Unset, float], data)
value = _parse_value(d.pop("value", UNSET))
def _parse_timestamp(data: object) -> Union[None, Unset, datetime.datetime]:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, str):
raise TypeError()
timestamp_type_0 = isoparse(data)
return timestamp_type_0
except: # noqa: E722
pass
return cast(Union[None, Unset, datetime.datetime], data)
timestamp = _parse_timestamp(d.pop("timestamp", UNSET))
health_metric_update = cls(
metric_type=metric_type,
value=value,
timestamp=timestamp,
)
health_metric_update.additional_properties = d
return health_metric_update
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,75 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, Union
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.validation_error import ValidationError
T = TypeVar("T", bound="HTTPValidationError")
@_attrs_define
class HTTPValidationError:
"""
Attributes:
detail (Union[Unset, list['ValidationError']]):
"""
detail: Union[Unset, list["ValidationError"]] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
detail: Union[Unset, list[dict[str, Any]]] = UNSET
if not isinstance(self.detail, Unset):
detail = []
for detail_item_data in self.detail:
detail_item = detail_item_data.to_dict()
detail.append(detail_item)
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update({})
if detail is not UNSET:
field_dict["detail"] = detail
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.validation_error import ValidationError
d = dict(src_dict)
detail = []
_detail = d.pop("detail", UNSET)
for detail_item_data in _detail or []:
detail_item = ValidationError.from_dict(detail_item_data)
detail.append(detail_item)
http_validation_error = cls(
detail=detail,
)
http_validation_error.additional_properties = d
return http_validation_error
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,125 @@
import datetime
from collections.abc import Mapping
from typing import Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
from ..types import UNSET, Unset
T = TypeVar("T", bound="Token")
@_attrs_define
class Token:
"""
Attributes:
access_token (str):
refresh_token (str):
expires_at (datetime.datetime):
user_id (str):
created_at (datetime.datetime):
updated_at (Union[None, Unset, datetime.datetime]):
"""
access_token: str
refresh_token: str
expires_at: datetime.datetime
user_id: str
created_at: datetime.datetime
updated_at: Union[None, Unset, datetime.datetime] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
access_token = self.access_token
refresh_token = self.refresh_token
expires_at = self.expires_at.isoformat()
user_id = self.user_id
created_at = self.created_at.isoformat()
updated_at: Union[None, Unset, str]
if isinstance(self.updated_at, Unset):
updated_at = UNSET
elif isinstance(self.updated_at, datetime.datetime):
updated_at = self.updated_at.isoformat()
else:
updated_at = self.updated_at
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"access_token": access_token,
"refresh_token": refresh_token,
"expires_at": expires_at,
"user_id": user_id,
"created_at": created_at,
}
)
if updated_at is not UNSET:
field_dict["updated_at"] = updated_at
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
access_token = d.pop("access_token")
refresh_token = d.pop("refresh_token")
expires_at = isoparse(d.pop("expires_at"))
user_id = d.pop("user_id")
created_at = isoparse(d.pop("created_at"))
def _parse_updated_at(data: object) -> Union[None, Unset, datetime.datetime]:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, str):
raise TypeError()
updated_at_type_0 = isoparse(data)
return updated_at_type_0
except: # noqa: E722
pass
return cast(Union[None, Unset, datetime.datetime], data)
updated_at = _parse_updated_at(d.pop("updated_at", UNSET))
token = cls(
access_token=access_token,
refresh_token=refresh_token,
expires_at=expires_at,
user_id=user_id,
created_at=created_at,
updated_at=updated_at,
)
token.additional_properties = d
return token
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,85 @@
import datetime
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
T = TypeVar("T", bound="TokenCreate")
@_attrs_define
class TokenCreate:
"""
Attributes:
access_token (str):
refresh_token (str):
expires_at (datetime.datetime):
user_id (str):
"""
access_token: str
refresh_token: str
expires_at: datetime.datetime
user_id: str
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
access_token = self.access_token
refresh_token = self.refresh_token
expires_at = self.expires_at.isoformat()
user_id = self.user_id
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"access_token": access_token,
"refresh_token": refresh_token,
"expires_at": expires_at,
"user_id": user_id,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
access_token = d.pop("access_token")
refresh_token = d.pop("refresh_token")
expires_at = isoparse(d.pop("expires_at"))
user_id = d.pop("user_id")
token_create = cls(
access_token=access_token,
refresh_token=refresh_token,
expires_at=expires_at,
user_id=user_id,
)
token_create.additional_properties = d
return token_create
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,77 @@
import datetime
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
T = TypeVar("T", bound="TokenUpdate")
@_attrs_define
class TokenUpdate:
"""
Attributes:
access_token (str):
refresh_token (str):
expires_at (datetime.datetime):
"""
access_token: str
refresh_token: str
expires_at: datetime.datetime
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
access_token = self.access_token
refresh_token = self.refresh_token
expires_at = self.expires_at.isoformat()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"access_token": access_token,
"refresh_token": refresh_token,
"expires_at": expires_at,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
access_token = d.pop("access_token")
refresh_token = d.pop("refresh_token")
expires_at = isoparse(d.pop("expires_at"))
token_update = cls(
access_token=access_token,
refresh_token=refresh_token,
expires_at=expires_at,
)
token_update.additional_properties = d
return token_update
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,115 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.user_preferences_type_0 import UserPreferencesType0
T = TypeVar("T", bound="User")
@_attrs_define
class User:
"""
Attributes:
name (str):
email (str):
id (int):
preferences (Union['UserPreferencesType0', None, Unset]):
"""
name: str
email: str
id: int
preferences: Union["UserPreferencesType0", None, Unset] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
from ..models.user_preferences_type_0 import UserPreferencesType0
name = self.name
email = self.email
id = self.id
preferences: Union[None, Unset, dict[str, Any]]
if isinstance(self.preferences, Unset):
preferences = UNSET
elif isinstance(self.preferences, UserPreferencesType0):
preferences = self.preferences.to_dict()
else:
preferences = self.preferences
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"name": name,
"email": email,
"id": id,
}
)
if preferences is not UNSET:
field_dict["preferences"] = preferences
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.user_preferences_type_0 import UserPreferencesType0
d = dict(src_dict)
name = d.pop("name")
email = d.pop("email")
id = d.pop("id")
def _parse_preferences(data: object) -> Union["UserPreferencesType0", None, Unset]:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, dict):
raise TypeError()
preferences_type_0 = UserPreferencesType0.from_dict(data)
return preferences_type_0
except: # noqa: E722
pass
return cast(Union["UserPreferencesType0", None, Unset], data)
preferences = _parse_preferences(d.pop("preferences", UNSET))
user = cls(
name=name,
email=email,
id=id,
preferences=preferences,
)
user.additional_properties = d
return user
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,107 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.user_create_preferences_type_0 import UserCreatePreferencesType0
T = TypeVar("T", bound="UserCreate")
@_attrs_define
class UserCreate:
"""
Attributes:
name (str):
email (str):
preferences (Union['UserCreatePreferencesType0', None, Unset]):
"""
name: str
email: str
preferences: Union["UserCreatePreferencesType0", None, Unset] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
from ..models.user_create_preferences_type_0 import UserCreatePreferencesType0
name = self.name
email = self.email
preferences: Union[None, Unset, dict[str, Any]]
if isinstance(self.preferences, Unset):
preferences = UNSET
elif isinstance(self.preferences, UserCreatePreferencesType0):
preferences = self.preferences.to_dict()
else:
preferences = self.preferences
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"name": name,
"email": email,
}
)
if preferences is not UNSET:
field_dict["preferences"] = preferences
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.user_create_preferences_type_0 import UserCreatePreferencesType0
d = dict(src_dict)
name = d.pop("name")
email = d.pop("email")
def _parse_preferences(data: object) -> Union["UserCreatePreferencesType0", None, Unset]:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, dict):
raise TypeError()
preferences_type_0 = UserCreatePreferencesType0.from_dict(data)
return preferences_type_0
except: # noqa: E722
pass
return cast(Union["UserCreatePreferencesType0", None, Unset], data)
preferences = _parse_preferences(d.pop("preferences", UNSET))
user_create = cls(
name=name,
email=email,
preferences=preferences,
)
user_create.additional_properties = d
return user_create
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="UserCreatePreferencesType0")
@_attrs_define
class UserCreatePreferencesType0:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
user_create_preferences_type_0 = cls()
user_create_preferences_type_0.additional_properties = d
return user_create_preferences_type_0
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="UserPreferencesType0")
@_attrs_define
class UserPreferencesType0:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
user_preferences_type_0 = cls()
user_preferences_type_0.additional_properties = d
return user_preferences_type_0
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,129 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.user_update_preferences_type_0 import UserUpdatePreferencesType0
T = TypeVar("T", bound="UserUpdate")
@_attrs_define
class UserUpdate:
"""
Attributes:
name (Union[None, Unset, str]):
email (Union[None, Unset, str]):
preferences (Union['UserUpdatePreferencesType0', None, Unset]):
"""
name: Union[None, Unset, str] = UNSET
email: Union[None, Unset, str] = UNSET
preferences: Union["UserUpdatePreferencesType0", None, Unset] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
from ..models.user_update_preferences_type_0 import UserUpdatePreferencesType0
name: Union[None, Unset, str]
if isinstance(self.name, Unset):
name = UNSET
else:
name = self.name
email: Union[None, Unset, str]
if isinstance(self.email, Unset):
email = UNSET
else:
email = self.email
preferences: Union[None, Unset, dict[str, Any]]
if isinstance(self.preferences, Unset):
preferences = UNSET
elif isinstance(self.preferences, UserUpdatePreferencesType0):
preferences = self.preferences.to_dict()
else:
preferences = self.preferences
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update({})
if name is not UNSET:
field_dict["name"] = name
if email is not UNSET:
field_dict["email"] = email
if preferences is not UNSET:
field_dict["preferences"] = preferences
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.user_update_preferences_type_0 import UserUpdatePreferencesType0
d = dict(src_dict)
def _parse_name(data: object) -> Union[None, Unset, str]:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(Union[None, Unset, str], data)
name = _parse_name(d.pop("name", UNSET))
def _parse_email(data: object) -> Union[None, Unset, str]:
if data is None:
return data
if isinstance(data, Unset):
return data
return cast(Union[None, Unset, str], data)
email = _parse_email(d.pop("email", UNSET))
def _parse_preferences(data: object) -> Union["UserUpdatePreferencesType0", None, Unset]:
if data is None:
return data
if isinstance(data, Unset):
return data
try:
if not isinstance(data, dict):
raise TypeError()
preferences_type_0 = UserUpdatePreferencesType0.from_dict(data)
return preferences_type_0
except: # noqa: E722
pass
return cast(Union["UserUpdatePreferencesType0", None, Unset], data)
preferences = _parse_preferences(d.pop("preferences", UNSET))
user_update = cls(
name=name,
email=email,
preferences=preferences,
)
user_update.additional_properties = d
return user_update
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="UserUpdatePreferencesType0")
@_attrs_define
class UserUpdatePreferencesType0:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
user_update_preferences_type_0 = cls()
user_update_preferences_type_0.additional_properties = d
return user_update_preferences_type_0
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,88 @@
from collections.abc import Mapping
from typing import Any, TypeVar, Union, cast
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="ValidationError")
@_attrs_define
class ValidationError:
"""
Attributes:
loc (list[Union[int, str]]):
msg (str):
type_ (str):
"""
loc: list[Union[int, str]]
msg: str
type_: str
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
loc = []
for loc_item_data in self.loc:
loc_item: Union[int, str]
loc_item = loc_item_data
loc.append(loc_item)
msg = self.msg
type_ = self.type_
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"loc": loc,
"msg": msg,
"type": type_,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
loc = []
_loc = d.pop("loc")
for loc_item_data in _loc:
def _parse_loc_item(data: object) -> Union[int, str]:
return cast(Union[int, str], data)
loc_item = _parse_loc_item(loc_item_data)
loc.append(loc_item)
msg = d.pop("msg")
type_ = d.pop("type")
validation_error = cls(
loc=loc,
msg=msg,
type_=type_,
)
validation_error.additional_properties = d
return validation_error
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,91 @@
import datetime
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse
if TYPE_CHECKING:
from ..models.workout_plan_plan_details import WorkoutPlanPlanDetails
T = TypeVar("T", bound="WorkoutPlan")
@_attrs_define
class WorkoutPlan:
"""
Attributes:
user_id (int):
plan_details (WorkoutPlanPlanDetails):
id (int):
created_at (datetime.datetime):
"""
user_id: int
plan_details: "WorkoutPlanPlanDetails"
id: int
created_at: datetime.datetime
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
user_id = self.user_id
plan_details = self.plan_details.to_dict()
id = self.id
created_at = self.created_at.isoformat()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"user_id": user_id,
"plan_details": plan_details,
"id": id,
"created_at": created_at,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.workout_plan_plan_details import WorkoutPlanPlanDetails
d = dict(src_dict)
user_id = d.pop("user_id")
plan_details = WorkoutPlanPlanDetails.from_dict(d.pop("plan_details"))
id = d.pop("id")
created_at = isoparse(d.pop("created_at"))
workout_plan = cls(
user_id=user_id,
plan_details=plan_details,
id=id,
created_at=created_at,
)
workout_plan.additional_properties = d
return workout_plan
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,73 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
if TYPE_CHECKING:
from ..models.workout_plan_create_plan_details import WorkoutPlanCreatePlanDetails
T = TypeVar("T", bound="WorkoutPlanCreate")
@_attrs_define
class WorkoutPlanCreate:
"""
Attributes:
user_id (int):
plan_details (WorkoutPlanCreatePlanDetails):
"""
user_id: int
plan_details: "WorkoutPlanCreatePlanDetails"
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
user_id = self.user_id
plan_details = self.plan_details.to_dict()
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"user_id": user_id,
"plan_details": plan_details,
}
)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
from ..models.workout_plan_create_plan_details import WorkoutPlanCreatePlanDetails
d = dict(src_dict)
user_id = d.pop("user_id")
plan_details = WorkoutPlanCreatePlanDetails.from_dict(d.pop("plan_details"))
workout_plan_create = cls(
user_id=user_id,
plan_details=plan_details,
)
workout_plan_create.additional_properties = d
return workout_plan_create
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

View File

@@ -0,0 +1,44 @@
from collections.abc import Mapping
from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="WorkoutPlanCreatePlanDetails")
@_attrs_define
class WorkoutPlanCreatePlanDetails:
""" """
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
return field_dict
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
workout_plan_create_plan_details = cls()
workout_plan_create_plan_details.additional_properties = d
return workout_plan_create_plan_details
@property
def additional_keys(self) -> list[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties

Some files were not shown because too many files have changed in this diff Show More