HTTP clients
cURL, Node.js, Python and TypeScript requests, response handling and bounded batch behavior.
On this page
The four implementations issue one POST /api/v3/ine with profile=extended and mode=both. They share the same multipart fields and an existing transaction key; redirects and automatic POST retries are disabled.
idempotencyKey / idempotency_key matches [A-Za-z0-9._:-]{8,128}. The same transaction retains its key and exact image bytes. Multipart boundaries are transport metadata and may differ between exact replays.
Response semantics
| Outcome | Meaning |
|---|---|
200 with status: "succeeded" | Completed result in data; warnings and expires_at accompany it. |
202 with status: "processing" | Pending result; Retry-After controls the next GET interval. |
| Structured error | Machine-readable error.code, message and action; error reference. |
| Redirect, malformed body, network error or timeout | Unconfirmed outcome. Recovery retains the transaction key and uses a known request ID when available. |
GET and exact replay do not initiate new extraction. A changed transaction key can reserve a new billable reading. The returned HTTP status and body remain separate; a parsed JSON body alone does not establish success.
Request implementations
curl --silent --show-error --max-time 90 \
--request POST 'https://ocr.ecostudios.dev/api/v3/ine' \
--header "X-API-Key: $INE_API_KEY" \
--header "Idempotency-Key: $INE_IDEMPOTENCY_KEY" \
--header 'Accept: application/json' \
--form 'profile=extended' \
--form 'mode=both' \
--form "front=@${INE_FRONT_PATH}" \
--form "back=@${INE_BACK_PATH}" \
--dump-header "$INE_HEADERS_PATH" \
--output "$INE_RESULT_PATH" \
--write-out '%{http_code}\n'
export async function createReading({ apiKey, idempotencyKey, front, back }) {
if (!apiKey || !/^[A-Za-z0-9._:-]{8,128}$/.test(idempotencyKey ?? '')) {
throw new TypeError('invalid_credentials');
}
if (!(front instanceof Blob) || !(back instanceof Blob)) {
throw new TypeError('images_must_be_blobs');
}
const body = new FormData();
body.set('profile', 'extended');
body.set('mode', 'both');
body.set('front', front, 'front');
body.set('back', back, 'back');
let response;
try {
response = await fetch('https://ocr.ecostudios.dev/api/v3/ine', {
method: 'POST',
headers: {
'X-API-Key': apiKey,
'Idempotency-Key': idempotencyKey,
Accept: 'application/json',
},
body,
redirect: 'manual',
signal: AbortSignal.timeout(90_000),
});
} catch {
throw new Error('connection_unconfirmed');
}
const payload = await response.json().catch(() => null);
const requestId = payload && typeof payload === 'object' && !Array.isArray(payload)
&& typeof payload.request_id === 'string' ? payload.request_id : null;
return {
http_status: response.status,
request_id: requestId ?? response.headers.get('x-request-id'),
retry_after: response.headers.get('retry-after'),
body: payload,
};
}
import json
import re
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener
from uuid import uuid4
class NoRedirects(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def create_reading(*, api_key, idempotency_key, front, back, mime_type):
if not api_key or not re.fullmatch(r'[A-Za-z0-9._:-]{8,128}', idempotency_key):
raise ValueError('invalid_credentials')
if not isinstance(front, bytes) or not isinstance(back, bytes):
raise TypeError('images_must_be_bytes')
if mime_type not in ('image/jpeg', 'image/png', 'image/webp'):
raise ValueError('unsupported_mime_type')
boundary = 'ine-' + uuid4().hex
chunks = []
for name, value in (('profile', 'extended'), ('mode', 'both')):
chunks.append((f'--{boundary}\r\nContent-Disposition: form-data; '
f'name="{name}"\r\n\r\n{value}\r\n').encode())
for side, data in (('front', front), ('back', back)):
chunks.extend([
(f'--{boundary}\r\nContent-Disposition: form-data; '
f'name="{side}"; filename="{side}"\r\n'
f'Content-Type: {mime_type}\r\n\r\n').encode(),
data, b'\r\n',
])
chunks.append(f'--{boundary}--\r\n'.encode())
request = Request(
'https://ocr.ecostudios.dev/api/v3/ine',
data=b''.join(chunks), method='POST',
headers={
'X-API-Key': api_key,
'Idempotency-Key': idempotency_key,
'Content-Type': f'multipart/form-data; boundary={boundary}',
'Accept': 'application/json',
},
)
try:
try:
response = build_opener(NoRedirects()).open(request, timeout=90)
except HTTPError as error:
response = error
with response:
status, headers = response.status, response.headers
raw = response.read(128 * 1024 + 1)
try:
payload = json.loads(raw) if len(raw) <= 128 * 1024 else None
except ValueError:
payload = None
except (URLError, TimeoutError, OSError):
raise RuntimeError('connection_unconfirmed') from None
request_id = payload.get('request_id') if isinstance(payload, dict) else None
request_id = request_id if isinstance(request_id, str) else None
return {
'http_status': status,
'request_id': request_id or headers.get('x-request-id'),
'retry_after': headers.get('retry-after'),
'body': payload,
}
type CreateReadingInput = {
apiKey: string;
idempotencyKey: string;
front: Blob;
back: Blob;
};
type ReadingResponse = {
http_status: number;
request_id: string | null;
retry_after: string | null;
body: unknown;
};
function requestIdFrom(payload: unknown): string | null {
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
return null;
}
return 'request_id' in payload && typeof payload.request_id === 'string'
? payload.request_id
: null;
}
export async function createReading({
apiKey, idempotencyKey, front, back,
}: CreateReadingInput): Promise<ReadingResponse> {
if (!apiKey || !/^[A-Za-z0-9._:-]{8,128}$/.test(idempotencyKey)) {
throw new TypeError('invalid_credentials');
}
if (!(front instanceof Blob) || !(back instanceof Blob)) {
throw new TypeError('images_must_be_blobs');
}
const body = new FormData();
body.set('profile', 'extended');
body.set('mode', 'both');
body.set('front', front, 'front');
body.set('back', back, 'back');
let response: Response;
try {
response = await fetch('https://ocr.ecostudios.dev/api/v3/ine', {
method: 'POST',
headers: {
'X-API-Key': apiKey,
'Idempotency-Key': idempotencyKey,
Accept: 'application/json',
},
body,
redirect: 'manual',
signal: AbortSignal.timeout(90_000),
});
} catch {
throw new Error('connection_unconfirmed');
}
const payload: unknown = await response.json().catch(() => null);
return {
http_status: response.status,
request_id: requestIdFrom(payload) ?? response.headers.get('x-request-id'),
retry_after: response.headers.get('retry-after'),
body: payload,
};
}
Runtime contract
Runtime targets are cURL 8+, Node.js 22+, Python 3.10+ and TypeScript 5+. JavaScript and TypeScript use native Node.js web APIs; TypeScript compilation includes ES2022 and DOM types. Python uses only its standard library. No vendor SDK is required.
| Format | Input and transport behavior |
|---|---|
| cURL | Image paths in INE_FRONT_PATH and INE_BACK_PATH; headers in INE_HEADERS_PATH, response body in INE_RESULT_PATH, HTTP status on standard output. |
| Node.js | front and back are Blob instances with the image MIME type. Native FormData generates the boundary. |
| Python | front and back are bytes; mime_type applies to both files. Response capture is bounded to 128 KiB. |
| TypeScript | Typed inputs and transport metadata; body: unknown remains unvalidated API content. request_id is narrowed to a string independently. |
The cURL deadline and JavaScript abort deadline are 90 seconds; Python uses a 90-second socket timeout. These are client settings, not API latency guarantees. The response body and HTTP status remain separate, and these functions do not validate the full result schema.
Bounded result polling
The Node.js client and Python client accept PNG/JPEG files, submit the standard profile and reserve a 90-second total wait budget. A valid 202 switches subsequent requests to GET. POST is never automatically repeated.
| Client input | Meaning |
|---|---|
INE_API_KEY | Extraction credential. |
| Two file paths and a transaction key | One standard-profile, two-sided request. |
--request-id UUID | GET-only retrieval; no image upload. |
--print-data | Full response output; default output excludes identity values. |
Alternative invocations:
node ine-node.mjs "$INE_FRONT_PATH" "$INE_BACK_PATH" "$INE_IDEMPOTENCY_KEY"
python3 ine-python.py "$INE_FRONT_PATH" "$INE_BACK_PATH" "$INE_IDEMPOTENCY_KEY"
node ine-node.mjs --request-id "$INE_REQUEST_ID"
Batch contract
The Node.js batch client accepts 1–100 manifest entries and runs at most two concurrent requests. Concurrency and rate limits remain shared with every process using the API account.
| Manifest key | Type / constraint |
|---|---|
idempotency_key | Distinct stable string per transaction. |
front | File path relative to the manifest; required by both and front modes. |
back | File path relative to the manifest; required by both and back modes. |
profile | standard or extended; defaults to standard. |
mode | both, front or back; defaults to both. |
node ine-batch.mjs "$INE_MANIFEST_PATH" --output "$INE_STATE_PATH"
The state file is exclusively created with private permissions. It contains request IDs, statuses, image hashes and transaction keys; it excludes image paths, OCR values and API keys. The exported runBatch function accepts onResult({ index, request_id, result }) for successful result handling.
| Condition | Batch behavior |
|---|---|
Admission 429: rate_limited, concurrency_limited, admission_changed | At most two retries with the same bytes and key; full Retry-After must fit within 60 seconds. |
Authentication, quota, network, technical 5xx, malformed response or result-handler failure | New submissions stop; active requests may complete. No automatic POST retry. |
Valid 202 | Request state saved for a later explicit GET. |
| Existing state | No automatic polling or resumption. |