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

# Criar run

> Inicia a execução do bureau para um CPF ou CNPJ.
Retorna imediatamente com `run_id` e `status: queued`.
O resultado é entregue via webhook quando disponível (5–30s em média).




## OpenAPI

````yaml POST /api/v1/bureau/runs
openapi: 3.0.3
info:
  title: kycert API
  version: '2026-06-03'
  description: >
    API KYC/AML para corretoras de câmbio autorizadas pelo Banco Central do
    Brasil.

    Permite rodar verificações de bureau em CPF ou CNPJ e receber o resultado
    via webhook.


    **Fluxo principal:**

    ```

    POST /runs → 202 (run_id) → [bureau processa 5–30s] → webhook entregue →
    agir

    ```
  contact:
    name: kycert
    url: https://kycert.com.br
  license:
    name: Proprietário
    url: https://kycert.com.br
servers:
  - url: https://admin.kycert.com.br
    description: Produção (sk_live_...)
  - url: https://admin.kycert.com.br
    description: Sandbox (sk_test_...)
security:
  - ApiKeyHeader: []
  - BearerToken: []
tags:
  - name: Runs
    description: Execução de bureau para CPF ou CNPJ
  - name: Customers
    description: Gestão de clientes do tenant
paths:
  /api/v1/bureau/runs:
    post:
      tags:
        - Runs
      summary: Criar run de bureau
      description: |
        Inicia a execução do bureau para um CPF ou CNPJ.
        Retorna imediatamente com `run_id` e `status: queued`.
        O resultado é entregue via webhook quando disponível (5–30s em média).
      operationId: createRun
      parameters:
        - name: Idempotency-Key
          in: header
          required: false
          schema:
            type: string
            format: uuid
          description: >
            UUID único por tentativa. Mesmo valor nas próximas 24h retorna o run
            original sem executar novamente.

            Use sempre que implementar retry no seu código.
        - name: x-kycert-api-version
          in: header
          required: false
          schema:
            type: string
            example: '2026-06-03'
          description: |
            Versão da API a usar. **Omitir = versão mais recente.**
            Fixe em `2026-06-03` para garantir estabilidade em produção.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateRunRequest'
            example:
              template_id: 550e8400-e29b-41d4-a716-446655440000
              subject:
                type: pf
                doc: '12345678901'
                name: João Silva
              webhook_url: https://broker.com/webhooks/kycert
              external_id: cust_abc123
              metadata:
                customer_name: João Silva
                channel: app_mobile
      responses:
        '202':
          description: Run criado e em processamento. Resultado entregue via webhook.
          headers:
            X-Request-Id:
              schema:
                type: string
                format: uuid
              description: ID único do request para rastreamento
            X-Kycert-Api-Version:
              schema:
                type: string
              description: Versão da API usada para processar este request
            X-RateLimit-Limit:
              schema:
                type: integer
              description: Limite total da janela atual
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: Requisições restantes na janela atual
            X-RateLimit-Reset:
              schema:
                type: integer
              description: Unix timestamp do momento em que a janela reseta
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateRunResponse'
              example:
                run_id: 550e8400-e29b-41d4-a716-446655440000
                status: queued
                livemode: true
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          $ref: '#/components/responses/PaymentRequired'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/InternalError'
      x-codeSamples:
        - lang: cURL
          label: cURL
          source: |
            curl -X POST https://admin.kycert.com.br/api/v1/bureau/runs \
              -H "x-api-key: $KYCERT_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "template_id": "550e8400-e29b-41d4-a716-446655440000",
                "subject": {
                  "type": "pf",
                  "doc": "12345678901",
                  "name": "João Silva"
                },
                "webhook_url": "https://broker.com/webhooks/kycert"
              }'
        - lang: Node
          label: Node.js
          source: >
            const res = await
            fetch('https://admin.kycert.com.br/api/v1/bureau/runs', {
              method: 'POST',
              headers: {
                'x-api-key': process.env.KYCERT_API_KEY,
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                template_id: '550e8400-e29b-41d4-a716-446655440000',
                subject: { type: 'pf', doc: '12345678901', name: 'João Silva' },
                webhook_url: 'https://broker.com/webhooks/kycert',
              }),
            })

            const { run_id, status } = await res.json()

            console.log(run_id, status)
        - lang: Python
          label: Python
          source: |
            import requests, os

            res = requests.post(
                'https://admin.kycert.com.br/api/v1/bureau/runs',
                headers={'x-api-key': os.environ['KYCERT_API_KEY']},
                json={
                    'template_id': '550e8400-e29b-41d4-a716-446655440000',
                    'subject': {'type': 'pf', 'doc': '12345678901', 'name': 'João Silva'},
                    'webhook_url': 'https://broker.com/webhooks/kycert',
                },
            )
            data = res.json()
            print(data['run_id'], data['status'])
        - lang: PHP
          label: PHP
          source: >
            $client = new \GuzzleHttp\Client();

            $response = $client->request('POST',
            'https://admin.kycert.com.br/api/v1/bureau/runs', [
                'headers' => ['x-api-key' => getenv('KYCERT_API_KEY')],
                'json' => [
                    'template_id' => '550e8400-e29b-41d4-a716-446655440000',
                    'subject' => ['type' => 'pf', 'doc' => '12345678901', 'name' => 'João Silva'],
                    'webhook_url' => 'https://broker.com/webhooks/kycert',
                ],
            ]);

            $data = json_decode($response->getBody(), true);

            echo $data['run_id'];
        - lang: Go
          label: Go
          source: |
            package main

            import (
                "bytes"
                "encoding/json"
                "fmt"
                "net/http"
                "os"
            )

            func main() {
                payload, _ := json.Marshal(map[string]interface{}{
                    "template_id": "550e8400-e29b-41d4-a716-446655440000",
                    "subject": map[string]string{
                        "type": "pf",
                        "doc":  "12345678901",
                        "name": "João Silva",
                    },
                    "webhook_url": "https://broker.com/webhooks/kycert",
                })
                req, _ := http.NewRequest("POST", "https://admin.kycert.com.br/api/v1/bureau/runs", bytes.NewBuffer(payload))
                req.Header.Set("x-api-key", os.Getenv("KYCERT_API_KEY"))
                req.Header.Set("Content-Type", "application/json")

                resp, _ := http.DefaultClient.Do(req)
                defer resp.Body.Close()

                var result map[string]interface{}
                json.NewDecoder(resp.Body).Decode(&result)
                fmt.Println(result["run_id"])
            }
components:
  schemas:
    CreateRunRequest:
      type: object
      required:
        - template_id
        - subject
      properties:
        template_id:
          type: string
          format: uuid
          description: ID do template configurado no dashboard kycert
        subject:
          type: object
          required:
            - doc
          description: Sujeito a ser analisado
          properties:
            type:
              type: string
              enum:
                - pf
                - pj
              description: >
                Tipo do sujeito — `pf` (pessoa física) ou `pj` (pessoa
                jurídica).

                Opcional: quando omitido, inferido automaticamente do `doc` (11
                dígitos = pf, 14 dígitos = pj).

                Se informado, deve ser consistente com o documento — caso
                contrário retorna 400.
            doc:
              type: string
              description: >
                CPF (11 dígitos) ou CNPJ (14 dígitos). Envie sem formatação
                (recomendado).

                A API também aceita CPF/CNPJ formatados com pontos e traços —
                normalizados antes da validação.
              example: '12345678901'
            name:
              type: string
              description: >-
                Nome completo (PF) ou razão social (PJ). Opcional — melhora a
                qualidade do match.
            birth_date:
              type: string
              format: date
              description: >-
                Data de nascimento (apenas PF). Opcional. Formato ISO 8601
                (YYYY-MM-DD).
        webhook_url:
          type: string
          format: uri
          description: >
            URL HTTPS para entrega do resultado deste run.

            Se omitido, usa o endpoint padrão configurado em Integrações & API →
            Webhooks no dashboard.
        external_id:
          type: string
          maxLength: 255
          description: >-
            Seu identificador interno para este run. Útil para correlacionar com
            seu sistema.
        metadata:
          type: object
          additionalProperties:
            type: string
            maxLength: 500
          maxProperties: 10
          description: >-
            Até 10 pares chave-valor string. Retornado no webhook e no GET
            /runs.
    CreateRunResponse:
      type: object
      properties:
        run_id:
          type: string
          format: uuid
          description: Identificador único do run — use para correlação e lookup
        status:
          type: string
          enum:
            - queued
          description: Sempre queued na criação
        livemode:
          type: boolean
          description: true para produção, false para sandbox
    ErrorResponse:
      type: object
      properties:
        error:
          type: object
          properties:
            type:
              type: string
              enum:
                - invalid_request_error
                - authentication_error
                - authorization_error
                - billing_error
                - server_error
            code:
              type: string
              description: Código específico do erro
            message:
              type: string
              description: Descrição legível do erro
            param:
              type: string
              nullable: true
              description: Campo que causou o erro (quando aplicável)
  responses:
    BadRequest:
      description: Requisição inválida — corrija os dados e tente novamente
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missing_subject:
              summary: subject ausente
              value:
                error:
                  type: invalid_request_error
                  code: missing_subject
                  message: subject é obrigatório.
                  param: subject
            invalid_document:
              summary: CPF/CNPJ inválido
              value:
                error:
                  type: invalid_request_error
                  code: invalid_document
                  message: CPF (11 dígitos) ou CNPJ (14 dígitos) inválido.
                  param: subject.doc
            subject_type_mismatch:
              summary: tipo incompatível com template
              value:
                error:
                  type: invalid_request_error
                  code: subject_type_mismatch
                  message: Este template espera subject.type pj, recebido pf.
                  param: subject.type
            template_not_found:
              summary: template não encontrado
              value:
                error:
                  type: invalid_request_error
                  code: template_not_found
                  message: Template não encontrado.
                  param: template_id
            invalid_json:
              summary: JSON malformado
              value:
                error:
                  type: invalid_request_error
                  code: invalid_json
                  message: JSON inválido.
                  param: null
    Unauthorized:
      description: API key ausente ou inválida
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missing_api_key:
              value:
                error:
                  type: authentication_error
                  code: missing_api_key
                  message: API key ausente.
                  param: null
            invalid_api_key:
              value:
                error:
                  type: authentication_error
                  code: invalid_api_key
                  message: API key inválida ou inativa.
                  param: null
    PaymentRequired:
      description: Saldo insuficiente ou billing suspenso
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              type: billing_error
              code: billing_suspended
              message: Saldo insuficiente para realizar a consulta.
              param: null
    Forbidden:
      description: Escopo insuficiente para esta operação
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              type: authorization_error
              code: insufficient_scope
              message: Esta chave não tem permissão para criar runs.
              param: null
    UnprocessableEntity:
      description: Dados semanticamente inválidos
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RateLimited:
      description: Limite de requisições atingido — aguarde Retry-After
      headers:
        Retry-After:
          schema:
            type: integer
          description: Segundos a aguardar antes de tentar novamente
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              type: server_error
              code: rate_limit_exceeded
              message: Limite de uso da chave atingido.
              param: null
    InternalError:
      description: Falha interna — tente novamente com backoff exponencial
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              type: server_error
              code: internal_error
              message: Erro interno. Tente novamente.
              param: null
  securitySchemes:
    ApiKeyHeader:
      type: apiKey
      in: header
      name: x-api-key
      description: API key no header x-api-key (recomendado)
    BearerToken:
      type: http
      scheme: bearer
      description: API key como Bearer token no header Authorization

````