OCR API code examples: Python, JavaScript, C#, Java, Go and more

To read the text from an image in code, send the image to POST https://api.runemic.com/v1/ocr with your API key and read the text field of the JSON answer. You don't need an SDK. Any language that can make an HTTPS request works, and the examples below each fit on one screen.

Before you start

Sign in to the console and create an API key. New accounts get 2,500 free credits (see pricing). Each example reads the key from the RUNEMIC_API_KEY environment variable and the page from page.png. Keep the key on your server, never in a web page or an app you ship.

You can send the image in either of two ways:

  • multipart/form-data, with the image in a file field (as cURL, Python, C#, PHP and Ruby do below)
  • JSON, with the image as a base64 data: URI or a public https:// URL in an image field (as JavaScript, Java, Go and Rust do below)

Each example asks for plain text with "format": "text". Leave it out and you get Markdown, with headings, lists and tables.

cURL

curl https://api.runemic.com/v1/ocr \
  -H "Authorization: Bearer $RUNEMIC_API_KEY" \
  -F "file=@page.png" \
  -F "format=text"

Python

import os
import requests

res = requests.post(
    "https://api.runemic.com/v1/ocr",
    headers={"Authorization": f"Bearer {os.environ['RUNEMIC_API_KEY']}"},
    files={"file": open("page.png", "rb")},
    data={"format": "text"},
)
res.raise_for_status()
print(res.json()["text"])

JavaScript (Node.js 18 or later)

import { readFile } from "node:fs/promises";

const image = "data:image/png;base64," + (await readFile("page.png")).toString("base64");
const res = await fetch("https://api.runemic.com/v1/ocr", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.RUNEMIC_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ image, format: "text" }),
});
if (!res.ok) throw new Error(await res.text());
console.log((await res.json()).text);

C# (.NET 6 or later)

using System.Net.Http.Headers;
using System.Text.Json;

using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("RUNEMIC_API_KEY"));

using var form = new MultipartFormDataContent();
var image = new ByteArrayContent(await File.ReadAllBytesAsync("page.png"));
image.Headers.ContentType = new MediaTypeHeaderValue("image/png");
form.Add(image, "file", "page.png");
form.Add(new StringContent("text"), "format");

var res = await http.PostAsync("https://api.runemic.com/v1/ocr", form);
res.EnsureSuccessStatusCode();
using var json = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
Console.WriteLine(json.RootElement.GetProperty("text").GetString());

Java (11 or later)

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.util.Base64;

public class Ocr {
    public static void main(String[] args) throws Exception {
        String image = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of("page.png")));
        String body = "{\"image\": \"data:image/png;base64," + image + "\", \"format\": \"text\"}";
        HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.runemic.com/v1/ocr"))
            .header("Authorization", "Bearer " + System.getenv("RUNEMIC_API_KEY"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
        System.out.println(res.body()); // JSON: the page's text is in "text" (read it with Jackson or Gson)
    }
}

Go

package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	img, err := os.ReadFile("page.png")
	if err != nil {
		panic(err)
	}
	body, _ := json.Marshal(map[string]string{
		"image":  "data:image/png;base64," + base64.StdEncoding.EncodeToString(img),
		"format": "text",
	})
	req, _ := http.NewRequest("POST", "https://api.runemic.com/v1/ocr", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("RUNEMIC_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	var out struct {
		Text string `json:"text"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	fmt.Println(out.Text)
}

PHP

<?php
$ch = curl_init("https://api.runemic.com/v1/ocr");
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("RUNEMIC_API_KEY")],
    CURLOPT_POSTFIELDS => ["file" => new CURLFile("page.png", "image/png"), "format" => "text"],
    CURLOPT_RETURNTRANSFER => true,
]);
$res = json_decode(curl_exec($ch), true);
echo $res["text"];

Ruby

require "net/http"
require "json"

uri = URI("https://api.runemic.com/v1/ocr")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV["RUNEMIC_API_KEY"]}"
req.set_form([["file", File.open("page.png")], ["format", "text"]], "multipart/form-data")
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
puts JSON.parse(res.body)["text"]

Rust

// Cargo.toml: reqwest = { version = "0.12", features = ["blocking", "json"] }, serde_json = "1", base64 = "0.22"
use base64::Engine;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let image = base64::engine::general_purpose::STANDARD.encode(std::fs::read("page.png")?);
    let res: serde_json::Value = reqwest::blocking::Client::new()
        .post("https://api.runemic.com/v1/ocr")
        .bearer_auth(std::env::var("RUNEMIC_API_KEY")?)
        .json(&serde_json::json!({ "image": format!("data:image/png;base64,{image}"), "format": "text" }))
        .send()?
        .error_for_status()?
        .json()?;
    println!("{}", res["text"].as_str().unwrap_or(""));
    Ok(())
}

What comes back

The answer is JSON. text holds the page's text in reading order; the rest says which model read it and how many credits it used. The text keeps the page's own script and direction. A Persian page, for example, comes back right to left, with its Persian digits as printed.

A few options work the same in every language:

  • model: a model id from GET /v1/models; leave it out for the default
  • instructions: up to 300 characters of guidance, such as "Only return the table"
  • stream: true sends the text while it is being written, as server-sent events

Already using an OpenAI SDK? Point it at https://api.runemic.com/v1 with your Runemic key. Every field, error code and limit is in the API docs.

Without code

To read a single page, use the free OCR tool in your browser, with no account.

More from the blog