Skip to content

Code Examples for Migration

Authentication

Login
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
using System.Text.Json;
using System.Net;

var baseUrl = "http://dev-api.v2.areal.ai/api/v2";

// 0. Login - details in Authentication section
var loginData = new
{
    username = "test@areal.ai",
    password = "test123"
};

var handler = new HttpClientHandler
{
    UseCookies = true,
    CookieContainer = new CookieContainer()
};
var client = new HttpClient(handler);

var loginContent = new StringContent(
    JsonSerializer.Serialize(loginData),
    Encoding.UTF8,
    "application/json"
);

var loginResponse = await client.PostAsync($"{baseUrl}/accounts/login/", loginContent);
loginResponse.EnsureSuccessStatusCode();

// Cookies (access_token and refresh_token) are automatically stored in handler.CookieContainer
// This client is now authenticated for the duration of access_token
// after that you can refresh it using the /accounts/refresh endpoint
Login
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.CookieManager;
import java.net.CookieHandler;
import java.net.HttpCookie;
import java.nio.charset.StandardCharsets;

public class Login {
    public static void main(String[] args) throws Exception {
        String baseUrl = "http://dev-api.v2.areal.ai/api/v2";

        // 0. Login - details in Authentication section
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);

        URL url = new URL(baseUrl + "/accounts/login/");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        String loginData = "{\"username\":\"test@areal.ai\",\"password\":\"test123\"}";

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = loginData.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Cookies are automatically stored in the CookieManager
            // this client is now authenticated for the duration of access_token
            // after that you can refresh it using the /accounts/refresh endpoint
        }

        connection.disconnect();
    }
}
Login
import requests

BASE_URL = 'http://dev-api.v2.areal.ai/api/v2'

# 0. Login - details in Authentication section
login_response = requests.post(f'{BASE_URL}/accounts/login/', {
    'username': 'test@areal.ai',
    'password': 'test123',
})
client = requests.Session()
client.cookies.update(
    {
        'access_token': login_response.cookies['access_token'],
        'refresh_token': login_response.cookies['refresh_token'],
    }
)
# this client is now authenticated for the duration of access_token
# after that you can refresh it using the /accounts/refresh endpoint

Document Processing

Start Processing
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
using System.Text.Json;
using System.IO;
using System.Collections.Generic;
using System.Linq;

var basePath = Directory.GetCurrentDirectory();
var baseUrl = "http://dev-api.v2.areal.ai/api/v2";

// 0. Login - details in Authentication section
// See code_samples/auth/c#/login.cs for authentication

var handler = new HttpClientHandler();
var client = new HttpClient(handler);
// Assume client is already authenticated with cookies from login

// 1. Get Pre-Signed URL's for a secure & fast upload channel
var fileNames = new[] { "sample.pdf" };
var presignedUrlRequest = new
{
    file_names = fileNames
};

var presignedUrlContent = new StringContent(
    JsonSerializer.Serialize(presignedUrlRequest),
    Encoding.UTF8,
    "application/json"
);

var presignedUrlResponse = await client.PostAsync($"{baseUrl}/processing/presigned_url/", presignedUrlContent);
presignedUrlResponse.EnsureSuccessStatusCode();

var presignedUrlResponseJson = await presignedUrlResponse.Content.ReadAsStringAsync();
var presignedUrlData = JsonSerializer.Deserialize<JsonElement>(presignedUrlResponseJson);

// 2. Upload to your PDF's to the PreSignedURL's
var presignedUrls = presignedUrlData.GetProperty("presigned_urls").EnumerateArray();
var uploadSessionId = presignedUrlData.GetProperty("upload_session_id").GetString();

foreach (var (fileName, presignedUrl) in fileNames.Zip(presignedUrls))
{
    var url = presignedUrl.GetProperty("url").GetString();
    var documentId = presignedUrl.GetProperty("document_id").GetString();
    var fields = presignedUrl.GetProperty("fields");

    using var uploadClient = new HttpClient();
    var formData = new MultipartFormDataContent();

    // Add fields from presigned URL
    foreach (var field in fields.EnumerateObject())
    {
        formData.Add(new StringContent(field.Value.GetString()), field.Name);
    }

    // Add file
    var fileBytes = await File.ReadAllBytesAsync(Path.Combine(basePath, fileName));
    formData.Add(new ByteArrayContent(fileBytes), "file", fileName);

    // 2. Upload to your PDF's to the PreSignedURL's
    var uploadResponse = await uploadClient.PostAsync(url, formData);
    uploadResponse.EnsureSuccessStatusCode();

    // 3. Start processing flow
    var processRequest = new
    {
        upload_session_id = uploadSessionId,
        document_id = documentId,
        file_name = fileName
    };

    var processContent = new StringContent(
        JsonSerializer.Serialize(processRequest),
        Encoding.UTF8,
        "application/json"
    );

    var processResponse = await client.PostAsync($"{baseUrl}/processing/upload/", processContent);
    processResponse.EnsureSuccessStatusCode();
}
Start Processing
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.net.CookieManager;
import java.net.CookieHandler;
import java.nio.charset.StandardCharsets;
import org.json.JSONObject;
import org.json.JSONArray;

public class StartProcessing {
    public static void main(String[] args) throws Exception {
        String basePath = System.getProperty("user.dir");
        String baseUrl = "http://dev-api.v2.areal.ai/api/v2";

        // 0. Login - details in Authentication section
        // See code_samples/auth/java/login.java for authentication
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);

        // Assume client is already authenticated with cookies from login
        // For this example, we'll create a helper method to make authenticated requests

        // 1. Get Pre-Signed URL's for a secure & fast upload channel
        String[] fileNames = {"sample.pdf"};

        JSONObject presignedUrlRequest = new JSONObject();
        JSONArray fileNamesArray = new JSONArray();
        for (String fileName : fileNames) {
            fileNamesArray.put(fileName);
        }
        presignedUrlRequest.put("file_names", fileNamesArray);

        JSONObject presignedUrlResponse = makeAuthenticatedRequest(
            baseUrl + "/processing/presigned_url/",
            "POST",
            presignedUrlRequest.toString()
        );

        String uploadSessionId = presignedUrlResponse.getString("upload_session_id");
        JSONArray presignedUrls = presignedUrlResponse.getJSONArray("presigned_urls");

        for (int i = 0; i < fileNames.length; i++) {
            String fileName = fileNames[i];
            JSONObject presignedUrl = presignedUrls.getJSONObject(i);

            String url = presignedUrl.getString("url");
            String documentId = presignedUrl.getString("document_id");
            JSONObject fields = presignedUrl.getJSONObject("fields");

            // 2. Upload to your PDF's to the PreSignedURL's
            uploadToPresignedUrl(url, fields, Paths.get(basePath, fileName).toString());

            // 3. Start processing flow
            JSONObject processRequest = new JSONObject();
            processRequest.put("upload_session_id", uploadSessionId);
            processRequest.put("document_id", documentId);
            processRequest.put("file_name", fileName);

            JSONObject processResponse = makeAuthenticatedRequest(
                baseUrl + "/processing/upload/",
                "POST",
                processRequest.toString()
            );
        }
    }

    private static JSONObject makeAuthenticatedRequest(String urlString, String method, String body) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        // Cookies are automatically handled by CookieManager
        if (body != null) {
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = body.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return new JSONObject(response.toString());
            }
        }

        connection.disconnect();
        return null;
    }

    private static void uploadToPresignedUrl(String urlString, JSONObject fields, String filePath) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (OutputStream os = connection.getOutputStream();
             PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8), true)) {

            // Add fields
            for (String key : fields.keySet()) {
                writer.append("--").append(boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n");
                writer.append("\r\n");
                writer.append(fields.getString(key)).append("\r\n");
            }

            // Add file
            writer.append("--").append(boundary).append("\r\n");
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(Paths.get(filePath).getFileName()).append("\"\r\n");
            writer.append("Content-Type: application/pdf\r\n");
            writer.append("\r\n");
            writer.flush();

            Files.copy(Paths.get(filePath), os);

            writer.append("\r\n");
            writer.append("--").append(boundary).append("--\r\n");
        }

        int responseCode = connection.getResponseCode();
        connection.disconnect();
    }
}
Start Processing
import requests
from pathlib import Path

BASE_PATH = Path(__file__).parent
BASE_URL = 'http://dev-api.v2.areal.ai/api/v2'

# 0. Login - details in Authentication section
...

# 1. Get Pre-Signed URL's for a secure & fast upload channel
file_names = ['sample.pdf']
presigned_url_response = client.post(
    f'{BASE_URL}/processing/presigned_url/',
    # NOTE: you can upload to an existing session by passing the upload_session_id
    # but we recommend creating a new session for each loan
    # params={'upload_session_id': upload_session_id},
    json={'file_names': file_names},
).json()

# 2. Upload to your PDF's to the PreSignedURL's
for file_name, presigned_url in zip(
    file_names, presigned_url_response['presigned_urls']
):
    upload_response = requests.post(
        presigned_url['url'],
        data=presigned_url['fields'],
        files={'file': (BASE_PATH / file_name).read_bytes()},
    )

    # 3. Start processing flow
    process_response = client.post(
        f'{BASE_URL}/processing/upload/',
        json={
            'upload_session_id': presigned_url_response['upload_session_id'],
            'document_id': presigned_url['document_id'],
            'file_name': file_name,
        },
    )