Overview
This endpoint returns the user’s historical workout data, including all completed training sessions with details about exercises, duration, calories burned, and achievements unlocked.
This endpoint requires JWT authentication to ensure users can only access their own workout history.
Endpoint
GET /api/entrenamientos/historial/:userId
Authentication
Bearer token for JWT authentication Authorization: Bearer <your_jwt_token>
Path Parameters
The MongoDB ObjectId of the user whose history to retrieve. Must match the authenticated user’s ID.
Query Parameters
Maximum number of workout records to return. Results are sorted by date (most recent first).
Response
Indicates if the request was successful
Workout history data Show Data Object Properties
Array of completed workout sessions, sorted by date (newest first) Show Workout Object Properties
ISO 8601 timestamp of when the workout was completed
Name of the workout session Example: “Entrenamiento Pecho y Tríceps”
Focus or target muscle groups for the workout Examples: “Full body”, “Piernas y glúteos”, “Espalda y bíceps”
Total duration of the workout in minutes
Estimated calories burned during the session
Number of exercises completed in this session
Detailed list of exercises performed Show Exercise Object Properties
Repetitions per set or duration
Total number of workouts in the user’s complete history (not limited by the limit parameter)
Code Examples
const userId = '507f1f77bcf86cd799439011' ;
const response = await fetch (
`https://api.fitaiid.com/api/entrenamientos/historial/ ${ userId } ?limit=10` ,
{
method: 'GET' ,
headers: {
'Content-Type' : 'application/json' ,
'Authorization' : `Bearer ${ jwtToken } `
}
}
);
const data = await response . json ();
console . log ( `Total workouts: ${ data . data . total } ` );
console . log ( `Recent workouts:` , data . data . workouts );
Response Example
{
"success" : true ,
"data" : {
"workouts" : [
{
"date" : "2024-03-06T10:30:00.000Z" ,
"nombre" : "Entrenamiento Piernas" ,
"enfoque" : "Piernas y glúteos" ,
"duracionTotal" : 60 ,
"caloriasEstimadas" : 450 ,
"ejerciciosCompletados" : 5 ,
"ejercicios" : [
{
"nombre" : "Sentadillas" ,
"series" : 4 ,
"repeticiones" : "12-15" ,
"descanso" : "60 segundos"
},
{
"nombre" : "Peso muerto rumano" ,
"series" : 3 ,
"repeticiones" : "12-15" ,
"descanso" : "60 segundos"
},
{
"nombre" : "Prensa de piernas" ,
"series" : 3 ,
"repeticiones" : "15-20" ,
"descanso" : "45 segundos"
},
{
"nombre" : "Zancadas" ,
"series" : 3 ,
"repeticiones" : "10-12 por pierna" ,
"descanso" : "45 segundos"
},
{
"nombre" : "Elevaciones de pantorrilla" ,
"series" : 4 ,
"repeticiones" : "15-20" ,
"descanso" : "30 segundos"
}
]
},
{
"date" : "2024-03-04T09:15:00.000Z" ,
"nombre" : "Entrenamiento Pecho y Tríceps" ,
"enfoque" : "Pecho, hombros y tríceps" ,
"duracionTotal" : 55 ,
"caloriasEstimadas" : 380 ,
"ejerciciosCompletados" : 4 ,
"ejercicios" : [
{
"nombre" : "Press de banca" ,
"series" : 4 ,
"repeticiones" : "10-12" ,
"descanso" : "90 segundos"
},
{
"nombre" : "Press inclinado con mancuernas" ,
"series" : 3 ,
"repeticiones" : "12-15" ,
"descanso" : "60 segundos"
},
{
"nombre" : "Fondos en paralelas" ,
"series" : 3 ,
"repeticiones" : "10-12" ,
"descanso" : "60 segundos"
},
{
"nombre" : "Extensiones de tríceps" ,
"series" : 3 ,
"repeticiones" : "12-15" ,
"descanso" : "45 segundos"
}
]
}
],
"total" : 47
}
}
Error Responses
User attempting to access another user’s history {
"success" : false ,
"message" : "No autorizado para acceder a estos datos"
}
User not found {
"success" : false ,
"message" : "Usuario no encontrado"
}
Implementation Details
Data Storage
Workout history is stored in the User model under fitnessStats.workoutHistory. Each workout entry is automatically created when:
User completes a day via /api/rutina/:userId/completar-dia
User registers a workout via /api/entrenamientos/registrar
When workouts are registered, the system also updates:
Total Workouts fitnessStats.totalWorkouts - Lifetime count
Total Minutes fitnessStats.totalMinutes - Cumulative training time
Current Streak fitnessStats.currentStreak - Consecutive workout days
Max Streak fitnessStats.maxStreak - Best streak achieved
Workout Progress Tracking
Each completed workout also creates a WorkoutProgress document:
{
user : ObjectId , // Reference to User
duration : Number , // Minutes
calories : Number , // Estimated burn
createdAt : Date // Completion timestamp
}
This separate collection enables efficient analytics queries without loading full User documents.
Achievement System
Workout history triggers automatic achievement unlocking based on milestones:
First Workout
Primera Rutina 🎯 - Complete your first training session
7-Day Streak
Racha de 7 días 🔥 - Train for 7 consecutive days
10 Workouts
Dedicación 💪 - Complete 10 total workouts
50 Workouts
Guerrero 👑 - Complete 50 total workouts
Achievements are stored in fitnessStats.achievements array with achievementId and unlockedAt timestamp.
The limit parameter controls how many workouts are returned. For optimal performance:
Default : 20 workouts
Recommended for mobile : 10-15 workouts
Maximum suggested : 50 workouts
For “infinite scroll” functionality, track the date of the last workout returned and query with date filters (custom implementation needed).
Use Cases
Progress Visualization Display workout frequency and consistency over time
Exercise Analytics Analyze which muscle groups are trained most often
Calorie Tracking Calculate total calories burned over periods
Motivation Features Show streak history and achievement progress
Generate Routine Generate a new AI-powered workout routine
Get Progress View current routine progress
User Statistics Get detailed workout statistics
Best Practices
Security : Always validate that req.user._id matches the requested userId to prevent unauthorized access to workout data.
Performance : Use the limit parameter appropriately. Fetching hundreds of workouts can slow down mobile devices.
Data Consistency : The total field always reflects the complete workout count, even if limit restricts the returned workouts array.