Pular para o conteúdo

Padrão de imagem ​

Formatos e tamanho ​

  • PDF*, JPG, PNG, WebP ou GIF. *Lemos apenas a primeira página do PDF.
  • Até 10 MB por arquivo. A requisição inteira, com a imagem em base64, vai até 15 MB; acima disso, a resposta é 413.
  • O tipo do arquivo é lido do próprio arquivo, não da extensão nem do nome.

Nosso padrão: 1344 a 2048 px no lado maior ​

Os motores leem melhor uma imagem com 1344 a 2048 px no lado maior; numa digitalização A4, isso é cerca de 120 a 175 DPI. Uma imagem fora do padrão é recusada com 422, com IMAGE_RESOLUTION_TOO_LOW ou IMAGE_RESOLUTION_TOO_HIGH, sem custo.

resizeImage ​

Com "resizeImage": true, uma imagem fora do padrão é redimensionada do nosso lado em vez de recusada, por 1 crédito a mais; nos motores padrão, a requisição precisa de 2 créditos disponíveis. Uma imagem dentro do padrão nunca é redimensionada. Quando a imagem foi redimensionada, a resposta traz imageResized: true e os tamanhos de antes e depois.

bash
#!/usr/bin/env bash
# Extract an image outside our standard: resizeImage brings it to the
# standard first, for one extra credit (the 800x640 sample is too small).
# Needs DOCSOCR_API_KEY in the environment.
set -euo pipefail

REQUEST_ID="resize-$(date +%s)-$RANDOM" # one id per document

# The API answers within 90 s
curl -sS --max-time 120 https://api.docsocr.com/api/v1/documents/birth-certificate \
  -H "Authorization: Bearer $DOCSOCR_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @- <<EOF
{
  "imageType": "url",
  "imageUrl": "https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg",
  "requestId": "$REQUEST_ID",
  "resizeImage": true
}
EOF
py
"""Extract an image outside our standard: resizeImage brings it to the
standard first, for one extra credit (the 800x640 sample is too small).

Needs the requests package and DOCSOCR_API_KEY in the environment.
"""
import os
import uuid

import requests

response = requests.post(
    "https://api.docsocr.com/api/v1/documents/birth-certificate",
    headers={"Authorization": f"Bearer {os.environ['DOCSOCR_API_KEY']}"},
    json={
        "imageType": "url",
        "imageUrl": "https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg",
        "requestId": str(uuid.uuid4()),  # one id per document
        "resizeImage": True,
    },
    timeout=120,  # above the API's 90 s extraction budget
)
answer = response.json()
if response.status_code != 201 or not answer["success"]:
    raise SystemExit(f"{response.status_code} {answer.get('errorCode', '')} {answer.get('message') or answer.get('error')}")
print(answer["data"]["dados_pessoais"]["nome_completo"])
print("resized:", answer.get("imageResized", False), "credits:", answer["creditsCharged"])
js
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'

const response = await fetch('https://api.docsocr.com/api/v1/documents/birth-certificate', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    imageType: 'url',
    imageUrl: 'https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg',
    requestId: randomUUID(), // one id per document
    resizeImage: true,
  }),
  signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
})
const answer = await response.json()
if (response.status !== 201 || !answer.success) {
  console.error(response.status, answer.errorCode ?? '', answer.message ?? answer.error)
  process.exit(1)
}
console.log(answer.data.dados_pessoais.nome_completo)
console.log('resized:', answer.imageResized ?? false, 'credits:', answer.creditsCharged)
php
<?php
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'url',
        'imageUrl' => 'https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg',
        'requestId' => bin2hex(random_bytes(16)), // one id per document
        'resizeImage' => true,
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;
echo 'resized: ', var_export($answer['imageResized'] ?? false, true), ' credits: ', $answer['creditsCharged'], PHP_EOL;
java
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs Java 17+ and DOCSOCR_API_KEY in the environment. Run: java Resize.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.UUID;

public class Resize {
    public static void main(String[] args) throws Exception {
        String body = """
            {
              "imageType": "url",
              "imageUrl": "https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg",
              "requestId": "%s",
              "resizeImage": true
            }""".formatted(UUID.randomUUID()); // one id per document

        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.docsocr.com/api/v1/documents/birth-certificate"))
            .timeout(Duration.ofSeconds(120)) // above the API's 90 s extraction budget
            .header("Authorization", "Bearer " + System.getenv("DOCSOCR_API_KEY"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());

        // The answer is JSON: data, imageResized and creditsCharged; read them with your JSON library
        System.out.println(response.body());
        if (response.statusCode() != 201 || !response.body().contains("\"success\":true")) {
            System.exit(1);
        }
    }
}
csharp
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs .NET 8+ and DOCSOCR_API_KEY in the environment. Run: dotnet run Resize.cs (.NET 10)
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;

using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(120) }; // above the API's 90 s extraction budget
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("DOCSOCR_API_KEY"));

var body = new JsonObject
{
    ["imageType"] = "url",
    ["imageUrl"] = "https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg",
    ["requestId"] = Guid.NewGuid().ToString(), // one id per document
    ["resizeImage"] = true,
};
using var content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");
using var response = await http.PostAsync("https://api.docsocr.com/api/v1/documents/birth-certificate", content);
using var answer = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = answer.RootElement;

if ((int)response.StatusCode != 201 || !root.GetProperty("success").GetBoolean())
{
    Console.Error.WriteLine($"{(int)response.StatusCode} {root}");
    return 1;
}
Console.WriteLine(root.GetProperty("data").GetProperty("dados_pessoais").GetProperty("nome_completo").GetString());
var resized = root.TryGetProperty("imageResized", out var flag) && flag.GetBoolean();
Console.WriteLine($"resized: {resized} credits: {root.GetProperty("creditsCharged")}");
return 0;

Uma URL ou o arquivo em base64 ​

  • "imageType": "url" com imageUrl: um link público e direto para o arquivo, que abra sem login. Um endereço privado ou local é recusado com IMAGE_URL_NOT_ALLOWED, e um link que não baixa, com IMAGE_DOWNLOAD_FAILED.
  • "imageType": "base64" com imageBase64: o conteúdo do arquivo em base64, com ou sem o prefixo data:image/jpeg;base64,.
bash
#!/usr/bin/env bash
# Extract a certificate from a local file, sent in base64. The JSON body is
# written to a file, so a large image never becomes a shell argument.
# Needs DOCSOCR_API_KEY in the environment.
set -euo pipefail

FILE="certificate.jpg"
REQUEST_ID="local-file-$(date +%s)-$RANDOM" # one id per document

{
  printf '{"imageType":"base64","requestId":"%s","imageBase64":"' "$REQUEST_ID"
  base64 < "$FILE" | tr -d '\n'
  printf '"}'
} > body.json

# The API answers within 90 s
curl -sS --max-time 120 https://api.docsocr.com/api/v1/documents/birth-certificate \
  -H "Authorization: Bearer $DOCSOCR_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @body.json
py
"""Extract a certificate from a local file, sent in base64.

Needs the requests package and DOCSOCR_API_KEY in the environment.
"""
import base64
import os
import uuid

import requests

with open("certificate.jpg", "rb") as file:
    image_base64 = base64.b64encode(file.read()).decode("ascii")

response = requests.post(
    "https://api.docsocr.com/api/v1/documents/birth-certificate",
    headers={"Authorization": f"Bearer {os.environ['DOCSOCR_API_KEY']}"},
    json={
        "imageType": "base64",
        "imageBase64": image_base64,
        "requestId": str(uuid.uuid4()),  # one id per document
    },
    timeout=120,  # above the API's 90 s extraction budget
)
answer = response.json()
if response.status_code != 201 or not answer["success"]:
    raise SystemExit(f"{response.status_code} {answer.get('errorCode', '')} {answer.get('message') or answer.get('error')}")
print(answer["data"]["dados_pessoais"]["nome_completo"])
js
// Extract a certificate from a local file, sent in base64.
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'
import { readFile } from 'node:fs/promises'

const imageBase64 = (await readFile('certificate.jpg')).toString('base64')

const response = await fetch('https://api.docsocr.com/api/v1/documents/birth-certificate', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    imageType: 'base64',
    imageBase64,
    requestId: randomUUID(), // one id per document
  }),
  signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
})
const answer = await response.json()
if (response.status !== 201 || !answer.success) {
  console.error(response.status, answer.errorCode ?? '', answer.message ?? answer.error)
  process.exit(1)
}
console.log(answer.data.dados_pessoais.nome_completo)
php
<?php
// Extract a certificate from a local file, sent in base64.
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$imageBase64 = base64_encode(file_get_contents('certificate.jpg'));

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'base64',
        'imageBase64' => $imageBase64,
        'requestId' => bin2hex(random_bytes(16)), // one id per document
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;
java
// Extract a certificate from a local file, sent in base64.
// Needs Java 17+ and DOCSOCR_API_KEY in the environment. Run: java LocalFile.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Base64;
import java.util.UUID;

public class LocalFile {
    public static void main(String[] args) throws Exception {
        String imageBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of("certificate.jpg")));
        String body = """
            {"imageType": "base64", "requestId": "%s", "imageBase64": "%s"}"""
            .formatted(UUID.randomUUID(), imageBase64); // one id per document

        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.docsocr.com/api/v1/documents/birth-certificate"))
            .timeout(Duration.ofSeconds(120)) // above the API's 90 s extraction budget
            .header("Authorization", "Bearer " + System.getenv("DOCSOCR_API_KEY"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());

        // The answer is JSON: read data.dados_pessoais.nome_completo with your JSON library
        System.out.println(response.body());
        if (response.statusCode() != 201 || !response.body().contains("\"success\":true")) {
            System.exit(1);
        }
    }
}
csharp
// Extract a certificate from a local file, sent in base64.
// Needs .NET 8+ and DOCSOCR_API_KEY in the environment. Run: dotnet run LocalFile.cs (.NET 10)
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;

var imageBase64 = Convert.ToBase64String(await File.ReadAllBytesAsync("certificate.jpg"));

using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(120) }; // above the API's 90 s extraction budget
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("DOCSOCR_API_KEY"));

var body = new JsonObject
{
    ["imageType"] = "base64",
    ["imageBase64"] = imageBase64,
    ["requestId"] = Guid.NewGuid().ToString(), // one id per document
};
using var content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");
using var response = await http.PostAsync("https://api.docsocr.com/api/v1/documents/birth-certificate", content);
using var answer = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = answer.RootElement;

if ((int)response.StatusCode != 201 || !root.GetProperty("success").GetBoolean())
{
    Console.Error.WriteLine($"{(int)response.StatusCode} {root}");
    return 1;
}
Console.WriteLine(root.GetProperty("data").GetProperty("dados_pessoais").GetProperty("nome_completo").GetString());
return 0;

Uma boa foto ​

  • A certidão inteira no quadro, sem cortar as bordas, e de frente.
  • Luz uniforme, sem reflexo sobre o texto.
  • Uma imagem nítida: uma foto tremida pode voltar sem dados, com IMAGE_NOT_PROCESSABLE, sem custo.

Cada recusa tem o seu errorCode e uma mensagem que diz o que fazer: veja Erros.