# Listas de valores (API)

> Las operaciones de Listas de valores (API) de la API de Trevol: parámetros, cuerpo, respuestas y ejemplos de código.

Fuente: https://platform.trevol.si/docs/api/catalogs

Los códigos que acepta cada campo de un pedido (municipios, unidades, tributos, medios de pago…), de las mismas tablas con que Trevol valida. Cualquier llave; cacheables con `ETag` e `If-None-Match`.

Los ejemplos de código salen de los SDK reales. La llave va en `TREVOL_API_KEY`; los cuerpos de ejemplo son los de la especificación. Los errores comunes están en [Errores](/docs/errores).

## Las listas de valores

`GET /v1/catalogs` · `listCatalogs`

Las listas de valores: los códigos que acepta cada campo de un pedido (municipios, unidades, tributos, medios de pago…), con dónde se usa cada lista, qué filtros admite, cuántas entradas tiene y `content_hash`, que cambia si cambia su contenido. Salen de las mismas tablas con que Trevol valida los pedidos. Cualquier llave; cuenta como lectura. La respuesta lleva `ETag`: mándalo en `If-None-Match` y, si nada cambió, la respuesta es 304 sin cuerpo.

**Respuestas**

| Estado | Qué pasó |
| --- | --- |
| 200 | {object: list, data, has_more, next_cursor} (objeto) |
| 304 | No cambió: el `ETag` de `If-None-Match` es el de la respuesta de hoy. Sin cuerpo. |
| 422 | Error (application/problem+json) ([Problem](/docs/api/objetos#Problem)) |
| Error | Error (application/problem+json) ([Problem](/docs/api/objetos#Problem)) |

`GET /v1/catalogs` (`listCatalogs`)

#### cURL

```bash
curl "https://api.trevol.si/v1/catalogs" \
  -H "Authorization: Bearer $TREVOL_API_KEY"
```

#### Node.js

```javascript
import { Trevol } from '@trevol/sdk';

const trevol = new Trevol(); // lee TREVOL_API_KEY

const lista = await trevol.catalogs.listCatalogs();
for (const item of lista.data ?? []) {
  console.log(item.name);
}
```

#### Python

```python
from trevol import Trevol

trevol = Trevol()  # lee TREVOL_API_KEY

lista = trevol.catalogs.list_catalogs()
for item in lista.data or []:
    print(item.name)
```

#### PHP

```php
<?php

use Trevol\Trevol;

require __DIR__ . '/vendor/autoload.php';

$trevol = new Trevol(getenv('TREVOL_API_KEY')); // tvl_test_… → $trevol->environment === 'test'

$lista = $trevol->catalogs->listCatalogs();
foreach ($lista->getData() as $item) {
    echo $item->getName(), PHP_EOL;
}

```

#### Java

```java
import si.trevol.Trevol;

public class Ejemplo {
    public static void main(String[] args) throws Exception {
        Trevol trevol = Trevol.builder().apiKey(System.getenv("TREVOL_API_KEY")).build(); // tvl_test_… → trevol.environment() == TEST

        var lista = trevol.catalogs().listCatalogs().execute();
        for (var item : lista.getData()) {
            System.out.println(item.getName());
        }
    }
}

```

#### C#

```csharp
using System;
using System.Threading.Tasks;
using Trevol;

public static class Ejemplo
{
    public static async Task Main()
    {
        var trevol = new TrevolClient(Environment.GetEnvironmentVariable("TREVOL_API_KEY")); // tvl_test_… → trevol.Environment == TrevolEnvironment.Test

        var lista = await trevol.Catalogs.ListCatalogsAsync();
        foreach (var item in lista.Data)
        {
            Console.WriteLine(item.Name);
        }
    }
}

```

#### Go

```go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	trevol "github.com/trevol-si/trevol-go"
)

func main() {
	ctx := context.Background()
	c, err := trevol.NewClient(os.Getenv("TREVOL_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	lista, _, err := c.CatalogsAPI.ListCatalogs(ctx).Execute()
	if err != nil {
		log.Fatal(err)
	}
	for _, item := range lista.GetData() {
		fmt.Println(item.GetName())
	}
}

```

#### Ruby

```ruby
require 'trevol'

trevol = Trevol::Client.new # lee TREVOL_API_KEY

lista = trevol.catalogs.list_catalogs
lista.data.each { |item| puts item.name }

```

#### Respuesta 200

```json
{
  "object": "list",
  "has_more": false,
  "next_cursor": null,
  "data": [
    {
      "object": "catalog",
      "id": "departments",
      "name": "Departamentos",
      "description": "Los departamentos de Colombia con su código DANE (2 dígitos).",
      "source": "DIAN, Anexo técnico 1.9, tabla 13.4.2 (DANE)",
      "used_in": [
        "customer.department_code",
        "seller.department_code",
        "employee.workplace.department_code",
        "generation_place.department_code"
      ],
      "filters": [
        "code",
        "q"
      ],
      "count": 33,
      "content_hash": "e427ef5ef26f7c45"
    },
    {
      "object": "catalog",
      "id": "municipalities",
      "name": "Municipios",
      "description": "Los municipios de Colombia con su código DANE (5 dígitos: los dos primeros son el departamento).",
      "source": "DIAN, Anexo técnico 1.9, tabla 13.4.3 (DANE)",
      "used_in": [
        "customer.municipality_code",
        "shipment.address.municipality_code",
        "shipment.carrier.address.municipality_code",
        "seller.municipality_code",
        "employee.workplace.municipality_code",
        "generation_place.municipality_code",
        "municipality_code (customers)"
      ],
      "filters": [
        "code",
        "q",
        "department_code"
      ],
      "count": 1122,
      "content_hash": "57ec750600b8135e"
    },
    {
      "object": "catalog",
      "id": "units",
      "name": "Unidades de medida",
      "description": "Las unidades de medida de las líneas, de los tributos por unidad y de los productos. El documento soporte tiene su propia tabla (suma MGM y no tiene MG ni MHZ): mira `resources`. Los nombres son los que publica la DIAN, tal cual.",
      "source": "DIAN, Anexo técnico 1.9, tabla 13.3.6, y documento soporte, tabla 16.3.5.1",
      "used_in": [
        "items[].unit",
        "items[].taxes[].unit",
        "unit (products)"
      ],
      "filters": [
        "code",
        "q",
        "resource"
      ],
      "count": 1081,
      "content_hash": "295f863c2e29fde8"
    }
  ]
}
```

[Probar en el Playground](https://platform.trevol.si/playground?op=listCatalogs)

## Las entradas de una lista de valores

`GET /v1/catalogs/{name}` · `listCatalogEntries`

Las entradas de una lista (`name`: departments, municipalities, postal_codes, countries, currencies, units, taxes, payment_means, payment_forms, credit_note_concepts, debit_note_concepts, support_document_adjustment_concepts, equivalent_document_adjustment_concepts, identity_document_types, tax_responsibilities, tax_schemes, document_types, operation_types, incoterms, discount_charge_codes, reference_price_types, product_code_schemes, payroll_worker_types, payroll_worker_subtypes, payroll_contract_types, payroll_periods, payroll_disability_types, payroll_overtime_types, radian_claim_concepts), en su orden, con cursor (`starting_after` es el `code` de la última entrada que ya tienes) y `limit` de 1 a 1000 (1000 por defecto). Filtros: `q` (busca en el código y en el nombre, sin tildes ni mayúsculas), `code` (hasta 100 códigos separados por coma) y, según la lista, `department_code` (municipios) o `resource` (solo las entradas que valen en ese recurso). Cualquier llave; cuenta como lectura. La respuesta lleva `ETag`: mándalo en `If-None-Match` y, si nada cambió, la respuesta es 304 sin cuerpo.

**Parámetros**

| Nombre | En | Tipo | Obligatorio | Descripción |
| --- | --- | --- | --- | --- |
| `name` | ruta | texto | sí | El nombre de la lista (`id` en `GET /v1/catalogs`): municipalities, units, taxes, payment_means… |
| `limit` | consulta | entero |  |  |
| `starting_after` | consulta | texto |  | El `code` de la última entrada que ya tienes. |
| `q` | consulta | texto |  | Busca en el código y en el nombre, sin tildes ni mayúsculas y sin contar los puntos (`q=0.5` busca «05»). El largo se mide después de quitar los puntos y los espacios de más: «a.» o « a» tienen una letra (422). |
| `code` | consulta | texto |  | Hasta 100 códigos separados por coma. |
| `department_code` | consulta | texto |  | Solo en `municipalities` y `postal_codes`: las entradas de ese departamento. |
| `resource` | consulta | `invoices` \| `credit_notes` \| `debit_notes` \| `support_documents` \| `support_document_adjustments` \| `equivalent_documents` \| `equivalent_document_adjustments` \| `payrolls` \| `payroll_adjustments` \| `customers` \| `products` |  | Solo en las listas con `resources`: las entradas que valen en ese recurso. Cada lista admite solo los recursos que aparecen en sus entradas (por ejemplo, `units` no tiene `customers`); otro, 422. |

**Respuestas**

| Estado | Qué pasó |
| --- | --- |
| 200 | {object: list, data, has_more, next_cursor} (objeto) |
| 304 | No cambió: el `ETag` de `If-None-Match` es el de la respuesta de hoy. Sin cuerpo. |
| 404 | Error (application/problem+json) ([Problem](/docs/api/objetos#Problem)) |
| 422 | Error (application/problem+json) ([Problem](/docs/api/objetos#Problem)) |
| Error | Error (application/problem+json) ([Problem](/docs/api/objetos#Problem)) |

`GET /v1/catalogs/{name}` (`listCatalogEntries`)

#### cURL

```bash
curl "https://api.trevol.si/v1/catalogs/municipalities?limit=100" \
  -H "Authorization: Bearer $TREVOL_API_KEY"
```

#### Node.js

```javascript
import { Trevol } from '@trevol/sdk';

const trevol = new Trevol(); // lee TREVOL_API_KEY

for await (const item of trevol.paginate((cursor) => trevol.catalogs.listCatalogEntries({ name: 'municipalities', limit: 100, startingAfter: cursor }))) {
  console.log(item.code);
}
```

#### Python

```python
from trevol import Trevol

trevol = Trevol()  # lee TREVOL_API_KEY

for item in trevol.paginate(lambda cursor: trevol.catalogs.list_catalog_entries(name="municipalities", limit=100, starting_after=cursor)):
    print(item.code)
```

#### PHP

```php
<?php

use Trevol\Trevol;

require __DIR__ . '/vendor/autoload.php';

$trevol = new Trevol(getenv('TREVOL_API_KEY')); // tvl_test_… → $trevol->environment === 'test'

foreach ($trevol->paginate(fn (?string $cursor) => $trevol->catalogs->listCatalogEntries(name: 'municipalities', limit: 100, starting_after: $cursor)) as $item) {
    echo $item->getCode(), PHP_EOL;
}

```

#### Java

```java
import si.trevol.Trevol;
import si.trevol.generado.model.CodeListEntryList;

public class Ejemplo {
    public static void main(String[] args) throws Exception {
        Trevol trevol = Trevol.builder().apiKey(System.getenv("TREVOL_API_KEY")).build(); // tvl_test_… → trevol.environment() == TEST

        for (var item : trevol.paginate(
                cursor -> trevol.catalogs().listCatalogEntries("municipalities").limit(100).startingAfter(cursor).execute(),
                CodeListEntryList::getData)) {
            System.out.println(item.getCode());
        }
    }
}

```

#### C#

```csharp
using System;
using System.Threading.Tasks;
using Trevol;

public static class Ejemplo
{
    public static async Task Main()
    {
        var trevol = new TrevolClient(Environment.GetEnvironmentVariable("TREVOL_API_KEY")); // tvl_test_… → trevol.Environment == TrevolEnvironment.Test

        await foreach (var item in trevol.PaginateAsync(cursor => trevol.Catalogs.ListCatalogEntriesAsync(name: "municipalities", limit: 100, startingAfter: cursor)))
        {
            Console.WriteLine(item.Code);
        }
    }
}

```

#### Go

```go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	trevol "github.com/trevol-si/trevol-go"
	"github.com/trevol-si/trevol-go/generado"
)

func main() {
	ctx := context.Background()
	c, err := trevol.NewClient(os.Getenv("TREVOL_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	for item, err := range trevol.Paginate(ctx, func(cursor *string) (*generado.CodeListEntryList, error) {
		r := c.CatalogsAPI.ListCatalogEntries(ctx, "municipalities").Limit(100)
		if cursor != nil {
			r = r.StartingAfter(*cursor)
		}
		l, _, err := r.Execute()
		return l, err
	}) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(item.GetCode())
	}
}

```

#### Ruby

```ruby
require 'trevol'

trevol = Trevol::Client.new # lee TREVOL_API_KEY

trevol.paginate { |cursor| trevol.catalogs.list_catalog_entries('municipalities', limit: 100, starting_after: cursor) }.each do |item|
  puts item.code
end

```

#### Respuesta 200

```json
{
  "object": "list",
  "data": [
    {
      "object": "catalog_entry",
      "code": "05001",
      "name": "MEDELLÍN",
      "department_code": "05",
      "department_name": "Antioquia"
    },
    {
      "object": "catalog_entry",
      "code": "05002",
      "name": "ABEJORRAL",
      "department_code": "05",
      "department_name": "Antioquia"
    },
    {
      "object": "catalog_entry",
      "code": "05004",
      "name": "ABRIAQUÍ",
      "department_code": "05",
      "department_name": "Antioquia"
    }
  ],
  "has_more": true,
  "next_cursor": "05004"
}
```

[Probar en el Playground](https://platform.trevol.si/playground?op=listCatalogEntries)
