openapi: 3.1.0
info:
  title: 1billion API
  version: "1.0"
  summary: Transactional e-mail by 1billion, on its own sending infrastructure.
  description: |
    Send e-mail from your server with an API key of an app. All that can refuse a mail
    happens before the 202; after it, the result comes by webhook.
servers:
  - url: https://api.1billion.clowk.in
security:
  - apiKey: []
tags:
  - name: Envio
  - name: Supressões
  - name: Validação

paths:
  /send:
    post:
      operationId: send
      tags: [Envio]
      summary: Enviar um e-mail
      description: |
        Tudo que pode recusar a mensagem acontece antes do 202; depois disso, o resultado
        chega por webhook. Cada destinatário custa 1.000 créditos. O 202 vem na hora, e cada
        e-mail sai na sua vez: 1 a cada 3 s com os créditos do dia, 5 por segundo com um pacote.
      parameters:
        - name: Idempotency-Key
          in: header
          required: false
          description: A mesma chave do mesmo app devolve o primeiro resultado (200) e não envia de novo. Vale por 30 dias.
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Mail" }
      responses:
        "202": { description: Aceito., content: { application/json: { schema: { $ref: "#/components/schemas/Accepted" } } } }
        "200": { description: A mesma Idempotency-Key; nada novo foi enviado., content: { application/json: { schema: { $ref: "#/components/schemas/Accepted" } } } }
        "400": { $ref: "#/components/responses/BadJson" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "429":
          description: Sem créditos hoje para estes destinatários. Os créditos do dia voltam às 00:00 UTC; Retry-After e retry_after dizem em quantos segundos. O corpo tem buy_url.
          headers: { Retry-After: { schema: { type: integer } } }
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403": { description: Os envios do workspace estão pausados (reputação abaixo de 90%)., content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "422": { description: Mensagem inválida, domínio não verificado, ou um destinatário falhou uma checagem (check e address no corpo)., content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "503": { $ref: "#/components/responses/Unavailable" }
      x-code-samples:
        - lang: curl
          label: cURL
          source: |
            curl -X POST https://api.1billion.clowk.in/send \
              -H "Authorization: Bearer $ONEBILLION_API_KEY" \
              -H "Content-Type: application/json" \
              -H "Idempotency-Key: login-jane-482913" \
              -d '{"from":"App <hi@seu-dominio.com>","to":["jane@exemplo.com"],"subject":"Seu código","body":{"text":"Seu código é 482 913"}}'
        - lang: ruby
          label: Ruby
          source: |
            OneBillion::Emails.send(
              {
                from: "App <hi@seu-dominio.com>",
                to: ["jane@exemplo.com"],
                subject: "Seu código",
                text: "Seu código é 482 913"
              },
              { idempotency_key: "login-jane-482913" }
            )
        - lang: go
          label: Go
          source: |
            client := onebillion.New("")

            _, err := client.Emails.Send(ctx, onebillion.Mail{
            	From:    "App <hi@seu-dominio.com>",
            	To:      []string{"jane@exemplo.com"},
            	Subject: "Seu código",
            	Text:    "Seu código é 482 913",
            }, onebillion.IdempotencyKey("login-jane-482913"))
        - lang: typescript
          label: TypeScript
          source: |
            const mail = new OneBillion()

            const { data, error } = await mail.emails.send(
              {
                from: "App <hi@seu-dominio.com>",
                to: ["jane@exemplo.com"],
                subject: "Seu código",
                text: "Seu código é 482 913",
              },
              { idempotencyKey: "login-jane-482913" },
            )

  /messages/{id}:
    get:
      operationId: message
      tags: [Envio]
      summary: Ler um destinatário
      description: O estado de um destinatário. Mensagens terminadas ficam 30 dias.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: O destinatário., content: { application/json: { schema: { $ref: "#/components/schemas/Message" } } } }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { description: Nenhuma mensagem, ou uma mensagem de outro app., content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "503": { $ref: "#/components/responses/Unavailable" }
      x-code-samples:
        - { lang: curl, label: cURL, source: "curl https://api.1billion.clowk.in/messages/9f2c… \\\n  -H \"Authorization: Bearer $ONEBILLION_API_KEY\"\n" }
        - { lang: ruby, label: Ruby, source: "client.message(\"9f2c…\")\n" }
        - { lang: go, label: Go, source: "msg, err := client.Message(ctx, \"9f2c…\")\n" }
        - { lang: typescript, label: TypeScript, source: "const msg = await mail.message(\"9f2c…\")\n" }

  /suppressions/{address}:
    delete:
      operationId: suppression
      tags: [Supressões]
      summary: Tirar da supressão
      description: Tira o endereço da lista de supressão do app. Codifique o @ como %40.
      parameters:
        - { name: address, in: path, required: true, schema: { type: string, format: email } }
      responses:
        "204": { description: Removido. }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "404": { description: O endereço não está na lista., content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
        "503": { $ref: "#/components/responses/Unavailable" }
      x-code-samples:
        - { lang: curl, label: cURL, source: "curl -X DELETE https://api.1billion.clowk.in/suppressions/jane%40exemplo.com \\\n  -H \"Authorization: Bearer $ONEBILLION_API_KEY\"\n" }
        - { lang: ruby, label: Ruby, source: "client.unsuppress(\"jane@exemplo.com\")\n" }
        - { lang: go, label: Go, source: "err := client.Unsuppress(ctx, \"jane@exemplo.com\")\n" }
        - { lang: typescript, label: TypeScript, source: "await mail.unsuppress(\"jane@exemplo.com\")\n" }

  /validate:
    post:
      operationId: validate
      tags: [Validação]
      summary: Validar um endereço
      description: |
        O veredito de um endereço (deliverable, risky ou undeliverable), o motivo, a nota de 0 a 1
        e os sinais: descartável, função, provedor gratuito, subendereço, erro de digitação e o
        histórico deste workspace. Não testa a caixa no servidor do destinatário. Não envia nada.
        Custa 100 créditos por chamada; sem créditos, 429.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [address]
              properties:
                address: { type: string, format: email, description: O endereço a validar. }
      responses:
        "200": { description: O veredito e cada checagem., content: { application/json: { schema: { $ref: "#/components/schemas/Validation" } } } }
        "400": { $ref: "#/components/responses/BadJson" }
        "429":
          description: Sem créditos para a validação. Retry-After até 00:00 no fuso do workspace.
          headers: { Retry-After: { schema: { type: integer } } }
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "503": { $ref: "#/components/responses/Unavailable" }
      x-code-samples:
        - { lang: curl, label: cURL, source: "curl -X POST https://api.1billion.clowk.in/validate \\\n  -H \"Authorization: Bearer $ONEBILLION_API_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"address\":\"jane@exemplo.com\"}'\n" }
        - { lang: ruby, label: Ruby, source: "client.validate(\"jane@exemplo.com\")[\"valid\"]\n" }
        - { lang: go, label: Go, source: "res, err := client.Validate(ctx, \"jane@exemplo.com\")\n" }
        - { lang: typescript, label: TypeScript, source: "const { valid } = await mail.validate(\"jane@exemplo.com\")\n" }

webhooks:
  event:
    post:
      summary: Um evento de um e-mail
      description: |
        Um POST para a URL do app a cada mensagem que termina. Headers 1B-Event-Id,
        1B-Timestamp e 1B-Signature: sha256=<hex>, o HMAC-SHA256 de "<timestamp>.<corpo>"
        com o segredo do app. Responda 2xx em até 10 s; outra resposta tenta de novo. A entrega
        é pelo menos uma vez: use o id para ignorar um evento repetido.
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Event" }
      responses:
        "200": { description: Recebido. }

components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      description: A chave da API de um app, criada no console (Apps e chaves). Só no servidor.

  responses:
    BadJson: { description: Corpo JSON inválido., content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
    Unauthorized: { description: API key errada., content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } } }
    Unavailable:
      description: Tente de novo depois do Retry-After, com a mesma Idempotency-Key. Só 503 e erros de rede valem um retry.
      headers: { Retry-After: { schema: { type: integer } } }
      content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  schemas:
    Mail:
      type: object
      required: [from, subject, body]
      properties:
        from: { type: string, description: "O remetente, como \"App <hi@seu-dominio.com>\". O domínio é do app e verificado." }
        to: { type: array, items: { type: string }, description: Os destinatários. 50 no total com cc e bcc. }
        cc: { type: array, items: { type: string }, description: Cópia. }
        bcc: { type: array, items: { type: string }, description: Cópia oculta; não vai na mensagem. }
        reply_to: { type: string, description: Para onde vão as respostas. Use um endereço que recebe e-mail. }
        subject: { type: string, description: O assunto. }
        body:
          type: object
          description: html, text ou os dois. Com os dois, a nota anti-spam é melhor.
          properties:
            html: { type: string }
            text: { type: string }
        attachments:
          type: array
          description: content em base64. A mensagem inteira tem limite de 15 MB.
          items:
            type: object
            required: [filename, content]
            properties:
              filename: { type: string }
              content_type: { type: string }
              content: { type: string, contentEncoding: base64 }
        priority: { type: string, enum: [normal, high], description: "high para o que uma pessoa espera: código, link mágico, senha." }
        raw: { type: string, description: Uma mensagem MIME pronta, no lugar dos outros campos (com to). }

    Accepted:
      type: object
      properties:
        messages:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              to: { type: string }
              status: { type: string, enum: [accepted, suppressed] }

    Message:
      type: object
      properties:
        id: { type: string }
        to: { type: string }
        status: { type: string, enum: [accepted, queued, sending, sent, bounced, suppressed, canceled] }
        attempts: { type: integer }
        last_error: { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    Validation:
      type: object
      properties:
        address: { type: string }
        user: { type: string, description: A parte antes do @. }
        domain: { type: string }
        result: { type: string, enum: [deliverable, risky, undeliverable] }
        reason: { type: string, enum: [invalid_syntax, no_mail_server, suppressed, bounced_before, disposable, possible_typo, looks_generated, role, delivered_before, mail_server_found] }
        score: { type: number, description: "De 0 a 1. Um subendereço tira 0,1." }
        did_you_mean: { type: [string, "null"], description: "O endereço com o provedor certo, para um erro como gmial.com." }
        free: { type: boolean, description: Provedor gratuito (Gmail, Outlook, UOL...). }
        role: { type: boolean, description: "Endereço de função: contato@, vendas@, noreply@." }
        disposable: { type: boolean, description: E-mail temporário. }
        generated: { type: boolean, description: "O nome parece gerado por máquina, como tszjzua6834@: um robô de cadastro." }
        subaddress: { type: boolean, description: "Tem +tag, como joao+promo@." }
        base_address: { type: [string, "null"], description: A caixa sem a tag. }
        mx_found: { type: boolean }
        mx_host: { type: [string, "null"] }
        suppressed: { type: boolean }
        history: { type: [string, "null"], enum: [delivered, bounced, null], description: O que este workspace viu do endereço em 30 dias. }
        credits: { type: integer, description: O custo desta validação. }
        duration_ms: { type: integer, description: Quanto a validação levou, em milissegundos. }
        valid: { type: boolean, description: Passou nas checagens que o /send faz. }
        checks:
          type: array
          items:
            type: object
            properties:
              check: { type: string, enum: [syntax, mx, suppression, disposable, role] }
              ok: { type: boolean }
              detail: { type: string }

    Event:
      type: object
      properties:
        id: { type: string, description: O mesmo id em cada nova tentativa. }
        type: { type: string, enum: [delivered, bounced, unsubscribed, test] }
        message_id: { type: string, description: Vazio em unsubscribed e test. }
        to: { type: string }
        detail: { type: string }
        created_at: { type: string, format: date-time }

    Error:
      type: object
      properties:
        error: { type: string }
        check: { type: string, description: "No 422 de uma checagem: syntax, mx, disposable ou role." }
        address: { type: string }
        retry_after: { type: integer, description: No 429, os segundos até as 00:00 UTC. }
        buy_url: { type: string, description: No 429. }
