Skip to main content

Overview

The Categories API provides endpoints for managing product categories, including CRUD operations and active category filtering. Base URL: /api/categorias Source: CategoriaController.java

Authentication

  • Public endpoints: GET requests (list, view)
  • Admin endpoints: POST, PUT, DELETE operations (no explicit @PreAuthorize in source, but should be admin-only in production)

Endpoints

List All Categories

GET /api/categorias
Retrieve all categories (including inactive categories). Authentication: None (public endpoint) Response: 200 OK - Array of category objects
categories
array
Example Request:
curl -X GET http://localhost:8080/api/categorias

List Active Categories

GET /api/categorias/activos
Retrieve only active categories (where activo = true). Authentication: None (public endpoint) Response: 200 OK - Array of active category objects Example Request:
cURL
curl -X GET http://localhost:8080/api/categorias/activos
Use this endpoint for public-facing category navigation to hide inactive/archived categories from customers.

Get Category by ID

GET /api/categorias/{id}
Retrieve a specific category by ID. Authentication: None (public endpoint)
id
long
required
Category ID
Responses:
  • 200 OK - Category object
  • 404 Not Found - Category does not exist
Example Request:
cURL
curl -X GET http://localhost:8080/api/categorias/1

Create Category

POST /api/categorias
Create a new product category. Authentication: Should require ROLE_ADMIN (not explicitly enforced in source) Request Body:
nombre
string
required
Category name
descripcion
string
Category description
activo
boolean
Active status (default: true)
Response: 200 OK - Created category object with generated ID Example Request:
cURL
curl -X POST http://localhost:8080/api/categorias \
  -H "Authorization: Bearer ADMIN_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "nombre": "Laptops",
    "descripcion": "Portable computers and notebooks",
    "activo": true
  }'
Example Response:
{
  "id": 5,
  "nombre": "Laptops",
  "descripcion": "Portable computers and notebooks",
  "activo": true
}

Update Category

PUT /api/categorias/{id}
Update an existing category. Authentication: Should require ROLE_ADMIN
id
long
required
Category ID to update
Request Body: Category object with updated fields Responses:
  • 200 OK - Updated category object
  • 404 Not Found - Category does not exist
Example Request:
cURL
curl -X PUT http://localhost:8080/api/categorias/5 \
  -H "Authorization: Bearer ADMIN_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "nombre": "Premium Laptops",
    "descripcion": "High-end portable computers",
    "activo": true
  }'

Delete Category

DELETE /api/categorias/{id}
Delete a category. Authentication: Should require ROLE_ADMIN
id
long
required
Category ID to delete
Responses:
  • 200 OK - Category successfully deleted
  • 400 Bad Request - Cannot delete (may have associated products)
Example Request:
cURL
curl -X DELETE http://localhost:8080/api/categorias/5 \
  -H "Authorization: Bearer ADMIN_JWT_TOKEN"
Deleting a category may fail if products are still associated with it. Consider implementing a soft delete (setting activo = false) instead of hard deletion.

Category Model

The complete category object structure:
{
  "id": 1,
  "nombre": "Electronics",
  "descripcion": "Electronic devices and accessories",
  "activo": true
}

Integration Examples

Frontend: Display Category Navigation

JavaScript
async function loadCategoryMenu() {
  const response = await fetch('http://localhost:8080/api/categorias/activos');
  const categories = await response.json();
  
  const menuHTML = categories.map(cat => 
    `<a href="/products?category=${cat.id}">${cat.nombre}</a>`
  ).join('');
  
  document.getElementById('category-menu').innerHTML = menuHTML;
}

Admin: Create New Category

JavaScript
async function createCategory(categoryData, token) {
  const response = await fetch('http://localhost:8080/api/categorias', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(categoryData)
  });
  
  return response.json();
}

// Usage
await createCategory({
  nombre: 'Smartphones',
  descripcion: 'Mobile phones and accessories',
  activo: true
}, adminToken);

Filter Products by Category

JavaScript
async function getProductsByCategory(categoryId) {
  const response = await fetch(`http://localhost:8080/api/productos/categoria/${categoryId}`);
  return response.json();
}

// Usage: Get all products in "Laptops" category
const laptops = await getProductsByCategory(1);

Use Cases

Navigation Menu

Use /activos endpoint to populate the category navigation menu on the storefront.

Product Filtering

Combine with Products API to filter products by category.

Admin Management

Create, update, and organize product categories from the admin panel.

Inventory Organization

Organize products into logical groups for easier inventory management.

Best Practices

Instead of permanently deleting categories, toggle the activo flag to false. This preserves data integrity and allows you to restore categories later.
Before deleting a category, verify that no products are assigned to it. Implement cascade rules or reassign products to a different category.
Consider adding a slug field (similar to products) for SEO-friendly category URLs like /categories/electronics instead of /categories/1.

Error Responses

Status CodeDescription
400 Bad RequestCannot delete category with associated products
401 UnauthorizedMissing or invalid JWT token
403 ForbiddenUser does not have admin role
404 Not FoundCategory does not exist
500 Internal Server ErrorServer error

Products API

Manage products within categories

Products by Category

Filter products by category ID

Build docs developers (and LLMs) love