Skip to main content

Overview

This endpoint generates a personalized weekly workout routine using OpenAI’s GPT-4o-mini model. The routine is tailored to the user’s fitness level, goals, training location, and available days per week.
This endpoint requires JWT authentication and can only generate routines for the authenticated user.

Endpoint

POST /api/generar-rutina

Authentication

Authorization
string
required
Bearer token for JWT authentication
Authorization: Bearer <your_jwt_token>

Request Body

userId
string
required
The ID of the user for whom to generate the routine. Must match the authenticated user’s ID.
profile
object
Optional fitness profile object. If not provided, the system will fetch the user’s saved profile from the database.

Response

success
boolean
Indicates if the routine was generated successfully
message
string
Success message
rutina
object
The generated workout routine

AI Integration

This endpoint uses OpenAI GPT-4o-mini to generate personalized routines based on:
  • Goal-specific training: Different approaches for toning, muscle gain, or weight loss
  • Progressive muscle group targeting: Ensures variety and proper muscle recovery
  • Location-appropriate exercises: Adapts exercises for home or gym equipment
  • Fallback mechanism: Provides pre-built routines if AI service is unavailable

Routine Generation Rules

Tonificar (Toning)

  • Each day targets different muscle groups
  • 12-15 repetitions per exercise
  • Short rest periods
  • Light cardio as complement

Ganar Masa Muscular (Muscle Gain)

  • 8-12 repetitions per exercise
  • 60-90 second rest periods
  • Compound exercises emphasized
  • Minimal intense cardio

Bajar de Peso (Weight Loss)

  • Circuit or full-body workouts
  • Daily cardio included
  • Short rest periods
  • High caloric expenditure focus

Code Examples

const response = await fetch('https://api.fitaiid.com/api/generar-rutina', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${jwtToken}`
  },
  body: JSON.stringify({
    userId: '507f1f77bcf86cd799439011',
    profile: {
      mainGoal: 'tonificar',
      fitnessLevel: 'intermedio',
      trainingDaysPerWeek: 4,
      trainingLocation: 'gimnasio',
      sessionDuration: '60 min',
      medicalConditions: 'ninguna'
    }
  })
});

const data = await response.json();
console.log(data.rutina);

Response Example

{
  "success": true,
  "message": "Rutina generada exitosamente",
  "rutina": {
    "nombreRutina": "Rutina de Tonificación 4 días",
    "descripcion": "Rutina diseñada para tonificar y definir músculos, trabajando diferentes grupos musculares cada día.",
    "dias": [
      {
        "nombre": "Lunes",
        "esDescanso": false,
        "enfoque": "Pecho, hombros y tríceps",
        "duracionTotal": 60,
        "caloriasEstimadas": 350,
        "ejercicios": [
          {
            "nombre": "Press de banca",
            "series": 3,
            "repeticiones": "12-15",
            "descanso": "45 segundos"
          },
          {
            "nombre": "Elevaciones laterales",
            "series": 3,
            "repeticiones": "12-15",
            "descanso": "45 segundos"
          },
          {
            "nombre": "Fondos en paralelas",
            "series": 3,
            "repeticiones": "10-12",
            "descanso": "60 segundos"
          }
        ]
      },
      {
        "nombre": "Martes",
        "esDescanso": true
      },
      {
        "nombre": "Miércoles",
        "esDescanso": false,
        "enfoque": "Piernas y glúteos",
        "duracionTotal": 60,
        "caloriasEstimadas": 400,
        "ejercicios": [
          {
            "nombre": "Sentadillas",
            "series": 4,
            "repeticiones": "12-15",
            "descanso": "60 segundos"
          },
          {
            "nombre": "Peso muerto rumano",
            "series": 3,
            "repeticiones": "12-15",
            "descanso": "60 segundos"
          }
        ]
      }
    ]
  }
}

Error Responses

400 Bad Request
object
Missing required userId parameter
{
  "success": false,
  "message": "userId requerido"
}
403 Forbidden
object
Attempting to generate routine for a different user
{
  "success": false,
  "message": "No autorizado para generar rutina para otro usuario"
}
503 Service Unavailable
object
OpenAI API quota exceeded (fallback routine will still be generated)
{
  "success": false,
  "error": "⚠️ El servicio de IA está temporalmente no disponible.",
  "details": "Se ha excedido la cuota de la API de OpenAI..."
}

Implementation Notes

The routine is automatically saved to the user’s currentRoutine field and added to their routineHistory for future reference.
The system enforces that users can only generate routines for themselves by validating the JWT token against the requested userId.

Get Progress

Track user’s progress through their routine

Workout History

View completed workout history

Build docs developers (and LLMs) love