Go SDK
Official Go SDK for LeapOCR - Type-safe client with idiomatic API
Go SDK
Official Go SDK for LeapOCR - Transform documents into structured data using AI-powered OCR.
Installation
go get github.com/leapocr/leapocr-goPrerequisites
- Go 1.21 or higher
- LeapOCR API key (sign up here)
Quick Start
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/leapocr/leapocr-go"
)
func main() {
// Initialize the SDK
client, err := ocr.New(os.Getenv("LEAPOCR_API_KEY"))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
// Submit a document for processing
job, err := client.ProcessURL(ctx,
"https://example.com/document.pdf",
ocr.WithFormat(ocr.FormatStructured),
ocr.WithInstructions("Extract invoice number, date, and total amount"),
)
if err != nil {
log.Fatal(err)
}
// Wait for processing to complete
result, err := client.WaitUntilDone(ctx, job.ID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Extracted data: %+v\n", result.Data)
// Delete the job
if err := client.DeleteJob(ctx, job.ID); err != nil {
log.Printf("Failed to delete job: %v", err)
}
}New to LeapOCR? Check out the Getting Started guide for a complete walkthrough.
Key Features
- Idiomatic Go API - Clean, type-safe interface following Go best practices
- Context Support - Full context.Context integration for timeouts and cancellation
- Built-in Retry Logic - Automatic handling of transient failures
- Zero Dependencies - Minimal external dependencies for easy integration
- Strongly Typed - Compile-time type checking for all operations
For models, formats, and schemas, see Core Concepts.
Usage Examples
Processing from URL
ctx := context.Background()
job, err := client.ProcessURL(ctx,
"https://example.com/invoice.pdf",
ocr.WithFormat(ocr.FormatStructured),
ocr.WithModel(ocr.ModelStandardV1),
ocr.WithInstructions("Extract invoice number, date, and total amount"),
)
if err != nil {
log.Fatal(err)
}
result, err := client.WaitUntilDone(ctx, job.ID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Processing completed in %v\n", result.Duration)
fmt.Printf("Credits used: %d\n", result.Credits)
fmt.Printf("Data: %+v\n", result.Data)Processing Local Files
file, err := os.Open("invoice.pdf")
if err != nil {
log.Fatal(err)
}
defer file.Close()
job, err := client.ProcessFile(ctx, file, "invoice.pdf",
ocr.WithFormat(ocr.FormatStructured),
ocr.WithModel(ocr.ModelProV1),
ocr.WithSchema(map[string]interface{}{
"invoice_number": "string",
"total_amount": "number",
"invoice_date": "string",
"vendor_name": "string",
}),
)
if err != nil {
log.Fatal(err)
}
result, err := client.WaitUntilDone(ctx, job.ID)Custom Schema Extraction
See the Custom Schemas guide for detailed schema design patterns.
schema := map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"patient_name": map[string]string{"type": "string"},
"date_of_birth": map[string]string{"type": "string"},
"medications": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]string{"type": "string"},
"dosage": map[string]string{"type": "string"},
},
},
},
},
}
job, err := client.ProcessURL(ctx, "https://example.com/medical-record.pdf",
ocr.WithFormat(ocr.FormatStructured),
ocr.WithSchema(schema),
)Monitoring Job Progress
// Poll for status updates
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
status, err := client.GetJobStatus(ctx, job.ID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Status: %s (%.1f%% complete)\n", status.Status, status.Progress*100)
if status.Status == "completed" {
result, _ := client.GetJobResult(ctx, job.ID)
fmt.Println("Processing complete!", result)
break
}
if status.Status == "failed" {
log.Fatal("Processing failed")
}
<-ticker.C
}Using Templates
Use pre-configured templates for common document types. Templates include predefined schemas, instructions, and model settings:
// Use a template by its slug
job, err := client.ProcessFile(ctx, file, "invoice.pdf",
ocr.WithTemplateSlug("invoice-extraction"),
)
if err != nil {
log.Fatal(err)
}
result, err := client.WaitUntilDone(ctx, job.ID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Extracted data: %+v\n", result.Data)
// Delete after processing
if err := client.DeleteJob(ctx, job.ID); err != nil {
log.Printf("Failed to delete job: %v", err)
}Common template use cases:
- Invoice extraction
- Receipt processing
- Medical records
- Identity documents
- Custom organizational templates
Deleting Jobs
All jobs are automatically deleted after 7 days. Delete jobs immediately after processing to remove sensitive data:
// Process and delete
job, err := client.ProcessURL(ctx, "https://example.com/document.pdf",
ocr.WithFormat(ocr.FormatStructured),
)
if err != nil {
log.Fatal(err)
}
result, err := client.WaitUntilDone(ctx, job.ID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Extracted data: %+v\n", result.Data)
// Delete immediately
if err := client.DeleteJob(ctx, job.ID); err != nil {
log.Printf("Failed to delete job: %v", err)
}Configuration
Custom Configuration
config := &ocr.Config{
APIKey: "your-api-key",
BaseURL: "https://api.leapocr.com",
HTTPClient: &http.Client{Timeout: 60 * time.Second},
UserAgent: "my-app/1.0",
Timeout: 30 * time.Second,
}
client, err := ocr.NewSDK(config)
if err != nil {
log.Fatal(err)
}Environment Variables
export LEAPOCR_API_KEY="your-api-key"
export OCR_BASE_URL="https://api.leapocr.com" # optionalError Handling
The SDK provides typed errors for robust error handling:
result, err := client.WaitUntilDone(ctx, job.ID)
if err != nil {
if sdkErr, ok := err.(*ocr.SDKError); ok {
switch sdkErr.Type {
case ocr.ErrorTypeAuth:
log.Fatal("Authentication failed - check your API key")
case ocr.ErrorTypeValidation:
log.Printf("Validation error: %s", sdkErr.Message)
case ocr.ErrorTypeNetwork:
if sdkErr.IsRetryable() {
// Retry the operation
}
case ocr.ErrorTypeProcessing:
log.Printf("Processing failed: %s", sdkErr.Message)
}
}
log.Fatal(err)
}Error Types
ErrorTypeInvalidConfig- Configuration errorsErrorTypeAuth- Authentication failuresErrorTypeValidation- Input validation errorsErrorTypeNetwork- Network/connectivity issues (retryable)ErrorTypeProcessing- Document processing errorsErrorTypeTimeout- Operation timeouts
See the Troubleshooting Guide for common issues and solutions.
API Reference
Full API documentation is available at pkg.go.dev/github.com/leapocr/leapocr-go.
Core Methods
// Initialize SDK
New(apiKey string) (*SDK, error)
NewSDK(config *Config) (*SDK, error)
// Process documents
ProcessURL(ctx context.Context, url string, opts ...ProcessingOption) (*Job, error)
ProcessFile(ctx context.Context, file io.Reader, filename string, opts ...ProcessingOption) (*Job, error)
// Job management
GetJobStatus(ctx context.Context, jobID string) (*JobStatus, error)
GetJobResult(ctx context.Context, jobID string) (*OCRResult, error)
WaitUntilDone(ctx context.Context, jobID string) (*OCRResult, error)
DeleteJob(ctx context.Context, jobID string) errorProcessing Options
WithFormat(format Format) // Set output format
WithModel(model Model) // Set OCR model
WithModelString(model string) // Set custom model
WithSchema(schema map[string]interface{}) // Define extraction schema
WithInstructions(instructions string) // Add processing instructions
WithTemplateSlug(templateSlug string) // Set document template slugModels and Formats
// Available models
const (
ModelStandardV1 Model = "standard-v1"
ModelEnglishProV1 Model = "english-pro-v1"
ModelProV1 Model = "pro-v1"
)
// Available formats
const (
FormatStructured Format = "structured"
FormatMarkdown Format = "markdown"
FormatPerPageStructured Format = "per_page_structured"
)Next Steps
- Explore Common Use Cases for real-world examples
- Learn about Processing Models
- Review Custom Schemas for structured extraction
- Check the FAQ for common questions
Resources
- API Reference: pkg.go.dev/github.com/leapocr/leapocr-go
- GitHub: github.com/leapocr/leapocr-go
- Issues: GitHub Issues