Início / Descrições de produtos: fluxo

Descrições de produtos: fluxo

Gere descrições a partir do nome e das características do produto. Escolha idioma e tamanho, estime o custo e obtenha HTML, título, descrição e H1.

Nesta página

Gere descrições de catálogo a partir do nome e das características do produto. A API retorna HTML, título da página, metadescrição e H1. A geração ocorre em segundo plano: estime o custo, crie um documento e consulte o resultado pelo identificador.

Os três campos são obrigatórios no corpo JSON das duas solicitações POST. Envie Content-Type: application/json. O limite é 16 KiB. Criar exige ai-product-descriptions:write; estimar e consultar o resultado exigem ai-product-descriptions:read.

Parâmetro Descrição
title · string Nome e características principais: de 1 a 256 caracteres. Inclua modelo, material, tamanho ou finalidade para identificar o produto.
language · string Código do idioma na tabela abaixo. Este campo define o idioma do resultado.
word_count · integer Valores do parâmetro e extensão desejada: 400 → 400–600 palavras; 600 → 600–800 palavras; 800 → 800–1200 palavras. O número real de palavras é retornado em actual_words.

Idiomas disponíveis

Use pt para gerar uma descrição em português. Os códigos de idioma aceitos estão em ProductDescriptionRequest.

POST /public-api/v1/ai-writer/product-descriptions/cost

Estima o custo sem iniciar a geração nem gastar créditos. Retorna cost, total_credits, remaining_credits e has_enough_credits. Confira has_enough_credits antes de criar; a estimativa não reserva saldo.

curl

curl --fail-with-body --silent --show-error --location \
  --request POST \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{
  "title": "Ceramic coffee mug, 350 ml, dishwasher safe",
  "language": "en",
  "word_count": 400
}' \
  'https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/cost'

JavaScript

async function main () {
  const response = await fetch("https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/cost", {
    method: "POST",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      "title": "Ceramic coffee mug, 350 ml, dishwasher safe",
      "language": "en",
      "word_count": 400
    }),
    signal: AbortSignal.timeout(30_000),
  })

  if (!response.ok) {
    const responseText = await response.text()
    throw new Error(`HTTP ${response.status}: ${responseText}`)
  }

  const responseText = await response.text()
  const data = responseText && response.headers.get("content-type")?.includes("application/json") ? JSON.parse(responseText) : responseText

  console.log(data)
}

main().catch(error => {
  console.error(error)
  process.exitCode = 1
})

Python

import json
import requests

url = "https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/cost"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Accept": "application/json",
    "Content-Type": "application/json",
}
payload = json.loads("{\n  \"title\": \"Ceramic coffee mug, 350 ml, dishwasher safe\",\n  \"language\": \"en\",\n  \"word_count\": 400\n}")

response = requests.request(
    "POST",
    url,
    headers=headers,
    json=payload,
    timeout=30,
)
response.raise_for_status()
print(json.dumps(response.json(), ensure_ascii=False, indent=2) if response.content and "application/json" in response.headers.get("Content-Type", "") else response.text)

PHP

<?php

$curl = curl_init('https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/cost');

if ($curl === false) {
    throw new RuntimeException('Unable to initialize cURL');
}

curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer YOUR_API_KEY',
        'Accept: application/json',
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => '{
  "title": "Ceramic coffee mug, 350 ml, dishwasher safe",
  "language": "en",
  "word_count": 400
}',
]);

$response = curl_exec($curl);

if ($response === false) {
    $message = curl_error($curl);
    curl_close($curl);
    throw new RuntimeException('Network error: ' . $message);
}

$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($curl);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException("HTTP $status: $response");
}

if ($response !== '' && str_contains($contentType, 'application/json')) {
    print_r(json_decode($response, true, 512, JSON_THROW_ON_ERROR));
} else {
    echo $response;
}

Go

package main

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second)
	defer cancel()

	request, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/cost", strings.NewReader("{\n  \"title\": \"Ceramic coffee mug, 350 ml, dishwasher safe\",\n  \"language\": \"en\",\n  \"word_count\": 400\n}"))
	if err != nil {
		panic(err)
	}

	request.Header.Set("Authorization", "Bearer YOUR_API_KEY")
	request.Header.Set("Accept", "application/json")
	request.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 30 * time.Second}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
		errorBody, readErr := io.ReadAll(response.Body)
		if readErr != nil {
			panic(readErr)
		}
		panic(fmt.Sprintf("HTTP %d: %s", response.StatusCode, errorBody))
	}

	if _, err := io.Copy(os.Stdout, response.Body); err != nil {
		panic(err)
	}
}

Google Apps Script

function callLabrikaPublicAPI() {
  const response = UrlFetchApp.fetch("https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/cost", {
    method: "post",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
    payload: "{\n  \"title\": \"Ceramic coffee mug, 350 ml, dishwasher safe\",\n  \"language\": \"en\",\n  \"word_count\": 400\n}",
    followRedirects: false,
    muteHttpExceptions: true,
  });
  const status = response.getResponseCode();
  if (status < 200 || status >= 300) {
    throw new Error('HTTP ' + status + ': ' + response.getContentText());
  }
  Logger.log(response.getContentText());
}

POST /public-api/v1/ai-writer/product-descriptions/documents

Inicia a geração. Envie um Idempotency-Key exclusivo para cada novo documento. HTTP 202 retorna document_id, status, cost e has_enough_credits. Salve document_id para consultar o resultado.

curl

curl --fail-with-body --silent --show-error --location \
  --request POST \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'Idempotency-Key: product-123-description-v1' \
  --data '{
  "title": "Ceramic coffee mug, 350 ml, dishwasher safe",
  "language": "en",
  "word_count": 400
}' \
  'https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents'

JavaScript

async function main () {
  const response = await fetch("https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents", {
    method: "POST",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
      "Content-Type": "application/json",
      "Idempotency-Key": "product-123-description-v1",
    },
    body: JSON.stringify({
      "title": "Ceramic coffee mug, 350 ml, dishwasher safe",
      "language": "en",
      "word_count": 400
    }),
    signal: AbortSignal.timeout(30_000),
  })

  if (!response.ok) {
    const responseText = await response.text()
    throw new Error(`HTTP ${response.status}: ${responseText}`)
  }

  const responseText = await response.text()
  const data = responseText && response.headers.get("content-type")?.includes("application/json") ? JSON.parse(responseText) : responseText

  console.log(data)
}

main().catch(error => {
  console.error(error)
  process.exitCode = 1
})

Python

import json
import requests

url = "https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Idempotency-Key": "product-123-description-v1",
}
payload = json.loads("{\n  \"title\": \"Ceramic coffee mug, 350 ml, dishwasher safe\",\n  \"language\": \"en\",\n  \"word_count\": 400\n}")

response = requests.request(
    "POST",
    url,
    headers=headers,
    json=payload,
    timeout=30,
)
response.raise_for_status()
print(json.dumps(response.json(), ensure_ascii=False, indent=2) if response.content and "application/json" in response.headers.get("Content-Type", "") else response.text)

PHP

<?php

$curl = curl_init('https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents');

if ($curl === false) {
    throw new RuntimeException('Unable to initialize cURL');
}

curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer YOUR_API_KEY',
        'Accept: application/json',
        'Content-Type: application/json',
        'Idempotency-Key: product-123-description-v1',
    ],
    CURLOPT_POSTFIELDS => '{
  "title": "Ceramic coffee mug, 350 ml, dishwasher safe",
  "language": "en",
  "word_count": 400
}',
]);

$response = curl_exec($curl);

if ($response === false) {
    $message = curl_error($curl);
    curl_close($curl);
    throw new RuntimeException('Network error: ' . $message);
}

$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($curl);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException("HTTP $status: $response");
}

if ($response !== '' && str_contains($contentType, 'application/json')) {
    print_r(json_decode($response, true, 512, JSON_THROW_ON_ERROR));
} else {
    echo $response;
}

Go

package main

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second)
	defer cancel()

	request, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents", strings.NewReader("{\n  \"title\": \"Ceramic coffee mug, 350 ml, dishwasher safe\",\n  \"language\": \"en\",\n  \"word_count\": 400\n}"))
	if err != nil {
		panic(err)
	}

	request.Header.Set("Authorization", "Bearer YOUR_API_KEY")
	request.Header.Set("Accept", "application/json")
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Idempotency-Key", "product-123-description-v1")

	client := &http.Client{Timeout: 30 * time.Second}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
		errorBody, readErr := io.ReadAll(response.Body)
		if readErr != nil {
			panic(readErr)
		}
		panic(fmt.Sprintf("HTTP %d: %s", response.StatusCode, errorBody))
	}

	if _, err := io.Copy(os.Stdout, response.Body); err != nil {
		panic(err)
	}
}

Google Apps Script

function callLabrikaPublicAPI() {
  const response = UrlFetchApp.fetch("https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents", {
    method: "post",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
      "Content-Type": "application/json",
      "Idempotency-Key": "product-123-description-v1",
    },
    payload: "{\n  \"title\": \"Ceramic coffee mug, 350 ml, dishwasher safe\",\n  \"language\": \"en\",\n  \"word_count\": 400\n}",
    followRedirects: false,
    muteHttpExceptions: true,
  });
  const status = response.getResponseCode();
  if (status < 200 || status >= 300) {
    throw new Error('HTTP ' + status + ': ' + response.getContentText());
  }
  Logger.log(response.getContentText());
}

GET /public-api/v1/ai-writer/product-descriptions/documents/{document_id}

Com pending, repita GET após retry_after_seconds (normalmente 10 segundos). Com success: content (HTML), title, description, h1, actual_words e credits_spent. Com error, consulte error_code; credits_spent é 0.

curl

curl --fail-with-body --silent --show-error --location \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Accept: application/json' \
  'https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents/DOCUMENT_ID'

JavaScript

async function main () {
  const response = await fetch("https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents/DOCUMENT_ID", {
    method: "GET",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
    },
    signal: AbortSignal.timeout(30_000),
  })

  if (!response.ok) {
    const responseText = await response.text()
    throw new Error(`HTTP ${response.status}: ${responseText}`)
  }

  const responseText = await response.text()
  const data = responseText && response.headers.get("content-type")?.includes("application/json") ? JSON.parse(responseText) : responseText

  console.log(data)
}

main().catch(error => {
  console.error(error)
  process.exitCode = 1
})

Python

import json
import requests

url = "https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents/DOCUMENT_ID"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Accept": "application/json",
}

response = requests.request(
    "GET",
    url,
    headers=headers,
    timeout=30,
)
response.raise_for_status()
print(json.dumps(response.json(), ensure_ascii=False, indent=2) if response.content and "application/json" in response.headers.get("Content-Type", "") else response.text)

PHP

<?php

$curl = curl_init('https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents/DOCUMENT_ID');

if ($curl === false) {
    throw new RuntimeException('Unable to initialize cURL');
}

curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer YOUR_API_KEY',
        'Accept: application/json',
    ],
]);

$response = curl_exec($curl);

if ($response === false) {
    $message = curl_error($curl);
    curl_close($curl);
    throw new RuntimeException('Network error: ' . $message);
}

$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($curl);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException("HTTP $status: $response");
}

if ($response !== '' && str_contains($contentType, 'application/json')) {
    print_r(json_decode($response, true, 512, JSON_THROW_ON_ERROR));
} else {
    echo $response;
}

Go

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second)
	defer cancel()

	request, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents/DOCUMENT_ID", nil)
	if err != nil {
		panic(err)
	}

	request.Header.Set("Authorization", "Bearer YOUR_API_KEY")
	request.Header.Set("Accept", "application/json")

	client := &http.Client{Timeout: 30 * time.Second}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
		errorBody, readErr := io.ReadAll(response.Body)
		if readErr != nil {
			panic(readErr)
		}
		panic(fmt.Sprintf("HTTP %d: %s", response.StatusCode, errorBody))
	}

	if _, err := io.Copy(os.Stdout, response.Body); err != nil {
		panic(err)
	}
}

Google Apps Script

function callLabrikaPublicAPI() {
  const response = UrlFetchApp.fetch("https://app.labrika.com/public-api/v1/ai-writer/product-descriptions/documents/DOCUMENT_ID", {
    method: "get",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
    },
    followRedirects: false,
    muteHttpExceptions: true,
  });
  const status = response.getResponseCode();
  if (status < 200 || status >= 300) {
    throw new Error('HTTP ' + status + ': ' + response.getContentText());
  }
  Logger.log(response.getContentText());
}

Se perder a resposta POST, repita com a mesma chave API, Idempotency-Key e corpo. A resposta salva é retornada durante 24 horas. Corpo diferente ou solicitação incompleta gera HTTP 409. Se faltarem créditos, recarregue e use uma chave nova.

product_not_recognized: detalhe o nome e as características. product_description_failed: a geração falhou. Uma falha de reconhecimento conhecida pode retornar HTTP 422 imediatamente e fica em cache por 7 dias para o mesmo produto. Uma chave nova não ignora esse cache.

Créditos de IA são reservados no início. Após o sucesso, credits_spent indica o consumo real e a reserva não usada é devolvida. Falhas de geração não consomem créditos.

Antes de usar uma saída de IA, confira fatos, nome da empresa ou produto, idioma e consistência com os dados de entrada. Revise o HTML gerado antes de publicar. O sucesso técnico não substitui a revisão do conteúdo.