Skip to Content
Identomic SDK Docs

Backend examples by language

Authorize any of the six modules from a trusted server using the same HTTPS and JSON contract.

View as Markdown

Use these examples on your backend

These examples authorize one capture after your application has authenticated and authorized the caller. Set IDENTOMIC_SDK_URL to the full HTTPS URL ending in /api/v1/sdk, and IDENTOMIC_SECRET_KEY to the matching secret. Supply MODULE and OPERATION_ID from your server-side workflow. Use a fresh operation ID per intended capture and preserve it across retries. Return only the capture session fields to the authorized app. Keep authorization headers and response bodies out of logs.

Module IDs

  • fingerprints
  • face_capture
  • face_liveness
  • passport_photo
  • passport_nfc
  • face_comparison

cURL

Use the same endpoint from shells or HTTP clients. This smoke test writes the token response to a private file.

Terminal
umask 077
jq -n --arg module "$MODULE" --arg id "$OPERATION_ID" \
  '{module: $module, idempotencyKey: $id}' |
  curl --fail-with-body --silent --show-error --max-time 15 \
    -H "Authorization: Bearer $IDENTOMIC_SECRET_KEY" \
    -H "Content-Type: application/json" --data-binary @- \
    --output capture-session.json "$IDENTOMIC_SDK_URL/sessions"

Python

Uses the standard library. Handle HTTPError on your server without logging sensitive response data.

import json
import os
from urllib.request import HTTPRedirectHandler, Request, build_opener

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

def create_session(module, operation_id):
    body = json.dumps({"module": module, "idempotencyKey": operation_id}).encode()
    request = Request(os.environ["IDENTOMIC_SDK_URL"].rstrip("/") + "/sessions",
                      data=body, headers={
        "Authorization": "Bearer " + os.environ["IDENTOMIC_SECRET_KEY"],
        "Content-Type": "application/json",
    })
    with build_opener(NoRedirect).open(request, timeout=15) as response:
        return json.load(response)

Go

Use a bounded request timeout. Handle the returned error before passing any session data to the app.

package identomic

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

func CreateSession(module, operationID string) (json.RawMessage, error) {
    payload, err := json.Marshal(map[string]string{
        "module": module, "idempotencyKey": operationID,
    })
    if err != nil { return nil, err }
    req, err := http.NewRequest("POST", strings.TrimRight(os.Getenv("IDENTOMIC_SDK_URL"), "/")+"/sessions", bytes.NewReader(payload))
    if err != nil { return nil, err }
    req.Header.Set("Authorization", "Bearer "+os.Getenv("IDENTOMIC_SECRET_KEY"))
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{
        Timeout: 15 * time.Second,
        CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
    }
    res, err := client.Do(req)
    if err != nil { return nil, err }
    defer res.Body.Close()
    if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
        return nil, fmt.Errorf("Identomic HTTP %d", res.StatusCode)
    }
    var session json.RawMessage
    err = json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&session)
    return session, err
}

Java

Use the JDK HTTP client and your application’s JSON library. This example uses Jackson.

import com.fasterxml.jackson.databind.ObjectMapper;
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.Map;

class IdentomicApi {
    static String createSession(String module, String operationId) throws Exception {
        var client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(15))
            .followRedirects(HttpClient.Redirect.NEVER).build();
        var payload = new ObjectMapper().writeValueAsString(Map.of(
            "module", module, "idempotencyKey", operationId));
        var request = HttpRequest.newBuilder(URI.create(
                System.getenv("IDENTOMIC_SDK_URL") + "/sessions"))
            .timeout(Duration.ofSeconds(15))
            .header("Authorization", "Bearer " + System.getenv("IDENTOMIC_SECRET_KEY"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(payload)).build();
        var response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() != 200 && response.statusCode() != 201)
            throw new IllegalStateException("Identomic HTTP " + response.statusCode());
        return response.body();
    }
}

C# / .NET

Use a reusable HttpClient on your backend. The caller owns the workflow and operation ID.

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;

public static class IdentomicApi
{
    private static readonly HttpClient Client = new(
        new HttpClientHandler { AllowAutoRedirect = false })
    {
        Timeout = TimeSpan.FromSeconds(15)
    };

    public static async Task<string> CreateSession(string module, string operationId)
    {
        var url = Environment.GetEnvironmentVariable("IDENTOMIC_SDK_URL");
        using var request = new HttpRequestMessage(HttpMethod.Post, url + "/sessions");
        request.Headers.Authorization = new AuthenticationHeaderValue(
            "Bearer", Environment.GetEnvironmentVariable("IDENTOMIC_SECRET_KEY"));
        request.Content = JsonContent.Create(new { module, idempotencyKey = operationId });
        using var response = await Client.SendAsync(request);
        if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.Created))
            throw new HttpRequestException($"Identomic HTTP {(int)response.StatusCode}");
        return await response.Content.ReadAsStringAsync();
    }
}

PHP

Use the PHP cURL extension and keep the secret in your server environment.

<?php
function createSession(string $module, string $operationId): array {
    $url = rtrim(getenv('IDENTOMIC_SDK_URL'), '/') . '/sessions';
    $body = json_encode(['module' => $module, 'idempotencyKey' => $operationId], JSON_THROW_ON_ERROR);
    $handle = curl_init($url);
    curl_setopt_array($handle, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . getenv('IDENTOMIC_SECRET_KEY'),
            'Content-Type: application/json',
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_TIMEOUT => 15,
    ]);
    $response = curl_exec($handle);
    $status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
    if ($response === false || !in_array($status, [200, 201], true)) {
        throw new RuntimeException("Identomic HTTP " . $status);
    }
    return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
}

Ruby

Uses Net::HTTP with TLS. Check the response before returning session fields to the app.

require "net/http"
require "json"

def create_session(capture_module, operation_id)
  uri = URI(ENV.fetch("IDENTOMIC_SDK_URL") + "/sessions")
  request = Net::HTTP::Post.new(uri)
  request["Authorization"] = "Bearer " + ENV.fetch("IDENTOMIC_SECRET_KEY")
  request["Content-Type"] = "application/json"
  request.body = JSON.generate(module: capture_module, idempotencyKey: operation_id)
  response = Net::HTTP.start(uri.host, uri.port, use_ssl: true,
                            open_timeout: 5, read_timeout: 15) do |http|
    http.request(request)
  end
  raise "Identomic HTTP #{response.code}" unless %w[200 201].include?(response.code)
  JSON.parse(response.body)
end

Rust

Enable the reqwest json feature and add serde_json. Reuse the client in your service.

use reqwest::{redirect::Policy, Client, StatusCode};
use serde_json::{json, Value};
use std::{env, error::Error, time::Duration};

async fn create_session(module: &str, operation_id: &str) -> Result<Value, Box<dyn Error>> {
    let base = env::var("IDENTOMIC_SDK_URL")?;
    let client = Client::builder()
        .timeout(Duration::from_secs(15))
        .redirect(Policy::none())
        .build()?;
    let response = client.post(format!("{}/sessions", base.trim_end_matches('/')))
        .bearer_auth(env::var("IDENTOMIC_SECRET_KEY")?)
        .json(&json!({"module": module, "idempotencyKey": operation_id}))
        .send().await?;
    if !matches!(response.status(), StatusCode::OK | StatusCode::CREATED) {
        return Err(format!("Identomic HTTP {}", response.status()).into());
    }
    Ok(response.json().await?)
}

Other server languages

Use a trusted HTTPS client with redirects disabled, TLS verification enabled, explicit timeouts, and status-aware retry handling. Keep the same request schema and idempotency rules. For outcome reporting, send the original sessionId and final outcome to POST /outcomes using an outcome-scoped secret. Web and backend clients can authorize mobile operations. Capture itself is performed by a supported mobile SDK.