> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pierre.finance/llms.txt
> Use this file to discover all available pages before exploring further.

# Create Spending Limit

> Cria um novo limite de gastos personalizado para uma categoria específica. Requer API key para autenticação e assinatura ativa. O usuário deve ter cota disponível baseada no seu plano (Basic: 0 limites, Pro: 2 limites, Premium: 5 limites).

> [!NOTE]
>
> Este endpoint cria um novo alerta de gastos para monitorar uma categoria específica em um período definido.

## Descrição

O endpoint `POST /tools/api/create-spending-limit` permite criar alertas de gastos personalizados para categorias específicas. O usuário será notificado quando atingir 50%, 75% e 100% do limite configurado.

## Autenticação

Este endpoint requer autenticação via Bearer token.

**Authorization** `string` *required*

Bearer token com a API key do usuário. Formato: `Bearer sk-your-api-key-here`

## Parâmetros de Query

**s** `string` *required*

Parâmetro interno para indicar requisições via MCP. Use `s=s` para requisições MCP.

## Body Parameters

**category** `string` *required*

Nome da categoria a ser monitorada (ex: "Alimentação", "Transporte", "Lazer")

**limitAmount** `number` *required*

Valor limite em BRL. Deve ser um número positivo.

**period** `string` *required*

Período do alerta. Valores válidos: `daily`, `weekly`, `biweekly`, `monthly`

## Resposta

### Sucesso (200)

```json Success theme={null}
{
  "success": true,
  "data": {
    "id": "limit_123456789",
    "userId": "user_abc123",
    "category": "Alimentação",
    "limitAmount": 1000.00,
    "period": "monthly",
    "isActive": true,
    "isRecurring": false,
    "periodStart": null,
    "createdAt": "2024-11-04T15:30:00Z",
    "updatedAt": "2024-11-04T15:30:00Z"
  },
  "message": "Spending limit created successfully for Alimentação",
  "timestamp": "2024-11-04T15:30:00Z"
}
```

### Erro de Validação (400)

```json Error - Missing Category theme={null}
{
  "error": "Invalid or missing category",
  "message": "Category must be a non-empty string"
}
```

```json Error - Invalid Amount theme={null}
{
  "error": "Invalid or missing limitAmount",
  "message": "limitAmount must be a positive number"
}
```

```json Error - Invalid Period theme={null}
{
  "error": "Invalid or missing period",
  "message": "period must be one of: daily, weekly, monthly"
}
```

### Erro de Autenticação (401)

```json Error theme={null}
{
  "error": "Invalid or inactive API key",
  "message": "Please check your API key and try again",
  "type": "invalid_api_key"
}
```

### Erro de Quota Excedida (403)

```json Error theme={null}
{
  "error": "Quota exceeded",
  "message": "Plano FREE: 3/3 alertas utilizados. Limite atingido! Faça upgrade para criar mais alertas.",
  "success": false
}
```

## Campos da Resposta

**success** `boolean` *required*

Indica se a requisição foi bem-sucedida

**data** `object` *required*

Objeto com os dados do alerta criado

**Spending Limit Object**

**id** `string` *required*

Identificador único do alerta criado

**userId** `string` *required*

ID do usuário proprietário do alerta

**category** `string` *required*

Categoria de gasto monitorada

**limitAmount** `number` *required*

Valor limite configurado em BRL

**period** `string` *required*

Período do alerta: `daily`, `weekly`, `biweekly`, ou `monthly`

**isActive** `boolean` *required*

Se o alerta está ativo (sempre `true` na criação)

**isRecurring** `boolean` *required*

Se o alerta se renova automaticamente

**periodStart** `string`

Data de início do período (null se começar imediatamente)

**createdAt** `string` *required*

Data de criação do alerta (ISO 8601)

**updatedAt** `string` *required*

Data da última atualização (ISO 8601)

**message** `string` *required*

Mensagem de confirmação da criação

**timestamp** `string` *required*

Timestamp da requisição em formato ISO 8601

## Exemplos de Uso

### cURL

```bash theme={null}
# Criar alerta mensal para Alimentação
curl -X POST 'https://www.pierre.finance/tools/api/create-spending-limit' \
  -H 'Authorization: Bearer sk-your-api-key-here' \
  -H 'Content-Type: application/json' \
  -d '{
    "category": "Alimentação",
    "limitAmount": 1000,
    "period": "monthly"
  }'

# Criar alerta semanal para Transporte
curl -X POST 'https://www.pierre.finance/tools/api/create-spending-limit' \
  -H 'Authorization: Bearer sk-your-api-key-here' \
  -H 'Content-Type: application/json' \
  -d '{
    "category": "Transporte",
    "limitAmount": 300,
    "period": "weekly"
  }'
```

### JavaScript

```javascript theme={null}
const API_KEY = 'sk-your-api-key-here';
const BASE_URL = 'https://www.pierre.finance/tools/api';

async function createSpendingLimit(category, limitAmount, period) {
  const response = await fetch(`${BASE_URL}/create-spending-limit`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ category, limitAmount, period })
  });
  
  return await response.json();
}

// Exemplos de uso
createSpendingLimit('Alimentação', 1000, 'monthly');
createSpendingLimit('Transporte', 300, 'weekly');
createSpendingLimit('Lazer', 500, 'biweekly');
```

### Python

```python theme={null}
import requests

API_KEY = 'sk-your-api-key-here'
BASE_URL = 'https://www.pierre.finance/tools/api'

headers = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
}

def create_spending_limit(category, limit_amount, period):
    data = {
        'category': category,
        'limitAmount': limit_amount,
        'period': period
    }
    response = requests.post(f'{BASE_URL}/create-spending-limit',
                           headers=headers, json=data)
    return response.json()

# Exemplos de uso
limit = create_spending_limit('Alimentação', 1000, 'monthly')
limit = create_spending_limit('Transporte', 300, 'weekly')
limit = create_spending_limit('Lazer', 500, 'biweekly')
```

## Códigos de Status

* `200`: Sucesso - Alerta criado
* `400`: Parâmetros inválidos
* `401`: Erro de autenticação ou assinatura
* `403`: Quota excedida - limite de alertas atingido
* `500`: Erro interno do servidor

## Períodos Disponíveis

* **`daily`**: Alerta renovado diariamente às 00:00 UTC
* **`weekly`**: Alerta renovado semanalmente às segundas-feiras 00:00 UTC
* **`biweekly`**: Alerta renovado a cada duas semanas
* **`monthly`**: Alerta renovado mensalmente no dia 1º às 00:00 UTC

## Limites por Plano

* **FREE**: 3 alertas de gastos
* **PRO**: 10 alertas de gastos
* **PREMIUM**: 30 alertas de gastos

> [!NOTE]
>
> Os alertas enviam notificações automáticas quando você atinge 50%, 75% e 100% do limite configurado. Use categorias consistentes com as suas transações para melhor precisão.

> [!TIP]
>
> Para criar alertas que começam no próximo período (e não imediatamente), use o endpoint `confirm-spending-limit` com o parâmetro `startNextPeriod`.


## OpenAPI

````yaml POST /tools/api/create-spending-limit
openapi: 3.1.0
info:
  title: Pierre Finance API
  description: >-
    API para acessar dados financeiros do Pierre Finance, incluindo contas,
    transações, parcelas e sincronização.
  version: v1.0.0
servers:
  - url: https://www.pierre.finance
security: []
tags:
  - name: Authentication
    description: API key management and authentication
  - name: Accounts
    description: Financial accounts management
  - name: Transactions
    description: Financial transactions
  - name: Installments
    description: Credit card installments and purchases
  - name: Bills
    description: Credit card bills and current bill summaries
  - name: Balance
    description: Account balance information
  - name: Closing Dates
    description: Credit card closing date management
  - name: Sync
    description: Account synchronization
  - name: Spending Limits
    description: Personal spending limits and alerts management
  - name: Payment Reminders
    description: Payment reminders management with WhatsApp and Email notifications
  - name: Analytics
    description: Financial analytics and insights
  - name: Memories
    description: User memory management for personalized AI interactions
  - name: Open Finance
    description: Open Finance connection and integration
paths:
  /tools/api/create-spending-limit:
    post:
      tags:
        - Spending Limits
      description: >-
        Cria um novo limite de gastos personalizado para uma categoria
        específica. Requer API key para autenticação e assinatura ativa. O
        usuário deve ter cota disponível baseada no seu plano (Basic: 0 limites,
        Pro: 2 limites, Premium: 5 limites).
      operationId: createSpendingLimit
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSpendingLimitRequest'
      responses:
        '200':
          description: Limite de gastos criado com sucesso
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    $ref: '#/components/schemas/SpendingLimit'
                  message:
                    type: string
                    example: Spending limit created successfully for Alimentação
                  timestamp:
                    type: string
                    format: date-time
        '400':
          description: Parâmetros inválidos
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Invalid or missing category
                  message:
                    type: string
                    example: Category must be a non-empty string
        '401':
          $ref: '#/components/responses/AuthError'
        '403':
          description: Cota de limites excedida
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Quota exceeded
                  message:
                    type: string
                    example: >-
                      Limite de alertas atingido. Você já tem 2 alertas ativos e
                      seu plano PRO permite até 2 alertas.
                  success:
                    type: boolean
                    example: false
        '500':
          $ref: '#/components/responses/ServerError'
      security:
        - BearerAuth: []
components:
  schemas:
    CreateSpendingLimitRequest: {}
    SpendingLimit: {}
    AuthError: {}
    ServerError: {}
  responses:
    AuthError:
      description: Authentication or subscription error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/AuthError'
    ServerError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ServerError'
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: string
      description: 'API key in Bearer token format. Example: Bearer sk-your-api-key-here'

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.