# Salvar preferências

> Salvar preferências: PUT /v1/preferences. Muda as preferências. Parcial (só muda o que for enviado) e estrito (campo ou valor desconhecido dá 422 invalid_field). Devolve as preferências completas. Os e-mails de Com email true o servidor manda por e-mail postSent, postFailed, scheduledFail, o weeklyS

Fonte: https://praeko.app/docs/api/preferences/save-preferences

`PUT /v1/preferences` · escopo mínimo: write

Muda as preferências. Parcial (só muda o que for enviado) e estrito (campo ou valor desconhecido dá 422 `invalid_field`). Devolve as preferências completas. Os e-mails de Com `email` true o servidor manda por e-mail `postSent`, `postFailed`, `scheduledFail`, o `weeklySummary` (segunda 08:00 de São Paulo) e o `newComment` (agrupado, no máximo um e-mail por hora); com `panel` true o evento entra na central de avisos (`GET /v1/notifications`).

> **Cabeçalhos** `Authorization: Bearer praeko_…` e `X-Praeko-Contract: en`. Sempre envie os dois.

## Corpo da requisição

JSON. Campos obrigatórios precisam ir; os outros podem ser omitidos. Campo que não está na tabela é recusado. Estrito: campo ou valor desconhecido dá 422 `invalid_field`. Parcial: só o que for enviado muda.

| Campo | Tipo | Descrição |
|---|---|---|
| `theme` (opcional) | texto | Tema do painel. Valores: light, dark, system. |
| `language` (opcional) | texto | Idioma do painel. Valores: pt-BR, en. |
| `notifications` (opcional) | objeto | Avisos por evento. Só os eventos enviados mudam. |
| `notifications.postSent` (opcional) | objeto | Onde avisar este evento. |
| `notifications.postSent.email` (opcional) | verdadeiro/falso | Avisar por e-mail. |
| `notifications.postSent.panel` (opcional) | verdadeiro/falso | Avisar no painel. |
| `notifications.postFailed` (opcional) | objeto | Onde avisar este evento. |
| `notifications.postFailed.email` (opcional) | verdadeiro/falso | Avisar por e-mail. |
| `notifications.postFailed.panel` (opcional) | verdadeiro/falso | Avisar no painel. |
| `notifications.scheduledFail` (opcional) | objeto | Onde avisar este evento. |
| `notifications.scheduledFail.email` (opcional) | verdadeiro/falso | Avisar por e-mail. |
| `notifications.scheduledFail.panel` (opcional) | verdadeiro/falso | Avisar no painel. |
| `notifications.weeklySummary` (opcional) | objeto | Onde avisar este evento. |
| `notifications.weeklySummary.email` (opcional) | verdadeiro/falso | Avisar por e-mail. |
| `notifications.weeklySummary.panel` (opcional) | verdadeiro/falso | Avisar no painel. |
| `notifications.newComment` (opcional) | objeto | Onde avisar este evento. |
| `notifications.newComment.email` (opcional) | verdadeiro/falso | Avisar por e-mail. |
| `notifications.newComment.panel` (opcional) | verdadeiro/falso | Avisar no painel. |

**Exemplo de corpo**

```json
{
  "theme": "dark",
  "language": "pt-BR",
  "notifications": {
    "postFailed": {
      "email": true,
      "panel": true
    },
    "weeklySummary": {
      "email": false
    }
  }
}
```

## Exemplo

**curl**

```bash
curl -X PUT "https://praeko.app/v1/preferences" \
  -H "Authorization: Bearer $PRAEKO_KEY" \
  -H "X-Praeko-Contract: en" \
  -H "Content-Type: application/json" \
  -d '{
  "theme": "dark",
  "language": "pt-BR",
  "notifications": {
    "postFailed": {
      "email": true,
      "panel": true
    },
    "weeklySummary": {
      "email": false
    }
  }
}'
```

**JavaScript**

```js
const res = await fetch("https://praeko.app/v1/preferences", {
  method: "PUT",
  headers: {
    "Authorization": `Bearer ${process.env.PRAEKO_KEY}`,
    "X-Praeko-Contract": "en",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "theme": "dark",
    "language": "pt-BR",
    "notifications": {
      "postFailed": {
        "email": true,
        "panel": true
      },
      "weeklySummary": {
        "email": false
      }
    }
  }),
});
console.log(res.status, await res.json());
```

**Node**

```js
import { Praeko } from "@praeko/sdk";

const praeko = new Praeko({ url: "https://praeko.app", key: process.env.PRAEKO_KEY });
const resultado = await praeko.preferences.put({
  "theme": "dark",
  "language": "pt-BR",
  "notifications": {
    "postFailed": {
      "email": true,
      "panel": true
    },
    "weeklySummary": {
      "email": false
    }
  }
});
console.log(resultado);
```

**Python**

```python
import os
import requests

resp = requests.put(
    "https://praeko.app/v1/preferences",
    headers={
        "Authorization": f"Bearer {os.environ['PRAEKO_KEY']}",
        "X-Praeko-Contract": "en",
    },
    json={
        "theme": "dark",
        "language": "pt-BR",
        "notifications": {
            "postFailed": {
                "email": True,
                "panel": True,
            },
            "weeklySummary": {
                "email": False,
            },
        },
    },
)
print(resp.status_code, resp.json())
```

**PHP**

```php
<?php
$corpo = <<<'JSON'
{
  "theme": "dark",
  "language": "pt-BR",
  "notifications": {
    "postFailed": {
      "email": true,
      "panel": true
    },
    "weeklySummary": {
      "email": false
    }
  }
}
JSON;

$ch = curl_init('https://praeko.app/v1/preferences');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'PUT',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("PRAEKO_KEY"),
        'X-Praeko-Contract: en',
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => $corpo,
]);
$resposta = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $resposta, PHP_EOL;
curl_close($ch);
```

**Go**

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	body := strings.NewReader(`{
  "theme": "dark",
  "language": "pt-BR",
  "notifications": {
    "postFailed": {
      "email": true,
      "panel": true
    },
    "weeklySummary": {
      "email": false
    }
  }
}`)
	req, err := http.NewRequest("PUT", "https://praeko.app/v1/preferences", body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("PRAEKO_KEY"))
	req.Header.Set("X-Praeko-Contract", "en")
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	out, _ := io.ReadAll(resp.Body)
	fmt.Println(resp.Status, string(out))
}
```

**Ruby**

```ruby
require "net/http"
require "uri"

uri = URI("https://praeko.app/v1/preferences")
request = Net::HTTP::Put.new(uri)
request["Authorization"] = "Bearer #{ENV['PRAEKO_KEY']}"
request["X-Praeko-Contract"] = "en"
request["Content-Type"] = "application/json"
request.body = <<~'JSON'
  {
    "theme": "dark",
    "language": "pt-BR",
    "notifications": {
      "postFailed": {
        "email": true,
        "panel": true
      },
      "weeklySummary": {
        "email": false
      }
    }
  }
JSON

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(request) }
puts response.code, response.body
```

**C#**

```csharp
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Put, "https://praeko.app/v1/preferences");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("PRAEKO_KEY"));
request.Headers.Add("X-Praeko-Contract", "en");
request.Content = new StringContent("""
    {
      "theme": "dark",
      "language": "pt-BR",
      "notifications": {
        "postFailed": {
          "email": true,
          "panel": true
        },
        "weeklySummary": {
          "email": false
        }
      }
    }
""", Encoding.UTF8, "application/json");

using var response = await client.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

**Java**

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String body = """
            {
              "theme": "dark",
              "language": "pt-BR",
              "notifications": {
                "postFailed": {
                  "email": true,
                  "panel": true
                },
                "weeklySummary": {
                  "email": false
                }
              }
            }
            """;
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://praeko.app/v1/preferences"))
            .header("Authorization", "Bearer " + System.getenv("PRAEKO_KEY"))
            .header("X-Praeko-Contract", "en")
            .header("Content-Type", "application/json")
            .method("PUT", HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

**HTTPie**

```bash
http PUT "https://praeko.app/v1/preferences" \
  "Authorization: Bearer $PRAEKO_KEY" \
  "X-Praeko-Contract: en" \
  "Content-Type: application/json" \
  --raw='{
  "theme": "dark",
  "language": "pt-BR",
  "notifications": {
    "postFailed": {
      "email": true,
      "panel": true
    },
    "weeklySummary": {
      "email": false
    }
  }
}'
```

> SDK oficial para Node: Instale com `npm install @praeko/sdk` (veja [SDK e CLI](https://praeko.app/docs/sdk)).

## Resposta

| Status de sucesso | Quando |
|---|---|
| `200` | Sucesso. |

**Resposta 200**

```json
{
  "theme": "dark",
  "language": "pt-BR",
  "notifications": {
    "postSent": {
      "email": false,
      "panel": true
    },
    "postFailed": {
      "email": true,
      "panel": true
    },
    "scheduledFail": {
      "email": false,
      "panel": true
    },
    "weeklySummary": {
      "email": false,
      "panel": true
    },
    "newComment": {
      "email": false,
      "panel": true
    }
  }
}
```

## Erros

| Status | code | Quando |
|---|---|---|
| 400 | `empty_body` | O corpo veio vazio. |
| 400 | `invalid_json` | O corpo não é um objeto JSON. |
| 413 | `body_too_large` | O corpo passa de 1 MB. |
| 422 | `invalid_field` | Campo, evento, canal ou valor desconhecido. |

### Erros de qualquer rota

| Status | code | Quando |
|---|---|---|
| 401 | `unauthorized` | Faltou o cabeçalho `Authorization: Bearer …`. |
| 401 | `invalid_api_key` | A chave não existe. |
| 401 | `revoked_api_key` | A chave foi revogada. |
| 401 | `expired_api_key` | A chave expirou. |
| 403 | `forbidden` | O escopo da chave não basta para esta rota (veja o selo de escopo). |
| 429 | `rate_limited` | Passou do limite de requisições por minuto. |

O corpo de todo erro é `{ "error": { "code", "message", "details"? } }`. Veja [todos os códigos](https://praeko.app/docs/guides/errors-and-limits).

## Testar

> **Testar**: o teste ao vivo exige entrar na conta. Aqui ele fica desligado.
