Python SDK

Learn how to integrate the Brevo API into your Python applications

Overview

The Brevo Python SDK provides a fully typed client library for interacting with the Brevo API. It offers Pydantic-based models, automatic retries, native async support, and comprehensive error handling.

Version 4.0 PyPI downloads

Version 4.0 of the Python SDK has been released with significant improvements:

The legacy v1.x SDK (brevo-python < 4.0) will continue to receive critical security updates but no new features. We recommend migrating to v4.x for new projects and existing applications.

  • Native async support with AsyncBrevo
  • Pydantic-based typed models with full type annotations
  • Automatic retries with exponential backoff
  • Raw response access with headers and status codes
  • Custom httpx client support for proxies and mTLS
  • Configurable logging

Installation

Install the SDK using pip:

$pip install brevo-python

Quick start

Initialize the client and send your first email:

quick_start.py
1from brevo import Brevo
2
3client = Brevo(api_key="your-api-key")
4
5result = client.transactional_emails.send_transac_email(
6 subject="Hello",
7 text_content="Hello world!",
8 sender={"name": "Sender", "email": "sender@brevo.com"},
9 to=[{"email": "recipient@example.com"}],
10)
11
12print("Email sent:", result)

Configuration

Configure the client with custom timeout and HTTP settings:

configuration.py
1from brevo import Brevo
2
3client = Brevo(
4 api_key="your-api-key",
5 timeout=30.0, # 30 seconds
6 follow_redirects=True, # Default: True
7)

Constructor parameters

ParameterTypeDefaultDescription
api_keystrRequiredYour Brevo API key
timeoutfloat60.0Request timeout in seconds
base_urlstrNoneOverride the default API base URL
follow_redirectsboolTrueFollow HTTP redirects
httpx_clienthttpx.ClientNoneCustom httpx client instance
headersdictNoneAdditional default headers
loggingLogConfigNoneLogging configuration

Async client

The SDK exports an AsyncBrevo client for non-blocking calls. Use httpx.AsyncClient if passing a custom HTTP client.

async_client.py
1import asyncio
2from brevo import AsyncBrevo
3
4client = AsyncBrevo(api_key="your-api-key")
5
6async def main() -> None:
7 result = await client.transactional_emails.send_transac_email(
8 subject="Hello",
9 text_content="Hello world!",
10 sender={"name": "Sender", "email": "sender@brevo.com"},
11 to=[{"email": "recipient@example.com"}],
12 )
13 print("Email sent:", result)
14
15asyncio.run(main())

Error handling

The SDK raises ApiError (or a specific subclass) for non-success HTTP status codes:

error_handling.py
1from brevo import Brevo
2from brevo.errors import (
3 ApiError,
4 UnauthorizedError,
5 TooManyRequestsError,
6)
7
8client = Brevo(api_key="your-api-key")
9
10try:
11 client.transactional_emails.send_transac_email(
12 subject="Hello",
13 text_content="Hello world!",
14 sender={"name": "Sender", "email": "sender@brevo.com"},
15 to=[{"email": "recipient@example.com"}],
16 )
17except UnauthorizedError as e:
18 print("Invalid API key")
19except TooManyRequestsError as e:
20 print(f"Rate limited: {e.body}")
21except ApiError as e:
22 print(f"API Error {e.status_code}: {e.body}")

Error types

The SDK provides the following error types:

  • 400 - BadRequestError
  • 401 - UnauthorizedError
  • 402 - PaymentRequiredError
  • 403 - ForbiddenError
  • 404 - NotFoundError
  • 405 - MethodNotAllowedError
  • 409 - ConflictError
  • 412 - PreconditionFailedError
  • 415 - UnsupportedMediaTypeError
  • 417 - ExpectationFailedError
  • 422 - UnprocessableEntityError
  • 424 - FailedDependencyError
  • 425 - TooEarlyError
  • 429 - TooManyRequestsError
  • 500 - InternalServerError

All ApiError instances provide:

  • status_code: HTTP status code
  • body: Parsed error response body
  • headers: Response headers

Retries

Automatic retries with exponential backoff are enabled by default (2 retries). Configure retries at the client or request level:

retries.py
1from brevo import Brevo
2
3client = Brevo(api_key="your-api-key")
4
5# Request-level configuration
6client.transactional_emails.send_transac_email(
7 subject="Hello",
8 text_content="Hello world!",
9 sender={"name": "Sender", "email": "sender@brevo.com"},
10 to=[{"email": "recipient@example.com"}],
11 request_options={"max_retries": 5},
12)

Retry behavior

  • Retryable status codes: 408, 429, 5xx
  • Exponential backoff with jitter
  • Can be disabled per request with max_retries: 0

Timeouts

Default timeout is 60 seconds. Configure at client or request level:

timeouts.py
1from brevo import Brevo
2
3# Client-level timeout
4client = Brevo(
5 api_key="your-api-key",
6 timeout=30.0,
7)
8
9# Request-level timeout
10client.transactional_emails.send_transac_email(
11 subject="Hello",
12 text_content="Hello world!",
13 sender={"name": "Sender", "email": "sender@brevo.com"},
14 to=[{"email": "recipient@example.com"}],
15 request_options={"timeout_in_seconds": 10},
16)
  • Standard API calls: 30-60s (default)
  • Quick operations: 10-15s
  • Bulk operations: 120-300s
  • Real-time: 5-10s

Request options

All service methods accept a request_options dictionary as the last parameter. Available options:

OptionTypeDescription
timeout_in_secondsintOverride timeout for this request
max_retriesintOverride max retries for this request
additional_headersdictMerge additional headers into the request
additional_query_parametersdictAdd query parameters to the request
additional_body_parametersdictAdd body parameters to the request
chunk_sizeintChunk size for file downloads

Additional headers

Add custom headers to requests:

custom_headers.py
1client.transactional_emails.send_transac_email(
2 subject="Hello",
3 text_content="Hello world!",
4 sender={"name": "Sender", "email": "sender@brevo.com"},
5 to=[{"email": "recipient@example.com"}],
6 request_options={
7 "additional_headers": {"X-Custom-Header": "custom-value"}
8 },
9)

Additional query parameters

Add query parameters to requests:

query_params.py
1client.transactional_emails.send_transac_email(
2 subject="Hello",
3 text_content="Hello world!",
4 sender={"name": "Sender", "email": "sender@brevo.com"},
5 to=[{"email": "recipient@example.com"}],
6 request_options={
7 "additional_query_parameters": {"custom_param": "value"}
8 },
9)

Raw response access

Access raw response headers, status codes, and parsed data via with_raw_response:

raw_response.py
1from brevo import Brevo
2
3client = Brevo(api_key="your-api-key")
4
5response = client.transactional_emails.with_raw_response.send_transac_email(
6 subject="Hello",
7 text_content="Hello world!",
8 sender={"name": "Sender", "email": "sender@brevo.com"},
9 to=[{"email": "recipient@example.com"}],
10)
11
12print(response.status_code)
13print(response.headers)
14print(response.data)

Type hints

The SDK ships with full type annotations and Pydantic-based models. All request and response types are importable from the brevo package:

type_hints.py
1from brevo import Brevo
2
3client = Brevo(api_key="your-api-key")
4
5client.transactional_emails.send_transac_email(
6 subject="First email",
7 text_content="Hello world!",
8 sender={"name": "Bob Wilson", "email": "bob.wilson@brevo.com"},
9 to=[{"email": "sarah.davis@example.com", "name": "Sarah Davis"}],
10)

Logging

Configure logging to debug API calls:

logging_config.py
1from brevo import Brevo
2
3client = Brevo(
4 api_key="your-api-key",
5 logging={
6 "level": "debug",
7 "silent": False,
8 },
9)

Custom logger

Pass a custom logger instance for integration with your preferred logging library:

custom_logger.py
1import logging
2from brevo import Brevo
3
4logger = logging.getLogger("brevo")
5logger.setLevel(logging.DEBUG)
6handler = logging.StreamHandler()
7handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(message)s"))
8logger.addHandler(handler)
9
10client = Brevo(
11 api_key="your-api-key",
12 logging={
13 "level": "debug",
14 "logger": logger,
15 },
16)

Custom HTTP client

Override the default httpx client for proxies, custom transports, or mTLS:

custom_http_client.py
1import httpx
2from brevo import Brevo
3
4client = Brevo(
5 api_key="your-api-key",
6 httpx_client=httpx.Client(
7 proxy="http://my.test.proxy.example.com",
8 transport=httpx.HTTPTransport(local_address="0.0.0.0"),
9 ),
10)

Common use cases

Use a custom async HTTP client:

1import httpx
2from brevo import AsyncBrevo
3
4client = AsyncBrevo(
5 api_key="your-api-key",
6 httpx_client=httpx.AsyncClient(
7 proxy="http://my.test.proxy.example.com",
8 ),
9)

Configure timeout and transport settings:

1import httpx
2from brevo import Brevo
3
4client = Brevo(
5 api_key="your-api-key",
6 httpx_client=httpx.Client(
7 timeout=httpx.Timeout(120.0, connect=10.0),
8 transport=httpx.HTTPTransport(retries=3),
9 ),
10)

Add custom middleware using httpx event hooks:

1import httpx
2from brevo import Brevo
3
4def log_request(request: httpx.Request) -> None:
5 print(f"Request: {request.method} {request.url}")
6
7def log_response(response: httpx.Response) -> None:
8 print(f"Response: {response.status_code}")
9
10client = Brevo(
11 api_key="your-api-key",
12 httpx_client=httpx.Client(
13 event_hooks={
14 "request": [log_request],
15 "response": [log_response],
16 }
17 ),
18)

Available services

The SDK organizes API methods into service namespaces on the client:

ServiceDescription
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
contactsManage contacts, lists, folders, attributes and segments
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)
programManage loyalty programs
balanceManage loyalty balances and transactions
rewardManage loyalty rewards and vouchers
tierManage loyalty tiers and tier groups

Requirements

  • Python 3.8+
  • httpx >= 0.21.2
  • pydantic >= 1.9.2
  • typing_extensions >= 4.0.0

Migration from v1.x

Version 4.0 includes breaking changes. For the full migration guide, see the GitHub migration reference.

Key changes

  • New client initialization via single Brevo(api_key="...") entry point
  • Native async support with AsyncBrevo
  • Pydantic-based typed models
  • Automatic retries with exponential backoff
  • httpx replaces urllib3

Migration example

1# v1.x
2import brevo_python
3from brevo_python.rest import ApiException
4
5configuration = brevo_python.Configuration()
6configuration.api_key['api-key'] = 'YOUR_API_KEY'
7
8api_instance = brevo_python.AccountApi(
9 brevo_python.ApiClient(configuration)
10)
11api_response = api_instance.get_account()

Migration summary

Areav1.x (brevo_python)v4.x (brevo)
Moduleimport brevo_pythonfrom brevo import Brevo
ClientAccountApi(ApiClient(config))Brevo(api_key="...")
ConfigConfiguration() + api_key['api-key']Constructor parameter api_key
ErrorsApiExceptionApiError with .status_code, .body
HTTPurllib3httpx
AsyncNot availableAsyncBrevo
RetriesNot built-inAutomatic with exponential backoff
TimeoutsManual60s default, configurable
Python2.7, 3.4+3.8+
Buildsetup.pypyproject.toml (Poetry)

Resources