Go for Uploading Documents in Rossum API

This Go code shows how to upload a document automatically using Rossum API to a particular Rossum queue.

This Go code demonstrates how to upload a document using Rossum API to a particular Rossum queue. Set the options at the beginning of the script – they store your credentials, and also the identifier of the queue to upload in. You can find out the queue id by looking at your main screen URL, it is the number 12345 in https://elis.rossum.ai/annotations/12345.

See the reference API documentation for more details about how to use the upload API.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "mime/multipart"
    "net/http"
    "os"
    "path"
)

type LoginResponse struct {
    Key string `json:"key"`
}

func main() {
    username := "[email protected]"
    password := "secret_password"
    queueId := "12345"
    filePath := "/path/to/invoice.pdf"
    
    authToken := authorize(username, password)
    result := upload(queueId, filePath, authToken)

    log.Println(result)
}

func authorize(username string, password string) string {
    credentials := map[string]interface{}{
        "username": username,
        "password": password,
    }

    credentialsBytes, err := json.Marshal(credentials)
    if err != nil {
        log.Fatalln(err)
    }

    response, err := http.Post(
        "https://api.elis.rossum.ai/v1/auth/login",
        "application/json",
        bytes.NewBuffer(credentialsBytes))
    if err != nil {
        log.Fatalln(err)
    }

    loginResponse := LoginResponse{}

    json.NewDecoder(response.Body).Decode(&loginResponse)

    return loginResponse.Key
}

func upload(queueId string, filePath string, authToken string) string {
    // make request body
    file, err := os.Open(filePath)
    if err != nil {
        log.Fatalln(err)
    }
    defer file.Close()

    var requestBody bytes.Buffer

    multiPartWriter := multipart.NewWriter(&requestBody)
    fileName := path.Base(filePath)
    fileWriter, err := multiPartWriter.CreateFormFile("content", fileName)
    if err != nil {
        log.Fatalln(err)
    }

    _, err = io.Copy(fileWriter, file)
    if err != nil {
        log.Fatalln(err)
    }

    multiPartWriter.Close()

    // make request
    
    url := fmt.Sprintf("https://api.elis.rossum.ai/v1/queues/%s/upload", queueId)
    req, err := http.NewRequest("POST", url, &requestBody)
    if err != nil {
        log.Fatalln(err)
    }

    req.Header.Set("Content-Type", multiPartWriter.FormDataContentType())    
    req.Header.Set("Authorization", fmt.Sprintf("token %s", authToken))

    // perform the request and process the response
    
    client := &http.Client{}
    response, err := client.Do(req)
    if err != nil {
        log.Fatalln(err)
    }

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatalln(err)
    }

    return string(body)
}