Skip to navigation

Rust SDK

Learn how to integrate the Brevo API into your Rust applications.
View as Markdown

Overview

The Brevo Rust SDK (brevo-rust) is a typed client library for the Brevo API. It provides:

  • A unified BrevoClient with one namespaced client per API area, such as transactional_emails and contacts
  • Typed request and response structs
  • A typed ApiError for every documented error status
  • Automatic retries with exponential backoff
  • Per-request overrides through RequestOptions
  • A custom reqwest client option for proxies and TLS settings

crates.io

Requirements

  • Rust 2021 edition
  • An async runtime such as tokio, which the examples use

The SDK uses reqwest with rustls for TLS, so it needs no system OpenSSL.

Installation

cargo add brevo-rust

Import the crate as brevo_rust:

use brevo_rust::prelude::*;

Authentication

The Rust SDK authenticates with your Brevo API key, which it sends in the api-key request header. OAuth 2.0 machine-to-machine authentication is not supported in the Rust SDK yet; use an API key.

use brevo_rust::prelude::*;
let config = ClientConfig {
api_key: Some(std::env::var("BREVO_API_KEY").expect("BREVO_API_KEY not set")),
..Default::default()
};
let client = BrevoClient::new(config).expect("Failed to build client");

You can override the key for a single call with RequestOptions::new().api_key("...").

Quick start

Initialize the client and send your first email:

src/main.rs
use brevo_rust::prelude::*;
#[tokio::main]
async fn main() {
let config = ClientConfig {
api_key: Some("your-api-key".to_string()),
..Default::default()
};
let client = BrevoClient::new(config).expect("Failed to build client");
let result = client
.transactional_emails
.send_transac_email(
&SendTransacEmailRequest {
subject: Some("Hello from Brevo!".to_string()),
html_content: Some(
"<html><body><p>Hello,</p><p>This is my first transactional email.</p></body></html>"
.to_string(),
),
sender: Some(SendTransacEmailRequestSender {
name: Some("Alex from Brevo".to_string()),
email: Some("hello@brevo.com".to_string()),
..Default::default()
}),
to: Some(vec![SendTransacEmailRequestToItem {
email: "johndoe@example.com".to_string(),
name: Some("John Doe".to_string()),
..Default::default()
}]),
..Default::default()
},
None,
)
.await;
match result {
Ok(response) => println!("Sent: {:?}", response),
Err(ApiError::UnauthorizedError { message, .. }) => eprintln!("Check your API key: {message}"),
Err(ApiError::TooManyRequestsError { message, .. }) => eprintln!("Rate limited: {message}"),
Err(e) => eprintln!("Request failed: {e}"),
}
}

Every method takes a request struct (when the endpoint has a body or parameters) and an Option<RequestOptions>, and returns Result<T, ApiError>. Request structs implement Default, so you set only the fields you need.

Configuration

ClientConfig configures the client. Build one directly, as in the examples above, or use ApiClientBuilder:

use brevo_rust::ApiClientBuilder;
use std::time::Duration;
let client = ApiClientBuilder::new("https://api.brevo.com/v3")
.api_key("your-api-key")
.timeout(Duration::from_secs(30))
.max_retries(5)
.build()
.expect("Failed to build client");

Client configuration fields

FieldTypeDefaultDescription
api_keyOption<String>NoneYour Brevo API key
base_urlStringhttps://api.brevo.com/v3API base URL
timeoutDuration60 secondsDefault request timeout
max_retriesu323Default number of retries
custom_headersHashMap<String, String>SDK identification headersExtra headers sent with every request
user_agentStringbrevo-rust/<version>User-Agent header
reqwest_clientOption<reqwest::Client>NoneYour own reqwest client (see Custom HTTP client)

ClientConfig also has fields for other credential types. They are not used by this SDK yet; authenticate with api_key.

Error handling

Every method returns Result<T, ApiError>. Match on the variants you care about and handle the rest with a catch-all arm, as in the quick start.

Error variants

VariantWhen it happens
BadRequestError, UnauthorizedError, PaymentRequiredError, ForbiddenError, NotFoundError, MethodNotAllowedError, ConflictError, PreconditionFailedError, UnsupportedMediaTypeError, ExpectationFailedError, UnprocessableEntityError, FailedDependencyError, TooEarlyError, TooManyRequestsError, InternalServerErrorThe API returned the corresponding HTTP error status. Each carries the API’s message and any extra fields it documents.
Http { status, message }The API returned an error status that has no dedicated variant
NetworkThe request failed before a response arrived (connection or timeout error)
SerializationA request or response body could not be converted to or from JSON
ConfigurationThe client was built with an invalid configuration
InvalidHeaderA header value was not valid

The full list is in the crate’s error.rs, on docs.rs.

Retries

The SDK retries failed requests automatically, up to 3 times by default. It retries when:

  • The API returns 408, 429, or any status 500 or above
  • The request fails with a network error

The wait between attempts doubles each time, starting at 100 ms. Any other status, such as 400 or 404, is returned immediately without retrying. Set the number of retries on the client with max_retries, or for a single call with RequestOptions:

let response = client
.transactional_emails
.send_transac_email(&request, Some(RequestOptions::new().max_retries(5)))
.await;

Set max_retries to 0 to turn retries off.

Timeouts

Requests time out after 60 seconds by default. Change the default on the client with timeout, or for a single call:

let response = client
.transactional_emails
.send_transac_email(&request, Some(RequestOptions::new().timeout_seconds(30)))
.await;

Request options

RequestOptions customizes a single call. Besides max_retries and timeout_seconds, you can:

let options = RequestOptions::new()
.api_key("another-api-key")
.additional_header("X-My-Header", "value")
.additional_query_param("debug", "true");

additional_body_param adds a property to the request body in the same way.

Custom HTTP client

Provide your own reqwest::Client to control proxies, TLS roots or connection settings. When set, it owns all transport-level configuration:

use brevo_rust::ApiClientBuilder;
let http = reqwest::Client::builder().build().expect("reqwest client");
let client = ApiClientBuilder::new("https://api.brevo.com/v3")
.api_key("your-api-key")
.reqwest_client(http)
.build()
.expect("Failed to build client");

Available services

BrevoClient exposes the following service namespaces:

PropertyDescription
transactional_emailsSend emails, manage templates, blocked contacts and domains
transactional_smsSend SMS messages and view delivery statistics
transactional_whats_appSend WhatsApp messages and view event reports
sms_templatesList SMS templates
contactsManage contacts, lists, folders, attributes and segments
consent_groupsManage consent groups
email_campaignsCreate and manage email marketing campaigns
sms_campaignsCreate and manage SMS marketing campaigns
whats_app_campaignsCreate and manage WhatsApp campaigns and templates
companiesManage CRM companies
dealsManage CRM deals and pipelines
tasksManage CRM tasks
notesManage CRM notes
filesUpload and manage CRM files
conversationsManage conversation messages and automated messages
ecommerceManage products, categories, orders and attribution
couponsManage coupon collections and coupons
paymentsCreate and manage payment requests
eventTrack custom events
webhooksManage webhooks
sendersManage senders and IPs
domainsManage and authenticate domains
accountRetrieve account information and activity logs
inbound_parsingRetrieve inbound email events and attachments
custom_objectsManage custom object records
external_feedsManage external RSS feeds
master_accountManage sub-accounts and groups (enterprise)
userManage users and permissions
processRetrieve background process status
programManage loyalty programs
balanceManage loyalty balances and transactions
rewardManage loyalty rewards and vouchers
tierManage loyalty tiers and tier groups
walletGet wallet pass install URLs and redeem wallet passes

Every method and its request and response types are listed in the reference.

Resources