Files
2026-06-11 10:52:07 -04:00

6.8 KiB

VitFit V2 — API Standards

These conventions apply to every endpoint in V2. Define them once here so they do not need to be decided route-by-route during implementation.


Versioning

All API routes are prefixed /api/v1/.

POST   /api/v1/auth/login
GET    /api/v1/videos
POST   /api/v1/workouts
GET    /api/v1/admin/storage

Static files, the health endpoint, and Socket.io are not versioned:

GET    /health
GET    /public/*     (static assets)
       /socket.io/*  (Socket.io handshake)

When a breaking API change is needed, a /api/v2/ prefix is introduced and /api/v1/ continues to work during a transition period. V2 of the API does not mean V3 of the app — version the API independently.


Authentication Header

All protected endpoints expect:

Authorization: Bearer <jwt>

Endpoints that do not require auth: /api/v1/auth/login, /health.


Standard Response Shapes

Success — Single Resource

{
  "data": { ...resource fields }
}

Success — Collection

{
  "data": [ ...items ],
  "meta": {
    "total": 142,
    "page": 1,
    "limit": 50,
    "totalPages": 3
  }
}

Error

{
  "error": {
    "code": "VIDEO_NOT_FOUND",
    "message": "No video with that ID exists in your organization.",
    "field": null
  }
}
  • code — machine-readable, SCREAMING_SNAKE_CASE, stable across versions
  • message — human-readable, for display or logging
  • field — the specific input field that caused the error, or null if not field-specific

Validation Error (multiple fields)

{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "One or more fields are invalid.",
    "fields": [
      { "field": "workoutDate", "message": "Must be a valid ISO 8601 date." },
      { "field": "video1",      "message": "Video ID does not exist in this organization." }
    ]
  }
}

HTTP Status Codes

Situation Code
Success, resource returned 200
Success, resource created 201
Success, no body 204
Validation failed 400
Not authenticated (no/expired token) 401
Authenticated but not authorized (wrong role, wrong org) 403
Resource not found 404
Conflict (duplicate, constraint violation) 409
Insufficient storage (upload blocked) 507
Server error 500

Important: 404 is used when a resource doesn't exist OR when a user is not authorized to know it exists. Never return 403 for a resource that belongs to a different org — use 404. This prevents enumeration attacks.


Dates and Times

Storage

All DATETIME columns are stored as UTC in SQLite. Sequelize handles the conversion when type: DataTypes.DATE is used.

API Serialization

All date/time values in API responses and requests use ISO 8601 with UTC offset:

"scheduledDate": "2025-07-15T09:00:00.000Z"

Never return Unix timestamps (integers) — they are hard to read in logs and API explorers.

Timezone-Aware Queries

Each Organization has a timezone field (IANA timezone string, e.g., "America/New_York"). The "today's workouts" query must use this timezone, not the server's local time.

// Correct approach
const { DateTime } = require('luxon');
const org = await Organization.findByPk(req.user.organizationId);
const now = DateTime.now().setZone(org.timezone);
const todayStart = now.startOf('day').toUTC().toJSDate();
const todayEnd   = now.endOf('day').toUTC().toJSDate();

const workouts = await Workout.findAll({
  where: {
    organizationId: req.user.organizationId,
    workoutDate: { [Op.between]: [todayStart, todayEnd] }
  }
});

New dependency: luxon — timezone-aware date handling. More reliable than moment (deprecated) or raw Date manipulation.

Daylight Saving Time

Storing and querying in UTC avoids DST bugs entirely. The timezone field on Organization is only used at query-time to calculate the local "today" boundary. Events scheduled at 9:00 AM local time on a DST transition day will shift by 1 hour in UTC — this is correct and expected behavior for a gym schedule.


Pagination

All collection endpoints support pagination via query parameters:

GET /api/v1/workouts?page=2&limit=25
  • page — 1-indexed, default 1
  • limit — results per page, default 50, max 200

Response always includes meta (see collection shape above). Never omit meta for collections, even if all results fit on one page — clients rely on meta.total to know there are no more pages.


Error Codes (Catalog)

Defined upfront so frontend can handle specific errors without string-matching messages.

Auth

Code Meaning
AUTH_REQUIRED No token provided
AUTH_INVALID Token invalid or expired
AUTH_FORBIDDEN Valid token but insufficient role
AUTH_DEVICE_TOKEN_INVALID Device token not found, expired, or revoked
LOGIN_FAILED Bad username or password

Validation

Code Meaning
VALIDATION_FAILED One or more fields failed validation (see fields array)

Resources

Code Meaning
NOT_FOUND Resource does not exist (or you are not authorized to see it)
CONFLICT Duplicate value or constraint violation
UPLOAD_TYPE_INVALID File MIME type is not allowed
UPLOAD_SIZE_EXCEEDED File exceeds configured max size
STORAGE_INSUFFICIENT Server disk space too low to accept upload

Organization / Access

Code Meaning
FEATURE_DISABLED Org does not have this feature enabled
LAST_OWNER_PROTECTED Cannot deactivate or demote the last Owner in the org
CANCELLATION_TOO_LATE Client attempting to cancel a session starting in < 24 hours

Request Body Content Type

All request bodies use application/json except file uploads, which use multipart/form-data.

The server rejects application/x-www-form-urlencoded with a 400. Do not support it — it reduces attack surface.


OpenAPI

An OpenAPI 3.0 document (openapi.yaml) will be generated from the routes as V2 is built and committed to the repo. It is not required before implementation starts, but each module's routes should be documented in it as they are written.

The document is served at /api/v1/openapi.yaml (public, no auth). This allows easy API exploration during development and serves as integration documentation for the future iOS app.


Naming Conventions

Type Convention Example
Route paths kebab-case, plural nouns /api/v1/crossfit-workouts
JSON keys camelCase workoutDate, fileSizeBytes
Query params camelCase ?page=1&orgId=3
Error codes SCREAMING_SNAKE_CASE UPLOAD_TYPE_INVALID
Enum values in responses PascalCase "status": "Scheduled"