Segmentos
Gerenciamento de segmentos de usuários para targeting de feature flags.
Endpoints
| Método | Endpoint | Descrição | Permissão |
|---|---|---|---|
| POST | /api/v1/segments | Criar segmento | SEGMENTS_CREATE |
| GET | /api/v1/segments | Listar segmentos | SEGMENTS_READ |
| GET | /api/v1/segments/:id | Obter segmento | SEGMENTS_READ |
| PATCH | /api/v1/segments/:id | Atualizar segmento | SEGMENTS_UPDATE |
| DELETE | /api/v1/segments/:id | Excluir segmento | SEGMENTS_DELETE |
Atributos
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
key | string | Sim | Identificador único (alfanumerico, hifens, underscores) |
name | string | Sim | Nome de exibicao (max 200 caracteres) |
description | string | Não | Descrição (max 1000 caracteres) |
ruleType | enum | Não | Tipo de regra: SIMPLE ou DMN (default: SIMPLE) |
ruleContent | string | Não | Conteudo da regra (JSON para SIMPLE, XML para DMN) |
decisionId | string (UUID) | Não | ID de uma decisão do Decision Engine (para DMN) |
Criar Segmento
POST /api/v1/segments
Cria um novo segmento de usuários.
Request - Segmento SIMPLE
- cURL
- JavaScript
curl -X POST 'https://feature-flags.stg.catalisa.app/api/v1/segments' \
-H 'Authorization: Bearer SEU_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"key": "premium-users",
"name": "Premium Users",
"description": "Usuários com plano premium",
"ruleType": "SIMPLE",
"ruleContent": "{\"operator\":\"AND\",\"conditions\":[{\"attribute\":\"plan\",\"operator\":\"eq\",\"value\":\"premium\"}]}"
}'
const response = await fetch('https://feature-flags.stg.catalisa.app/api/v1/segments', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'premium-users',
name: 'Premium Users',
description: 'Usuários com plano premium',
ruleType: 'SIMPLE',
ruleContent: JSON.stringify({
operator: 'AND',
conditions: [
{ attribute: 'plan', operator: 'eq', value: 'premium' },
],
}),
}),
});
const { data } = await response.json();
Response (201 Created)
{
"data": {
"type": "segments",
"id": "550e8400-e29b-41d4-a716-446655440001",
"attributes": {
"key": "premium-users",
"name": "Premium Users",
"description": "Usuários com plano premium",
"ruleType": "SIMPLE",
"ruleContent": "{\"operator\":\"AND\",\"conditions\":[{\"attribute\":\"plan\",\"operator\":\"eq\",\"value\":\"premium\"}]}",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
},
"links": {
"self": "/api/v1/segments/550e8400-e29b-41d4-a716-446655440001"
}
}
}
Listar Segmentos
GET /api/v1/segments
Lista segmentos com suporte a paginação.
Query Parameters
| Parâmetro | Tipo | Descrição |
|---|---|---|
page[number] | integer | Número da pagina |
page[size] | integer | Itens por pagina (max 100) |
- cURL
- JavaScript
curl 'https://feature-flags.stg.catalisa.app/api/v1/segments' \
-H 'Authorization: Bearer SEU_TOKEN'
const response = await fetch('https://feature-flags.stg.catalisa.app/api/v1/segments', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
const { data, meta, links } = await response.json();
Response (200 OK)
{
"data": [
{
"type": "segments",
"id": "550e8400-e29b-41d4-a716-446655440001",
"attributes": {
"key": "premium-users",
"name": "Premium Users",
"ruleType": "SIMPLE"
}
},
{
"type": "segments",
"id": "550e8400-e29b-41d4-a716-446655440002",
"attributes": {
"key": "beta-testers",
"name": "Beta Testers",
"ruleType": "SIMPLE"
}
}
],
"meta": {
"totalItems": 2,
"totalPages": 1,
"currentPage": 1
},
"links": {
"self": "/api/v1/segments?page[number]=1&page[size]=20"
}
}
Obter Segmento
GET /api/v1/segments/:id
Obtém detalhes de um segmento específico.
- cURL
- JavaScript
curl 'https://feature-flags.stg.catalisa.app/api/v1/segments/550e8400-e29b-41d4-a716-446655440001' \
-H 'Authorization: Bearer SEU_TOKEN'
const id = '550e8400-e29b-41d4-a716-446655440001';
const response = await fetch(`https://feature-flags.stg.catalisa.app/api/v1/segments/${id}`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
const { data } = await response.json();
Response (200 OK)
{
"data": {
"type": "segments",
"id": "550e8400-e29b-41d4-a716-446655440001",
"attributes": {
"key": "premium-users",
"name": "Premium Users",
"description": "Usuários com plano premium",
"ruleType": "SIMPLE",
"ruleContent": "{\"operator\":\"AND\",\"conditions\":[{\"attribute\":\"plan\",\"operator\":\"eq\",\"value\":\"premium\"}]}",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
},
"links": {
"self": "/api/v1/segments/550e8400-e29b-41d4-a716-446655440001"
}
}
}
Atualizar Segmento
PATCH /api/v1/segments/:id
Atualiza um segmento existente. A atualização invalida automaticamente o cache de membership.
- cURL
- JavaScript
curl -X PATCH 'https://feature-flags.stg.catalisa.app/api/v1/segments/550e8400-e29b-41d4-a716-446655440001' \
-H 'Authorization: Bearer SEU_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"name": "Premium Users v2",
"ruleContent": "{\"operator\":\"OR\",\"conditions\":[{\"attribute\":\"plan\",\"operator\":\"eq\",\"value\":\"premium\"},{\"attribute\":\"plan\",\"operator\":\"eq\",\"value\":\"enterprise\"}]}"
}'
const id = '550e8400-e29b-41d4-a716-446655440001';
const response = await fetch(`https://feature-flags.stg.catalisa.app/api/v1/segments/${id}`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Premium Users v2',
ruleContent: JSON.stringify({
operator: 'OR',
conditions: [
{ attribute: 'plan', operator: 'eq', value: 'premium' },
{ attribute: 'plan', operator: 'eq', value: 'enterprise' },
],
}),
}),
});
const { data } = await response.json();
Response (200 OK)
{
"data": {
"type": "segments",
"id": "550e8400-e29b-41d4-a716-446655440001",
"attributes": {
"key": "premium-users",
"name": "Premium Users v2",
"ruleContent": "{\"operator\":\"OR\",\"conditions\":[...]}",
"updatedAt": "2024-01-15T11:00:00Z"
}
}
}
Excluir Segmento
DELETE /api/v1/segments/:id
Remove um segmento. Não pode ser excluido se estiver sendo usado por targeting rules.
- cURL
- JavaScript
curl -X DELETE 'https://feature-flags.stg.catalisa.app/api/v1/segments/550e8400-e29b-41d4-a716-446655440001' \
-H 'Authorization: Bearer SEU_TOKEN'
const id = '550e8400-e29b-41d4-a716-446655440001';
const response = await fetch(`https://feature-flags.stg.catalisa.app/api/v1/segments/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
},
});
// Status 204 No Content = sucesso
Response (204 No Content)
Sem corpo de resposta.
Tipos de Regra
SIMPLE
Regras simples baseadas em condições sobre atributos do usuário:
{
"operator": "AND",
"conditions": [
{ "attribute": "plan", "operator": "eq", "value": "premium" },
{ "attribute": "age", "operator": "gte", "value": 18 }
]
}
Estrutura
| Campo | Tipo | Descrição |
|---|---|---|
operator | enum | AND ou OR - como combinar as condições |
conditions | array | Lista de condições |
conditions[].attribute | string | Nome do atributo a verificar |
conditions[].operator | enum | Operador de comparacao |
conditions[].value | any | Valor para comparar |
Operadores
| Operador | Descrição | Exemplo |
|---|---|---|
eq | Igual | plan == "premium" |
neq | Diferente | status != "blocked" |
gt | Maior que | age > 18 |
gte | Maior ou igual | score >= 700 |
lt | Menor que | attempts < 3 |
lte | Menor ou igual | balance <= 0 |
in | Esta na lista | country in ["BR", "US"] |
notIn | Não esta na lista | status notIn ["blocked", "pending"] |
contains | Contém (string) | email contains "@gmail" |
startsWith | Começa com | name startsWith "John" |
endsWith | Termina com | email endsWith ".com" |
Atributo Especial: userId
O atributo userId e tratado de forma especial e e extraido diretamente do contexto de avaliação:
{
"conditions": [
{ "attribute": "userId", "operator": "in", "value": ["user-1", "user-2"] }
]
}
DMN
Regras complexas usando tabelas de decisão DMN (Decision Model and Notation):
{
"key": "complex-eligibility",
"name": "Complex Eligibility",
"ruleType": "DMN",
"ruleContent": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>...", // XML DMN
// ou
"decisionId": "550e8400-e29b-41d4-a716-446655440099" // Referencia ao Decision Engine
}
O segmento DMN retorna true se o output da decisão for:
- Um boolean
true - Um objeto com campo
isMember: true,match: trueouresult: true - Qualquer valor truthy
Exemplos de Segmentos
Usuários de Pais Específico
{
"key": "brazil-users",
"name": "Brazil Users",
"ruleType": "SIMPLE",
"ruleContent": "{\"conditions\":[{\"attribute\":\"country\",\"operator\":\"eq\",\"value\":\"BR\"}]}"
}
Usuários com Alto Score
{
"key": "high-score-users",
"name": "High Score Users",
"ruleType": "SIMPLE",
"ruleContent": "{\"conditions\":[{\"attribute\":\"creditScore\",\"operator\":\"gte\",\"value\":700}]}"
}
Combinacao AND
{
"key": "premium-active",
"name": "Premium and Active",
"ruleType": "SIMPLE",
"ruleContent": "{\"operator\":\"AND\",\"conditions\":[{\"attribute\":\"plan\",\"operator\":\"eq\",\"value\":\"premium\"},{\"attribute\":\"status\",\"operator\":\"eq\",\"value\":\"active\"}]}"
}
Combinacao OR
{
"key": "vip-users",
"name": "VIP Users",
"ruleType": "SIMPLE",
"ruleContent": "{\"operator\":\"OR\",\"conditions\":[{\"attribute\":\"plan\",\"operator\":\"eq\",\"value\":\"enterprise\"},{\"attribute\":\"totalSpent\",\"operator\":\"gte\",\"value\":10000}]}"
}
Lista de Usuários Específicos
{
"key": "beta-testers",
"name": "Beta Testers",
"ruleType": "SIMPLE",
"ruleContent": "{\"conditions\":[{\"attribute\":\"userId\",\"operator\":\"in\",\"value\":[\"user-1\",\"user-2\",\"user-3\"]}]}"
}
Erros Comuns
| Código | Erro | Descrição |
|---|---|---|
| 400 | VALIDATION | Campos obrigatorios ausentes ou ruleContent invalido |
| 404 | NOT_FOUND | Segmento nao encontrado |
| 409 | CONFLICT | Segmento com mesma key ja existe |
| 409 | CONFLICT | Segmento em uso por targeting rules (ao excluir) |