Motores e preços
Os motores
Três motores leem a certidão: mini e large, os motores padrão, respondem a toda requisição. O fast responde primeiro quando a requisição o pede com "engine": "fast"; se ele não conseguir responder, os motores padrão entram em seguida. A resposta diz qual motor respondeu, em engine.
bash
#!/usr/bin/env bash
# Ask for the fast engine: it is tried first, at its own price, and the
# standard engines follow when it cannot answer. The answer names the engine
# that answered and what it cost. Needs DOCSOCR_API_KEY in the environment.
set -euo pipefail
REQUEST_ID="fast-$(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.jpg",
"requestId": "$REQUEST_ID",
"engine": "fast"
}
EOFpy
"""Ask for the fast engine: it is tried first, at its own price, and the
standard engines follow when it cannot answer. The answer names the engine
that answered and what it cost.
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.jpg",
"requestId": str(uuid.uuid4()), # one id per document
"engine": "fast",
},
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("engine:", answer["engine"], "credits:", answer["creditsCharged"])js
// Ask for the fast engine: it is tried first, at its own price, and the
// standard engines follow when it cannot answer. The answer names the engine
// that answered and what it cost.
// 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.jpg',
requestId: randomUUID(), // one id per document
engine: 'fast',
}),
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('engine:', answer.engine, 'credits:', answer.creditsCharged)php
<?php
// Ask for the fast engine: it is tried first, at its own price, and the
// standard engines follow when it cannot answer. The answer names the engine
// that answered and what it cost.
// 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.jpg',
'requestId' => bin2hex(random_bytes(16)), // one id per document
'engine' => 'fast',
]),
]);
$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 'engine: ', $answer['engine'], ' credits: ', $answer['creditsCharged'], PHP_EOL;java
// Ask for the fast engine: it is tried first, at its own price, and the
// standard engines follow when it cannot answer. The answer names the engine
// that answered and what it cost.
// Needs Java 17+ and DOCSOCR_API_KEY in the environment. Run: java Fast.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 Fast {
public static void main(String[] args) throws Exception {
String body = """
{
"imageType": "url",
"imageUrl": "https://docsocr.com/samples/certidao-nascimento-exemplo.jpg",
"requestId": "%s",
"engine": "fast"
}""".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: engine and creditsCharged say who answered and the cost
System.out.println(response.body());
if (response.statusCode() != 201 || !response.body().contains("\"success\":true")) {
System.exit(1);
}
}
}csharp
// Ask for the fast engine: it is tried first, at its own price, and the
// standard engines follow when it cannot answer. The answer names the engine
// that answered and what it cost.
// Needs .NET 8+ and DOCSOCR_API_KEY in the environment. Run: dotnet run Fast.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.jpg",
["requestId"] = Guid.NewGuid().ToString(), // one id per document
["engine"] = "fast",
};
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($"engine: {root.GetProperty("engine").GetString()} credits: {root.GetProperty("creditsCharged")}");
return 0;O que custa
Uma resposta com dados custa o preço do motor que a deu, por documento. Os preços podem mudar; esta tabela os lê agora da API:
Lendo os preços…
- Sem
engine, a requisição reserva o maior dos preços do mini e do large enquanto roda. - Com
"engine": "fast", ela reserva o preço do fast. - Nos dois casos, ela paga o preço do motor que responde, nunca mais do que reservou.
resizeImage: o preço do redimensionamento a mais, quando a imagem é redimensionada. Veja Padrão de imagem.
O seu código lê a mesma lista em GET /documents/prices, que não precisa de chave.
bash
#!/usr/bin/env bash
# The price of an extraction, in credits, for each document: per engine and for resizeImage.
# A public endpoint: no key needed.
set -euo pipefail
curl -sS --max-time 30 https://api.docsocr.com/api/v1/documents/pricespy
"""The price of an extraction, in credits, for each document: per engine and for resizeImage.
A public endpoint: no key needed. Needs the requests package.
"""
import requests
response = requests.get("https://api.docsocr.com/api/v1/documents/prices", timeout=30)
response.raise_for_status()
for price in response.json()["documents"]:
print(
f"{price['document']}: standard {price['standard']}, fast {price['fast']}, "
f"resizeImage +{price['resizeImage']} credit(s)"
)js
// The price of an extraction, in credits, for each document: per engine and for resizeImage.
// A public endpoint: no key needed. Needs Node.js 18+.
const response = await fetch('https://api.docsocr.com/api/v1/documents/prices', {
signal: AbortSignal.timeout(30_000),
})
if (!response.ok) {
console.error(response.status)
process.exit(1)
}
for (const price of (await response.json()).documents) {
console.log(
`${price.document}: standard ${price.standard}, fast ${price.fast}, resizeImage +${price.resizeImage} credit(s)`
)
}php
<?php
// The price of an extraction, in credits, for each document: per engine and for resizeImage.
// A public endpoint: no key needed. Needs the curl extension.
$request = curl_init('https://api.docsocr.com/api/v1/documents/prices');
curl_setopt_array($request, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30]);
$body = curl_exec($request);
if ($body === false || curl_getinfo($request, CURLINFO_RESPONSE_CODE) !== 200) {
fwrite(STDERR, 'The price list did not answer' . PHP_EOL);
exit(1);
}
foreach (json_decode($body, true)['documents'] as $price) {
echo "{$price['document']}: standard {$price['standard']}, fast {$price['fast']}, "
. "resizeImage +{$price['resizeImage']} credit(s)", PHP_EOL;
}java
// The price of an extraction, in credits, for each document: per engine and for resizeImage.
// A public endpoint: no key needed. Needs Java 17+. Run: java Prices.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Prices {
public static void main(String[] args) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.docsocr.com/api/v1/documents/prices"))
.timeout(Duration.ofSeconds(30))
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
// The answer is JSON, e.g. {"documents": [{"document": "birth-certificate", "standard": 1, ...}]};
// read it with your JSON library
System.out.println(response.body());
if (response.statusCode() != 200) {
System.exit(1);
}
}
}csharp
// The price of an extraction, in credits, for each document: per engine and for resizeImage.
// A public endpoint: no key needed. Needs .NET 8+. Run: dotnet run Prices.cs (.NET 10)
using System.Text.Json;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
using var prices = JsonDocument.Parse(await http.GetStringAsync("https://api.docsocr.com/api/v1/documents/prices"));
foreach (var price in prices.RootElement.GetProperty("documents").EnumerateArray())
{
Console.WriteLine(
$"{price.GetProperty("document")}: standard {price.GetProperty("standard")}, fast {price.GetProperty("fast")}, "
+ $"resizeImage +{price.GetProperty("resizeImage")} credit(s)");
}O que não custa nada
- Uma requisição recusada, com 400 ou 422.
- Uma requisição que nenhum motor conseguiu atender: a resposta é 201 com
success: false. - Uma repetição respondida com a resposta guardada. Veja IDs de requisição e repetições.
Quanto custou
Cada resposta diz quanto custou, em creditsCharged, ao centésimo. Quando o saldo não paga a requisição, a resposta é 402 NOT_ENOUGH_CREDITS e nada roda. O saldo e as compras de créditos ficam no painel.