openapi: 3.0.1 info: # Rendered by Terraform's templatefile(); the title doubles as the API Gateway # name. API Gateway derives the HTTP API name from info.title on (re)import, so # this MUST equal the module's api_name or a body change renames the API and # breaks the CI endpoint lookup (Items[?Name=='leagueql-api--']). title: ${api_name} version: v1 description: > API for onboarding and querying fantasy football league data. Supports ESPN and Sleeper as data sources. League data is fetched from external APIs, transformed, and stored in DynamoDB for fast retrieval. license: name: MIT paths: /health: get: summary: Health check description: > Public, unauthenticated liveness check (backend/health-check-alerting) — no Clerk authorizer, so external uptime monitors (the Route 53 health check on api.leagueql.com/health) can probe it and get 200 rather than 401. Returns 200 whenever the API is running and responding to requests; it does not touch any downstream dependency. operationId: healthCheck responses: "200": description: Healthy! x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /feature-flags: get: summary: Global feature flags description: > Returns the resolved global feature-flag map (backend/feature-flags / frontend/feature-flags) the SPA uses to build its OpenFeature provider. Resolved from AWS SSM Parameter Store at runtime. Unauthenticated — no Clerk authorizer — so it loads before sign-in; the payload is only non-sensitive global booleans. operationId: getFeatureFlags responses: "200": description: Resolved global feature flags content: application/json: schema: $ref: "#/components/schemas/FeatureFlagsResponse" x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /leagues/yahoo/oauth/authorize: get: summary: Start the Yahoo OAuth link description: > Clerk-authenticated (backend/yahoo-oauth). Mints a single-use state bound to the caller (carrying the pending leagueId, return-context flow, and display mode) and returns the Yahoo consent URL the SPA opens — in a popup for display=popup, else a full-page redirect. The client secret never leaves the backend. operationId: yahooAuthorize parameters: - name: leagueId in: query required: true description: The Yahoo league id to resume onboarding for after the callback schema: type: string maxLength: 100 - name: flow in: query required: false description: > Return context. ONBOARD (default) returns the callback to the landing page, which resumes onboarding inline; MIGRATE returns it to /migrate_league so the migration wizard resumes. schema: type: string enum: [ONBOARD, MIGRATE] default: ONBOARD - name: display in: query required: false description: > How the callback hands the result back. page (default) 302-redirects to the return page; popup returns an HTML page that postMessages the opener and closes, so the connect page never reloads. schema: type: string enum: [page, popup] default: page responses: "200": description: Yahoo consent URL generated "401": description: Unauthenticated security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /leagues/yahoo/oauth/callback: get: summary: Yahoo OAuth callback description: > Public — no Clerk authorizer (backend/yahoo-oauth). Yahoo redirects the browser here with no JWT after the user authorizes. Validates and single-use-consumes the state, exchanges the code for tokens (PKCE public client, no secret), stores an encrypted per-user token item, and hands the linked/declined result back in the way the state's display selects: page 302-redirects to the flow's return page (ONBOARD -> the landing page, which resumes onboarding inline; MIGRATE -> /migrate_league); popup returns an HTML page that postMessages the opener and closes so the connect page never reloads. operationId: yahooCallback parameters: - name: code in: query required: false schema: type: string - name: state in: query required: false schema: type: string - name: error in: query required: false schema: type: string responses: "302": description: Redirect to the frontend connect page with a linked/declined marker x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /leagues/{leagueId}: get: summary: Get league metadata description: > Checks whether a league has been onboarded. If the league exists, returns the league name and the list of seasons the league has been active for. Returns 404 if the league has not been onboarded yet. operationId: getLeague parameters: - name: leagueId in: path required: true description: The ESPN or Sleeper league ID schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The name of the platform the fantasy football league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "ESPN" responses: "200": $ref: "#/components/responses/LeagueFoundResponse" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST # always POST for Lambda proxy, regardless of your route method uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" # use 2.0 for HTTP API (v2) delete: summary: Delete league description: > Deletes an onboarded league and its associated data from DynamoDB and S3. Also decrements the total onboarded league count. operationId: deleteLeague parameters: - name: leagueId in: path required: true description: The ESPN or Sleeper league ID schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The name of the platform the fantasy football league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "ESPN" responses: "200": $ref: "#/components/responses/DeleteLeagueResponse" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST # always POST for Lambda proxy, regardless of your route method uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" # use 2.0 for HTTP API (v2) /leagues/{leagueId}/auto-refresh: put: summary: Enable or disable scheduled auto-refresh for a league description: > Sets the league's scheduled auto-refresh opt-in (backend/scheduled-league-auto-refresh). The flag gates scheduled refresh for ESPN leagues only; Sleeper and Yahoo leagues are always auto-refreshed, so it has no effect for them. Owner only. Disabling the owner's last opted-in ESPN league also removes their stored ESPN cookies (backend/espn-credential-storage). Enabling ESPN auto-refresh still requires fresh cookies, supplied through the onboard/refresh form; this endpoint only records the flag. operationId: setAutoRefresh parameters: - name: leagueId in: path required: true description: The ESPN, Sleeper, or Yahoo league ID schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The name of the platform the fantasy football league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "ESPN" requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/AutoRefreshRequest" responses: "200": description: The auto-refresh setting was updated. content: application/json: schema: $ref: "#/components/schemas/APIResponse" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST # always POST for Lambda proxy, regardless of your route method uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" # use 2.0 for HTTP API (v2) /leagues: post: summary: Onboard a new league or refresh an existing league's data description: > Triggers the onboarding Lambda which fetches all historical season data from the specified platform (ESPN or Sleeper), transforms it via DuckDB, and writes precomputed views to DynamoDB. The requestType query parameter determines whether this is a new onboarding ("ONBOARD") or a refresh of an existing league's data ("REFRESH"). When an ESPN REFRESH with autoRefresh=true, swid and s2 is blocked (409 in progress / up to date / offseason, or 429 weekly cooldown), the API still validates the cookies against ESPN, stores them encrypted and sets auto_refresh_enabled on the league before returning that 409/429, so the opt-in is not lost. Rejected cookies return 400 and an ESPN outage returns 502, and nothing is stored in either case. operationId: onboardLeague parameters: - name: requestType in: query required: true description: > The type of onboarding request being made. Can be "ONBOARD" for new leagues or "REFRESH" to refresh data for an existing league. schema: type: string enum: [ONBOARD, REFRESH] example: "ONBOARD" requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/OnboardRequest" responses: "201": $ref: "#/components/responses/OnboardSuccessResponse" "400": $ref: "#/components/responses/BadRequestError" "409": $ref: "#/components/responses/ConflictError" "422": $ref: "#/components/responses/ValidationError" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" "502": $ref: "#/components/responses/BadGatewayError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST # always POST for Lambda proxy, regardless of your route method uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" # use 2.0 for HTTP API (v2) /leagues/{leagueId}/query: get: summary: Query a precomputed league view description: > Returns a precomputed data view for the specified league. The queryType parameter maps directly to the DynamoDB sort key (e.g. WEEKLY_SCORES#2024). operationId: queryLeague parameters: - name: leagueId in: path required: true description: The ESPN or Sleeper league ID schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The name of the platform the fantasy football league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "ESPN" - name: queryType in: query required: true description: > The precomputed view to retrieve. Season-scoped views require a season suffix (e.g. SEASON_STANDINGS#2024). Cross-season views such as ALL_TIME_STANDINGS do not require a suffix. TRANSACTIONS#{season} returns waivers, free agents, and trades on every platform (ESPN stores the current season only; a season with no stored transactions returns 404). LEAGUE_SETTINGS#{season} returns the season's playoff configuration (num_playoff_teams, playoff_week_start, regular_season_weeks). schema: type: string enum: - TEAMS - MATCHUPS - SEASON_STANDINGS - WEEKLY_STANDINGS - PLAYOFF_BRACKET - DRAFT - TRANSACTIONS - PLATFORM_MIGRATION - LEAGUE_SETTINGS example: "SEASON_STANDINGS" responses: "200": $ref: "#/components/responses/QuerySuccessResponse" "400": $ref: "#/components/responses/BadRequestError" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST # always POST for Lambda proxy, regardless of your route method uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" # use 2.0 for HTTP API (v2) /leagues/{leagueId}/export: get: summary: Export processed league views for selected seasons description: > Returns the processed views for the requested seasons bundled by season and view name, for a member of the league (same membership gate as the query endpoint: ESPN/Yahoo restricted to owner + members, Sleeper open). Each season object contains the available views (standings, weekly_standings, matchups, draft, transactions, playoff_bracket, league_settings, teams); a view with no stored data for a season is omitted. The frontend downloads this as a ZIP of one JSON file per view per season. operationId: exportLeague parameters: - name: leagueId in: path required: true description: The ESPN, Sleeper, or Yahoo league ID schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The name of the platform the fantasy football league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "ESPN" - name: seasons in: query required: true description: > Comma-separated list of season years to export. Seasons the league does not have are ignored; a request with no valid season returns 400. schema: type: string example: "2023,2024" responses: "200": $ref: "#/components/responses/ExportSuccessResponse" "400": $ref: "#/components/responses/BadRequestError" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST # always POST for Lambda proxy, regardless of your route method uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" # use 2.0 for HTTP API (v2) /leagues/{leagueId}/espn_members: post: summary: Fetch ESPN league members description: > Server-side proxy to the ESPN Fantasy API that returns the list of members for a given ESPN league. Avoids browser CORS restrictions by making the request from the Lambda function. operationId: getEspnMembers parameters: - name: leagueId in: path required: true description: The ID of the current (source) league schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The current platform the league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "SLEEPER" - name: espnLeagueId in: query required: true description: The ESPN league ID to fetch members from schema: type: string pattern: '^\d+$' example: "87654321" - name: season in: query required: true description: The ESPN season year schema: type: string pattern: '^\d{4}$' example: "2025" requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/EspnMembersRequest" responses: "200": $ref: "#/components/responses/EspnMembersResponse" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "502": $ref: "#/components/responses/BadGatewayError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /leagues/{leagueId}/yahoo_members: post: summary: Fetch Yahoo league members description: > Server-side proxy (backend/yahoo-members-proxy) that returns a destination Yahoo league's managers for the migration mapping, using the caller's linked Yahoo OAuth token to resolve the numeric league id to its league_key and fetch its teams. The token never reaches the browser. Owner-gated. operationId: getYahooMembers parameters: - name: leagueId in: path required: true description: The ID of the current (source) league schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The current platform the league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "SLEEPER" - name: yahooLeagueId in: query required: true description: The destination Yahoo (numeric) league ID to fetch members from schema: type: string pattern: '^\d+$' example: "456" responses: "200": $ref: "#/components/responses/YahooMembersResponse" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "502": $ref: "#/components/responses/BadGatewayError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /leagues/{leagueId}/migrate: post: summary: Migrate a league to a new platform description: > Migrates an onboarded league from its current platform to a new platform. Writes the new platform lookup entry, records the manager mapping, and updates the league metadata to reflect the new active platform. operationId: migrateLeague parameters: - name: leagueId in: path required: true description: The ID of the current (source) league schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The current platform the league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "SLEEPER" requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/MigrateRequest" responses: "202": $ref: "#/components/responses/MigrateSuccessResponse" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "409": $ref: "#/components/responses/ConflictError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /me/leagues: get: summary: List the caller's leagues description: > Lists every league the authenticated caller owns, has joined by redeeming an invite, or has opened on Sleeper (backend/user-leagues), newest first by updated_at. Backed by the per-user membership index (GSI4). Each entry carries the league's current platform and league ID (enough to open it), its unified seasons, and an owner-only ESPN re-auth flag. Responds with Cache-Control no-store. operationId: getMyLeagues responses: "200": description: The caller's leagues (possibly empty) content: application/json: schema: allOf: - $ref: "#/components/schemas/APIResponse" - type: object properties: data: type: array items: type: object required: - league_id - platform - seasons - espn_reauth_required properties: league_id: type: string description: League ID on the league's current platform (latest season for Sleeper) example: "1048211234567890123" platform: type: string enum: [ESPN, SLEEPER, YAHOO] description: Current platform (active_platform after a migration) league_name: type: string nullable: true seasons: type: array description: Onboarded seasons across all platforms, ascending items: type: string example: ["2022", "2023", "2024"] updated_at: type: string format: date-time nullable: true description: last_refresh_at, else onboarded_at migrated_from: type: string enum: [ESPN, SLEEPER, YAHOO] nullable: true espn_reauth_required: type: boolean description: > True only when the caller owns this auto-refreshed ESPN league and their stored ESPN cookies need re-entry "401": $ref: "#/components/responses/UnauthorizedError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST # always POST for Lambda proxy, regardless of your route method uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" # use 2.0 for HTTP API (v2) /jobs/{jobId}: get: summary: Get the status of an onboard/refresh/migrate job description: > Returns the status of a job triggered by onboarding, refresh, or migration, identified by the correlation (job) ID returned when the job was triggered. Used for polling until the job completes. When the job fails, a user-friendly failure_reason is included. A missing item (never created, or expired after its 24h TTL) is reported as FAILED. operationId: getJobStatus parameters: - name: jobId in: path required: true description: The correlation (job) ID returned when the job was triggered schema: type: string pattern: '^[0-9a-fA-F-]{36}$' example: "f47ac10b-58cc-4372-a567-0e02b2c3d479" responses: "200": $ref: "#/components/responses/JobStatusSuccessResponse" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST # always POST for Lambda proxy, regardless of your route method uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" # use 2.0 for HTTP API (v2) /leagues/{leagueId}/invite-token: post: summary: Mint an invite token description: > Owner-only (backend/league-authorization). Mints a reusable invite token for a gated league (ESPN or Yahoo), returning the plaintext token once; only its sha256 hash is stored (no expiry). The owner shares the resulting link; anyone who redeems it via accept-invite becomes a member without their own ESPN or Yahoo credentials. Minting a new token overwrites the stored hash, invalidating any prior link. Gated leagues only — Sleeper returns 400. operationId: createInviteToken parameters: - name: leagueId in: path required: true description: The fantasy league ID schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The platform the league is on (ESPN or YAHOO; SLEEPER returns 400) schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "ESPN" responses: "200": description: Invite link created content: application/json: schema: allOf: - $ref: "#/components/schemas/APIResponse" - type: object properties: data: type: object properties: token: type: string "400": $ref: "#/components/responses/ValidationError" "401": $ref: "#/components/responses/UnauthorizedError" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /leagues/{leagueId}/accept-invite: post: summary: Redeem an invite token description: > Adds the authenticated caller to a gated league's (ESPN or Yahoo) members when the submitted token matches the stored hash (backend/league-authorization) — no ESPN or Yahoo credentials of their own required. The token is reusable (the stored hash is not consumed). Returns 404 (no outstanding link), 403 (token mismatch), or 400 (Sleeper league). operationId: acceptInvite parameters: - name: leagueId in: path required: true description: The fantasy league ID schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The platform the league is on (ESPN or YAHOO; SLEEPER returns 400) schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "ESPN" requestBody: required: true content: application/json: schema: type: object required: [token] properties: token: type: string description: The plaintext invite token from the owner's link. responses: "200": $ref: "#/components/responses/LeagueFoundResponse" "400": $ref: "#/components/responses/ValidationError" "401": $ref: "#/components/responses/UnauthorizedError" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /leagues/{leagueId}/transfer-token: post: summary: Mint an ownership-transfer token description: > Owner-only (backend/league-authorization). Generates a one-time ownership-transfer token, returning the plaintext token once; only its sha256 hash and a short expiry are stored. Minting a new token invalidates any prior one. operationId: createTransferToken parameters: - name: leagueId in: path required: true description: The ID of the fantasy league schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The platform the league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "SLEEPER" responses: "200": description: Transfer token created content: application/json: schema: allOf: - $ref: "#/components/schemas/APIResponse" - type: object properties: data: type: object properties: token: type: string expires_at: type: string format: date-time "401": $ref: "#/components/responses/UnauthorizedError" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" /leagues/{leagueId}/claim-ownership: post: summary: Claim league ownership with a transfer token description: > Redeems a one-time transfer token to become the league owner (backend/league-authorization). Single-use and race-safe. Returns 404 (no outstanding token), 403 (token mismatch), 410 (expired), or 409 (token already redeemed). operationId: claimOwnership parameters: - name: leagueId in: path required: true description: The ID of the fantasy league schema: type: string pattern: '^\d+$' example: "12345678" - name: platform in: query required: true description: The platform the league is on schema: type: string enum: [ESPN, SLEEPER, YAHOO] example: "SLEEPER" requestBody: required: true content: application/json: schema: type: object required: [token] properties: token: type: string description: The plaintext transfer token issued to the recipient. responses: "200": $ref: "#/components/responses/LeagueFoundResponse" "401": $ref: "#/components/responses/UnauthorizedError" "403": $ref: "#/components/responses/ForbiddenError" "404": $ref: "#/components/responses/LeagueNotFoundError" "409": $ref: "#/components/responses/ConflictError" "410": $ref: "#/components/responses/GoneError" "500": $ref: "#/components/responses/InternalError" security: - ClerkJWT: [] x-amazon-apigateway-integration: type: aws_proxy httpMethod: POST uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations" payloadFormatVersion: "2.0" components: securitySchemes: ClerkJWT: type: apiKey name: Authorization in: header x-amazon-apigateway-authtype: jwt x-amazon-apigateway-authorizer: identitySource: $request.header.Authorization jwtConfiguration: issuer: "${clerk_issuer_url}" audience: - "${clerk_jwt_audience}" type: jwt schemas: LeagueFoundData: type: object required: [seasons] properties: seasons: type: array items: type: string description: Sorted list of seasons the league has been onboarded for. example: ["2023", "2024", "2025"] league_name: type: string description: Display name of the fantasy league. example: "The Gridiron Gang" is_owner: type: boolean description: > Whether the authenticated caller is the league owner (backend/league-authorization). Used by the frontend to gate owner-only actions. example: true onboarded_at: type: string format: date-time description: ISO 8601 timestamp of when the league was onboarded. example: "2025-01-15T12:00:00+00:00" last_refresh_at: type: string format: date-time nullable: true description: > ISO 8601 timestamp of the most recent successful refresh, or null until the league's first refresh. The frontend derives data freshness as last_refresh_at ?? onboarded_at to drive the stale-league refresh reminder. example: "2025-08-24T12:00:00+00:00" auto_refresh_enabled: type: boolean description: > Whether the league is opted into scheduled auto-refresh (backend/scheduled-league-auto-refresh). Meaningful for ESPN only (Sleeper and Yahoo are always auto-refreshed). Drives the connect-form checkbox prefill and the sidebar auto-refresh toggle. False (default) on leagues onboarded before opt-in. example: false espn_reauth_required: type: boolean description: > True only for the owner of an auto-refresh-enabled ESPN league whose stored ESPN cookies were rejected by ESPN during a scheduled refresh, or are missing (backend/league-metadata). Scheduled refresh is paused until the owner re-enters their cookies. Always false for non-owners and for other leagues. example: false espn_credentials_failed_at: type: string format: date-time nullable: true description: > When ESPN rejected the owner's stored cookies. Set only alongside espn_reauth_required for a rejection; null otherwise, including when the cookies are missing. example: null pending_lineup_seasons: type: array items: type: string description: > Seasons (ascending) whose weekly lineups and player points are still being backfilled (backend/yahoo-lineup-backfill). Yahoo only; empty for every other league and once a Yahoo league is fully backfilled. Drives the lineup notification bell and the per-feature pending state. example: ["2019", "2020"] failed_lineup_seasons: type: array items: type: string description: > Seasons (ascending) whose lineup backfill couldn't finish yet (repeated Yahoo throttling or a permanent error). They are retried automatically on the next scheduled refresh. Empty when there are none. example: [] APIResponse: type: object required: [detail] properties: detail: type: string example: "Found league" data: description: Present on success responses that return data; absent otherwise. nullable: true FeatureFlagsResponse: type: object required: [detail, data] properties: detail: type: string example: "Feature flags" data: type: object description: Global feature-flag map (flag name → enabled boolean). properties: banner: type: boolean example: false OnboardRequest: type: object required: [leagueId, platform] properties: leagueId: type: string maxLength: 100 pattern: '^\d+$' description: > The numeric ESPN, Sleeper, or Yahoo league ID (digits only). It is interpolated into the upstream platform request URLs, so non-digit characters are rejected (SEC-04). example: "12345678" platform: type: string enum: [ESPN, SLEEPER, YAHOO] description: The fantasy platform this league belongs to example: "ESPN" season: type: string pattern: '^\d{4}$' description: > The most recent season the league was active for (4-digit year). Required for ESPN leagues only. example: "2025" autoRefresh: type: boolean default: false description: > Opt this ESPN league into scheduled auto-refresh (backend/scheduled-league-auto-refresh). When true, the supplied cookies are stored encrypted at rest so the weekly refresh can reuse them (also when the REFRESH is blocked by a 409/429, after the cookies are validated against ESPN); when false they are not stored. Has no effect for Sleeper or Yahoo (always auto-refreshed); the frontend omits it for Yahoo. example: false s2: type: string description: > ESPN espn_s2 cookie value. Required for private ESPN leagues only. This value is never logged. It is stored (encrypted at rest) ONLY when autoRefresh is true, so the scheduled refresh can reuse it; otherwise it is used transiently for this request and not stored. example: "AEBxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" swid: type: string description: > ESPN SWID cookie value. Required for private ESPN leagues only. This value is never logged. It is stored (encrypted at rest) ONLY when autoRefresh is true, so the scheduled refresh can reuse it; otherwise it is used transiently for this request and not stored. example: "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" AutoRefreshRequest: type: object required: [enabled] properties: enabled: type: boolean description: Whether scheduled auto-refresh should be enabled for the league. example: true EspnMembersRequest: type: object required: [swid, s2] properties: swid: type: string description: ESPN SWID cookie value example: "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" s2: type: string description: ESPN espn_s2 cookie value example: "AEBxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ManagerMappingEntry: type: object additionalProperties: false required: [currentPlatformOwnerId, newPlatformOwnerId, displayName] properties: currentPlatformOwnerId: type: string maxLength: 100 example: "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" newPlatformOwnerId: type: string maxLength: 100 example: "987654321" displayName: type: string maxLength: 200 example: "John Doe" MigrateRequest: type: object required: [newPlatformLeagueId, newPlatform, managerMapping] properties: newPlatformLeagueId: type: string maxLength: 100 pattern: '^\d+$' description: > The numeric league ID on the destination platform (digits only). It is interpolated into the destination-platform request URLs, so non-digit characters are rejected (SEC-04). example: "87654321" newPlatform: type: string enum: [ESPN, SLEEPER, YAHOO] description: The destination platform example: "ESPN" season: type: string pattern: '^\d{4}$' description: Latest season, 4-digit year (required for ESPN destination) example: "2025" s2: type: string description: ESPN espn_s2 cookie value (required for ESPN destination) swid: type: string description: ESPN SWID cookie value (required for ESPN destination) managerMapping: type: array maxItems: 64 items: $ref: "#/components/schemas/ManagerMappingEntry" QueryResponse: type: object required: [data] properties: data: type: array description: Array of precomputed result objects. Shape varies by queryType. items: type: object ExportResponse: type: object required: [data] properties: data: type: object description: > Processed views keyed by season, then by view name. Each view value is an array of result objects whose shape matches the corresponding query view. Views with no data for a season are omitted. additionalProperties: type: object additionalProperties: type: array items: type: object example: "2024": standings: [{}] matchups: [{}] teams: [{}] "2023": standings: [{}] ErrorResponse: type: object required: [error] properties: error: type: string example: "Not found" message: type: string example: "A human-readable description of the error" responses: # ── Success responses ────────────────────────────────── LeagueFoundResponse: description: League found content: application/json: schema: allOf: - $ref: "#/components/schemas/APIResponse" - type: object properties: data: $ref: "#/components/schemas/LeagueFoundData" example: detail: "Found league" data: seasons: ["2023", "2024", "2025"] league_name: "The Gridiron Gang" is_owner: true onboarded_at: "2025-01-15T12:00:00+00:00" last_refresh_at: "2025-08-24T12:00:00+00:00" DeleteLeagueResponse: description: League successfully deleted content: application/json: schema: $ref: "#/components/schemas/APIResponse" example: detail: "Successfully deleted league" OnboardSuccessResponse: description: Onboarding successfully triggered content: application/json: schema: $ref: "#/components/schemas/APIResponse" example: detail: "Successfully triggered onboarding" QuerySuccessResponse: description: Precomputed view returned successfully headers: Cache-Control: description: Instructs the browser not to cache the response, so it is never re-served stale after a league is deleted, re-onboarded, or refreshed schema: type: string example: "no-store" content: application/json: schema: $ref: "#/components/schemas/QueryResponse" ExportSuccessResponse: description: Processed views exported successfully headers: Cache-Control: description: Instructs the browser not to cache the response, so it is never re-served stale after a league is deleted, re-onboarded, or refreshed schema: type: string example: "no-store" content: application/json: schema: $ref: "#/components/schemas/ExportResponse" JobStatusSuccessResponse: description: Job status returned successfully content: application/json: schema: allOf: - $ref: "#/components/schemas/APIResponse" - type: object properties: data: type: object required: [status] properties: status: type: string enum: [IN_PROGRESS, COMPLETED, FAILED] description: Current status of the onboard/refresh/migrate job. example: "IN_PROGRESS" failure_code: type: string nullable: true description: Machine-readable failure category (only when FAILED). example: "ESPN_AUTH" failure_reason: type: string nullable: true description: User-friendly failure message (only when FAILED). example: "ESPN rejected your credentials. Your espn_s2 / SWID cookies may have expired — re-copy them from ESPN and try again." example: detail: "Found job status" data: status: "IN_PROGRESS" failure_code: null failure_reason: null EspnMembersResponse: description: ESPN league members returned successfully content: application/json: schema: allOf: - $ref: "#/components/schemas/APIResponse" - type: object properties: data: type: array items: type: object required: [owner_id, display_name] properties: owner_id: type: string display_name: type: string example: detail: "Found ESPN members" data: - owner_id: "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" display_name: "John Doe" YahooMembersResponse: description: Yahoo league managers returned successfully content: application/json: schema: allOf: - $ref: "#/components/schemas/APIResponse" - type: object properties: data: type: array items: type: object required: [owner_id, display_name] properties: owner_id: type: string description: > The manager's real Yahoo guid when Yahoo exposes it and it is unique in the league; otherwise the per-league manager_id (a team slot number), e.g. when Yahoo masks guids as "--hidden--". display_name: type: string example: detail: "Found Yahoo members" data: - owner_id: "G1ABCDEF" display_name: "Alice" MigrateSuccessResponse: description: Migration successfully initiated content: application/json: schema: allOf: - $ref: "#/components/schemas/APIResponse" - type: object properties: data: type: object required: [correlation_id] properties: correlation_id: type: string example: detail: "Migration initiated" data: correlation_id: "550e8400-e29b-41d4-a716-446655440000" # ── Error responses ──────────────────────────────────── BadRequestError: description: Missing or invalid query parameters content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Bad request" message: "season is required for queryType WEEKLY_SCORES" LeagueNotFoundError: description: League not found — onboarding required content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "League not found" message: "No ESPN league with ID 12345678 has been onboarded. Use POST /leagues to onboard." ValidationError: description: Invalid request body content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Unprocessable entity" message: "platform must be one of: ESPN, SLEEPER, YAHOO" ConflictError: description: Conflict — operation already in progress or league already onboarded content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Conflict" message: "An operation is already in progress for this league" ForbiddenError: description: > The caller is not authorized for this league (backend/league-authorization) — not the owner for a mutating action, or not a member of a confidential ESPN league. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Forbidden" message: "Not the league owner" GoneError: description: The ownership-transfer token has expired (backend/league-authorization) content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Gone" message: "Transfer token has expired" BadGatewayError: description: Upstream ESPN API request failed content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Bad gateway" message: "Failed to fetch ESPN league members" InternalError: description: Unexpected server error content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Internal server error" message: "An unexpected error occurred. Please try again later." UnauthorizedError: description: No authenticated user (missing or invalid Clerk session) content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Unauthorized" message: "Authentication required" TooManyRequests: description: > The league is within the once-per-week refresh cooldown (backend/league-refresh). A manual refresh is rejected until the current UTC date is at least 7 calendar days after the UTC date of the most recent successful refresh (measured in whole days, not an exact 7x24h window). content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: "Too many requests" message: "This league can only be refreshed once per week. You can refresh again in 5 days."