Crate spiris

Crate spiris 

Source
Expand description

§Spiris Bokföring och Fakturering API Client for Rust

This crate provides a Rust client for the Spiris Bokföring och Fakturering API (formerly Visma eAccounting).

§Features

  • OAuth2 Authentication: Complete OAuth2 flow support with token refresh
  • Type-safe API: Strongly typed request/response models
  • Async/Await: Built on tokio and reqwest for async operations
  • Automatic Retries: Exponential backoff for transient failures
  • Request Tracing: Built-in logging support with tracing
  • Rate Limiting: Automatic handling of API rate limits
  • Comprehensive Coverage: Support for customers, invoices, articles, and more

§Quick Start

use spiris::{Client, AccessToken};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create an access token (usually obtained via OAuth2)
    let token = AccessToken::new("your_access_token".to_string(), 3600, None);

    // Create the API client
    let client = Client::new(token);

    // List customers
    let customers = client.customers().list(None).await?;
    println!("Found {} customers", customers.data.len());

    Ok(())
}

§OAuth2 Authentication

use spiris::auth::{OAuth2Config, OAuth2Handler};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = OAuth2Config::new(
        "your_client_id".to_string(),
        "your_client_secret".to_string(),
        "http://localhost:8080/callback".to_string(),
    );

    let handler = OAuth2Handler::new(config)?;

    // Get authorization URL
    let (auth_url, csrf_token, pkce_verifier) = handler.authorize_url();
    println!("Visit this URL to authorize: {}", auth_url);

    // After user authorizes and you receive the code...
    // let token = handler.exchange_code(code, pkce_verifier).await?;

    Ok(())
}

§Working with Customers

use spiris::{Client, AccessToken, Customer, PaginationParams};

// Create a new customer
let new_customer = Customer {
    name: Some("Acme Corporation".to_string()),
    email: Some("contact@acme.com".to_string()),
    phone: Some("+1234567890".to_string()),
    ..Default::default()
};

let created = client.customers().create(&new_customer).await?;
println!("Created customer with ID: {:?}", created.id);

// List customers with pagination
let params = PaginationParams::new().page(0).pagesize(100);
let customers = client.customers().list(Some(params)).await?;

§Creating Invoices

use spiris::{Client, AccessToken, Invoice, InvoiceRow, money};
use chrono::Utc;

let invoice = Invoice {
    customer_id: Some("customer-id-here".to_string()),
    invoice_date: Some(Utc::now()),
    rows: vec![
        InvoiceRow {
            text: Some("Consulting services".to_string()),
            unit_price: Some(money!(1000.0)),
            quantity: Some(money!(10.0)),
            ..Default::default()
        }
    ],
    ..Default::default()
};

let created_invoice = client.invoices().create(&invoice).await?;

§Advanced Configuration

use spiris::{Client, AccessToken, ClientConfig, RetryConfig};
use std::time::Duration;

let token = AccessToken::new("token".to_string(), 3600, None);

// Configure retry behavior
let retry_config = RetryConfig::new()
    .max_retries(5)
    .initial_interval(Duration::from_millis(1000));

// Create client with custom configuration
let config = ClientConfig::new()
    .timeout_seconds(60)
    .retry_config(retry_config)
    .enable_tracing(true);

let client = Client::with_config(token, config);

Re-exports§

pub use auth::AccessToken;
pub use auth::OAuth2Config;
pub use auth::OAuth2Handler;
pub use client::Client;
pub use client::ClientConfig;
pub use error::ApiErrorResponse;
pub use error::Error;
pub use error::Result;
pub use error::ValidationError;
pub use rate_limit::RateLimitConfig;
pub use retry::RetryConfig;
pub use types::Account;
pub use types::AccountBalance;
pub use types::AccountType;
pub use types::Address;
pub use types::AllocationPeriod;
pub use types::Article;
pub use types::ArticleAccountCoding;
pub use types::ArticleCreate;
pub use types::ArticleLabel;
pub use types::ArticleUpdate;
pub use types::Attachment;
pub use types::Bank;
pub use types::BankAccount;
pub use types::CompanySettings;
pub use types::ConvertDraftOptions;
pub use types::CostCenter;
pub use types::CostCenterItem;
pub use types::Country;
pub use types::Currency;
pub use types::Customer;
pub use types::CustomerCreate;
pub use types::CustomerInvoiceDraft;
pub use types::CustomerInvoiceDraftRow;
pub use types::CustomerLabel;
pub use types::CustomerLedgerItem;
pub use types::CustomerUpdate;
pub use types::DeliveryMethod;
pub use types::DeliveryTerm;
pub use types::Document;
pub use types::FiscalYear;
pub use types::ForeignPaymentCode;
pub use types::Invoice;
pub use types::InvoiceCreate;
pub use types::InvoicePayment;
pub use types::InvoiceRow;
pub use types::InvoiceRowCreate;
pub use types::InvoiceUpdate;
pub use types::Message;
pub use types::MessageThread;
pub use types::Money;
pub use types::Order;
pub use types::OrderRow;
pub use types::PaginatedResponse;
pub use types::PaginationParams;
pub use types::Project;
pub use types::QueryParams;
pub use types::Quotation;
pub use types::QuotationRow;
pub use types::ResponseMetadata;
pub use types::Supplier;
pub use types::SupplierInvoice;
pub use types::SupplierInvoiceDraft;
pub use types::SupplierInvoiceRow;
pub use types::SupplierLabel;
pub use types::SupplierLedgerItem;
pub use types::TermsOfPayment;
pub use types::Unit;
pub use types::User;
pub use types::VatCode;
pub use types::Voucher;
pub use types::VoucherRow;

Modules§

auth
OAuth2 authentication for the Spiris Bokföring och Fakturering API.
client
Core HTTP client for the Spiris Bokföring och Fakturering API.
endpoints
API endpoint modules.
error
Error types for the Visma eAccounting API client.
macros
Endpoint definition macros to reduce boilerplate.
middleware
Middleware support for request/response interception.
pagination
Pagination stream support for iterating through paginated API responses.
query
Type-safe OData filter builder for API queries.
rate_limit
Rate limiting for API requests.
retry
Retry logic with exponential backoff for API requests.
types
Common types and data models for the Visma eAccounting API.
webhooks
Webhook support for receiving event notifications.

Macros§

define_endpoint
Define an API endpoint with specified capabilities.
money
Create a Money value from a float literal.
paginated_stream
Creates a stream that automatically paginates through API responses.