Project

invoist

0.0
The project is in a healthy, maintained state
Send Invoist an invoice, receipt or bill and get its details back as data: sender, totals, tax, line items, due date and anything worth a second look. Covers business workspaces (extraction, documents, review queue, webhooks) and households (bills, what is due, held emails), with typed responses, automatic retries and webhook signature checks. Uses only Ruby's standard library.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

Invoist for Ruby

The official Ruby library for the Invoist API. Send Invoist an invoice, receipt or bill, and get its details back as data: who sent it, the totals, tax, line items, the due date, and anything worth a second look.

It uses only Ruby's standard library (Net::HTTP, JSON, OpenSSL), so it adds no other gems to your app.

Install

bundle add invoist

or gem install invoist. Ruby 3.3 or newer.

A business: read an invoice

require "invoist"

client = Invoist::Client.new(api_key: ENV.fetch("INVOIST_API_KEY"))
result = client.extract_and_wait("invoice.pdf")
puts result.extraction.vendor_name, result.extraction.total_cents, result.extraction.currency

Amounts are whole numbers of the smallest unit: total_cents: 48000 with currency: "GBP" is £480.00. There are no floats, so nothing is rounded on the way.

extract returns as soon as the file is accepted, while it is still being read; wait_for_extraction (or the extraction.completed webhook) gives you the result. A reading that failed is returned, not raised: check extraction.status and extraction.error_message.

result = client.extract(File.open("receipt.jpg", "rb"), idempotency_key: "upload-1842")
extraction = client.wait_for_extraction(result.document.id, timeout: 60)

client.list_documents(flagged: true, limit: 20).each { |doc| puts doc.original_filename }
client.list_review_queue(status: "pending")
client.get_document_file(result.document.id).save("copy.jpg")

A file can be a path, a Pathname, an open File or other IO, a file uploaded to a Rails or Rack app, or bytes: Invoist::Upload.new(bytes, filename: "invoice.pdf").

A household: what is there to pay

client = Invoist::Client.new(api_key: ENV.fetch("INVOIST_API_KEY"))
client.bills.list(paid: false, month: "2026-10").each do |bill|
  puts "#{bill.vendor_name}: #{bill.total_cents} #{bill.currency}, due #{bill.due_date}"
end
puts client.bills.summary.overdue

month takes "YYYY-MM" or a Date (a Time counts as the day it is where your program runs). There is also bills.get(id), bills.get_file(id), bills.stats(month:, sender:), bills.mark_paid(id) and bills.mark_unpaid(id) (these two need a key that may mark bills paid), and held_emails.list for emails waiting for someone to approve the sender.

Responses

Every method returns typed, immutable objects (Invoist::Models::Bill, Invoist::Models::Extraction, …) with a reader for each field, named as the API sends it. Fields the API leaves out are nil, and new fields the API adds later are ignored until you upgrade. to_h, to_json and bill[:total_cents] are there when you want plain data. Signatures for every type are in sig/ for Steep and other RBS tools.

Errors

Every failure is an Invoist::Error:

begin
  client.bills.mark_paid(bill_id)
rescue Invoist::Error => e
  e.status      # 403 (0 when no response arrived)
  e.code        # "insufficient_scope": stable, branch on this
  e.message     # for people; the wording can change
  e.request_id  # quote this to support
  e.body        # the raw response body
  e.auth_error? || e.permission_error? || e.not_found? || e.rate_limited? || e.retryable?
end

code is network_error when the API couldn't be reached, timeout when it didn't answer in time, and unexpected_response when something between you and the API (a proxy, a gateway) answered instead.

Retries and timeouts

The client retries a request up to twice when it could succeed the second time: no response, a timeout, 429 Too Many Requests, or a 5xx. It never retries another 4xx. It waits as long as the Retry-After header says, otherwise 0.5s, then 1s, … with a little randomness, at most 8s. When Retry-After asks for more than a minute, the call fails at once instead of hanging your program (e.retry_after says how long). Uploads are retried too: sending the same file twice gives back the same document.

Invoist::Client.new(
  api_key: ENV.fetch("INVOIST_API_KEY"),
  timeout: 30,       # seconds to connect, and for each read and write (default 60)
  max_retries: 5,    # 0 turns retrying off (default 2)
  base_url: "https://api.invoi.st"
)

Pass transport: (anything with call(request) -> response, see Invoist::Transport) to send requests through your own HTTP library or a test double.

Webhooks

Check every delivery's X-Invoist-Signature before trusting it. Pass the raw request body: parsing the JSON and turning it back into a string changes it, and the check fails.

Rails:

class InvoistWebhooksController < ActionController::API
  def create
    event = Invoist::Webhook.verify(request.raw_post,
                                    request.headers["X-Invoist-Signature"],
                                    ENV.fetch("INVOIST_WEBHOOK_SECRET"))
    if event.type == Invoist::Webhook::EXTRACTION_COMPLETED
      ImportInvoiceJob.perform_later(event.data["document_id"])
    end
    head :ok
  rescue Invoist::Error
    head :bad_request
  end
end

Sinatra:

post "/webhooks/invoist" do
  event = Invoist::Webhook.verify(request.body.read, request.env["HTTP_X_INVOIST_SIGNATURE"],
                                  ENV.fetch("INVOIST_WEBHOOK_SECRET"))
  logger.info("#{event.type}: #{event.data['document_id']}")
  200
rescue Invoist::Error
  400
end

Signatures older than five minutes, or more than five minutes ahead, are refused (tolerance: changes that; 0 turns it off). The event types are constants: Invoist::Webhook::DOCUMENT_CREATED, EXTRACTION_COMPLETED, EXTRACTION_FAILED, REVIEW_ITEM_CREATED, REVIEW_ITEM_RESOLVED and DOCUMENT_REQUEST_FULFILLED. To manage endpoints from code:

endpoint = client.create_webhook_endpoint(url: "https://example.com/webhooks/invoist",
                                          events: [Invoist::Webhook::EXTRACTION_COMPLETED])
endpoint.secret # shown only now: store it
client.list_webhook_endpoints.endpoints
client.delete_webhook_endpoint(endpoint.id)

Invoist::Webhook.sign(payload, secret) makes a valid header, for testing your own endpoint.

Development

bundle install
bundle exec rake            # rubocop, RBS validation and the tests
bundle exec rake generate   # rebuild lib/invoist/models.rb from openapi.yaml (INVOIST_OPENAPI=path)
gem build invoist.gemspec

Live tests run against a real API, read-only, when INVOIST_API_KEY (and optionally INVOIST_BASE_URL) is set.

Links