Skip to main content

Quick Start Guide

This guide will help you install, configure, and make your first API request to MaqAgr.

Prerequisites

Before you begin, ensure you have the following installed:

Node.js

v24.13.0 or higherJavaScript runtime

PostgreSQL

v12 or higherRelational database

npm/pnpm

Latest versionPackage manager

Installation

1

Clone the repository

Clone the MaqAgr backend repository to your local machine:
git clone https://github.com/David9604/BackMaqagr.git
cd BackMaqagr
2

Install dependencies

Install all required Node.js packages:
npm install
The project uses ES modules ("type": "module" in package.json), so all imports use ES6 syntax.
3

Configure environment variables

Create a .env file in the root directory with your configuration:
cp .env.example .env
# Edit .env with your database credentials and JWT secret
If .env.example doesn’t exist, create a .env file manually with the variables shown below.
Required environment variables:
.env
# Server Configuration
PORT=4000
NODE_ENV=development

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=MaqAgr
DB_USER=postgres
DB_PASS=your_postgres_password

# JWT Configuration
JWT_SECRET=your_super_secret_key_here
JWT_EXPIRES_IN=24h
Never commit your .env file to version control. Always use a strong, unique JWT_SECRET in production.
4

Set up the database

Create the PostgreSQL database and import the schema:
# Create database
createdb MaqAgr

# Import schema files
psql -d MaqAgr -f docs/dbSetting/users_202601311817.sql
psql -d MaqAgr -f docs/dbSetting/tractor_202601311817.sql
psql -d MaqAgr -f docs/dbSetting/implement_202601311817.sql
psql -d MaqAgr -f docs/dbSetting/terrain_202601311817.sql
psql -d MaqAgr -f database/indexes.sql
The schema files create all necessary tables, relationships, and indexes for the API.
5

Start the server

Run the development server:
npm run dev  # Development mode with nodemon
# OR
npm start    # Production mode
You should see output similar to:
🚜 Servidor corriendo en puerto 4000
📡 Ambiente: development
The API is now running at http://localhost:4000

Your First API Request

Let’s walk through a complete authentication flow and make your first authenticated request.
1

Register a new user

Create a new user account by sending a POST request to /api/auth/register:
cURL
curl -X POST http://localhost:4000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Juan Pérez",
    "email": "[email protected]",
    "password": "SecurePass123!"
  }'
const response = await fetch('http://localhost:4000/api/auth/register', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Juan Pérez',
    email: '[email protected]',
    password: 'SecurePass123!'
  })
});

const data = await response.json();
console.log(data);
Password requirements:
  • Minimum 8 characters
  • At least one uppercase letter
  • At least one number
  • At least one special character
Response (201 Created):
{
  "success": true,
  "message": "Usuario registrado exitosamente",
  "data": {
    "user": {
      "user_id": 1,
      "name": "Juan Pérez",
      "email": "[email protected]",
      "role_id": 2,
      "status": "active",
      "registration_date": "2026-03-11T10:00:00.000Z"
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}
New users are assigned role_id: 2 (regular user) by default. The response includes a JWT token valid for 24 hours.
2

Save your token

Copy the token value from the registration response. You’ll need this for authenticated requests.The token payload contains:
{
  "user_id": 1,
  "email": "[email protected]",
  "role_id": 2,
  "name": "Juan Pérez",
  "iat": 1710151200,
  "exp": 1710237600
}
Store tokens securely. Never expose them in client-side code or logs. Tokens expire after 24 hours.
3

Make an authenticated request

Use your token to access a protected endpoint. Let’s fetch your user profile:
cURL
curl -X GET http://localhost:4000/api/auth/profile \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';

const response = await fetch('http://localhost:4000/api/auth/profile', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

const profile = await response.json();
console.log(profile);
Response (200 OK):
{
  "success": true,
  "message": "Perfil obtenido exitosamente",
  "data": {
    "user": {
      "user_id": 1,
      "name": "Juan Pérez",
      "email": "[email protected]",
      "role_id": 2,
      "role_name": "Usuario",
      "status": "active",
      "registration_date": "2026-03-11T10:00:00.000Z",
      "last_session": "2026-03-11T10:05:00.000Z"
    }
  }
}
4

Explore other endpoints

Now that you’re authenticated, you can access other API endpoints. Let’s list available tractors:
cURL
curl -X GET http://localhost:4000/api/tractors \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
Response (200 OK):
{
  "success": true,
  "message": "Tractores obtenidos exitosamente",
  "data": [
    {
      "tractor_id": 1,
      "name": "John Deere 5075E",
      "power": 75,
      "weight": 3200,
      "brand": "John Deere",
      "model": "5075E"
    }
  ]
}

Common Errors

Here are some common errors you might encounter and how to resolve them:

Missing or Invalid Token

{
  "success": false,
  "message": "Token no proporcionado"
}
Solution: Include the Authorization: Bearer <token> header in your request.

Expired Token

{
  "success": false,
  "message": "Token inválido o expirado"
}
Solution: Tokens expire after 24 hours. Log in again to get a new token.

Validation Error

{
  "success": false,
  "message": "Contraseña no cumple requisitos",
  "errors": [
    "Debe tener al menos 8 caracteres",
    "Debe incluir una mayúscula"
  ]
}
Solution: Check the errors array for specific validation requirements.

Email Already Registered

{
  "success": false,
  "message": "El email ya está registrado"
}
Solution: Use a different email address or log in with the existing account.

Testing the API

The project includes comprehensive tests:
# Run all tests (97+ unit + E2E tests)
npm test

# Run tests with coverage report
npm run test:coverage

# Run tests in watch mode (development)
npm run test:watch

# Run only E2E tests
npm run test:e2e

# Run only unit tests
npm run test:unit

Swagger Documentation

The API includes interactive Swagger documentation. Once the server is running, visit:
http://localhost:4000/api-docs
Swagger UI allows you to:
  • Explore all endpoints interactively
  • View request/response schemas
  • Test endpoints directly from your browser
  • See detailed parameter descriptions

Health Check

Verify the API is running correctly:
curl http://localhost:4000/health
You should receive a health status response indicating the API and database connection status.

Next Steps

Authentication Deep Dive

Learn more about JWT authentication, token structure, and security

API Reference

Explore all available endpoints and their parameters

Calculations

Learn how to perform power calculations and get recommendations

Error Handling

Understand error responses and how to handle them

Build docs developers (and LLMs) love