Mollie is transitioning to new, automatically generated SDKs.
As a part of this transition, new features will be developed exclusively for the new Python SDK. We encourage you to migrate to this version by 23 October 2026, after which the legacy SDK will enter maintenance mode and receive no further updates.
Once a Python version reaches its official end of life date, a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.
The SDK can be installed with uv, pip, or poetry package managers.
uv
uv is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities.
uv add mollie-api-py
PIP
PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install mollie-api-py
Poetry
Poetry is a modern tool that simplifies dependency management and package publishing by using a single pyproject.toml file to handle project metadata and dependencies.
poetry add mollie-api-py
Shell and script usage with uv
You can use this SDK in a Python shell with uv and the uvx command that comes with it like so:
uvx --from mollie-api-py python
It's also possible to write a standalone Python script without needing to set up a whole project like so:
Once that is saved to a file, you can run it with uv run script.py where
script.py can be replaced with the actual file name.
IDE Support
PyCharm
Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.
# Synchronous Example
import mollie
from mollie import ClientSDK
with ClientSDK() as client_sdk:
res = client_sdk.oauth.generate(security=mollie.OauthGenerateTokensSecurity(
username="",
password="",
), idempotency_key="123e4567-e89b-12d3-a456-426", request_body={
"grant_type": mollie.OauthGrantType.AUTHORIZATION_CODE,
"code": "auth_...",
"refresh_token": "refresh_...",
"redirect_uri": "https://example.com/redirect",
})
# Handle response
print(res)
The same SDK client can also be used to make asynchronous requests by importing asyncio.
# Asynchronous Example
import asyncio
import mollie
from mollie import ClientSDK
async def main():
async with ClientSDK() as client_sdk:
res = await client_sdk.oauth.generate_async(security=mollie.OauthGenerateTokensSecurity(
username="",
password="",
), idempotency_key="123e4567-e89b-12d3-a456-426", request_body={
"grant_type": mollie.OauthGrantType.AUTHORIZATION_CODE,
"code": "auth_...",
"refresh_token": "refresh_...",
"redirect_uri": "https://example.com/redirect",
})
# Handle response
print(res)
asyncio.run(main())
Authentication
Per-Client Security Schemes
This SDK supports the following security schemes globally:
Name
Type
Scheme
Environment Variable
api_key
http
HTTP Bearer
CLIENT_API_KEY
advanced_access_token
http
HTTP Bearer
CLIENT_ADVANCED_ACCESS_TOKEN
o_auth
oauth2
OAuth2 token
CLIENT_O_AUTH
You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:
import mollie
from mollie import ClientSDK
import os
with ClientSDK(
security=mollie.Security(
api_key=os.getenv("CLIENT_API_KEY"),
),
testmode=True,
) as client_sdk:
res = client_sdk.balances.list(currency="EUR", limit=50, idempotency_key="123e4567-e89b-12d3-a456-426", x_client_signature="MEUCIQDx8sJvK3z...", x_client_signed_at="2025-01-01T12:00:00Z")
while res is not None:
# Handle items
res = res.next()
Per-Operation Security Schemes
Some operations in this SDK require the security scheme to be specified at the request level. For example:
import mollie
from mollie import ClientSDK
with ClientSDK() as client_sdk:
res = client_sdk.oauth.generate(security=mollie.OauthGenerateTokensSecurity(
username="",
password="",
), idempotency_key="123e4567-e89b-12d3-a456-426", request_body={
"grant_type": mollie.OauthGrantType.AUTHORIZATION_CODE,
"code": "auth_...",
"refresh_token": "refresh_...",
"redirect_uri": "https://example.com/redirect",
})
# Handle response
print(res)
Idempotency Key
This SDK supports the usage of Idempotency Keys. See our documentation on how to use it.
import os
from mollie import ClientSDK, Security
client = ClientSDK(
security = Security(
api_key = os.getenv("CLIENT_API_KEY", "test_..."),
)
)
payload = {
"description": "Description",
"amount": {
"currency": "EUR",
"value": "5.00",
},
"redirect_url": "https://example.org/redirect",
}
idempotency_key = "<some-idempotency-key>"
payment1 = client.payments.create(
payment_request=payload,
idempotency_key=idempotency_key
)
payment2 = client.payments.create(
payment_request=payload,
idempotency_key=idempotency_key
)
print(f"Payment created with ID: {payment1.id}")
print(f"Payment created with ID: {payment2.id}")
print("Payments are the same" if payment1.id == payment2.id else "Payments are different")
Add Custom User-Agent Header
The SDK allows you to append a custom suffix to the User-Agent header for all requests. This can be used to identify
your application or integration when interacting with the API, making it easier to track usage or debug requests. The suffix is automatically added to the default User-Agent string generated by the SDK. You can add it when creating the
client:
The SDK allows you to define the profileId and testmode in the client. This way, you don't need to add this
information to the payload every time when using OAuth. This will not override the details provided in the individual
requests.
Certain parameters are configured globally. These parameters may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, These global values will be used as defaults on the operations that use them. When such operations are called, there is a place in each to override the global value, if needed.
For example, you can set profileId to `` at SDK initialization and then you do not have to pass the same value on calls to operations like list. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.
Available Globals
The following global parameters are available.
Global parameters can also be set via environment variable.
Name
Type
Description
Environment
profile_id
str
The identifier referring to the profile you wish to retrieve the resources for.
Most API credentials are linked to a single profile. In these cases the profileId must not be sent. For organization-level credentials such as OAuth access tokens however, the profileId parameter is required.
CLIENT_PROFILE_ID
testmode
bool
Most API credentials are specifically created for either live mode or test mode. In those cases the testmode query parameter must not be sent. For organization-level credentials such as OAuth access tokens, you can enable test mode by setting the testmode query parameter to true.
Test entities cannot be retrieved when the endpoint is set to live mode, and vice versa.
CLIENT_TESTMODE
custom_user_agent
str
Custom user agent string to be appended to the default Mollie SDK user agent.
CLIENT_CUSTOM_USER_AGENT
Example
import mollie
from mollie import ClientSDK
import os
with ClientSDK(
testmode=True,
profile_id="<id>",
custom_user_agent="<value>",
security=mollie.Security(
advanced_access_token=os.getenv("CLIENT_ADVANCED_ACCESS_TOKEN"),
),
) as client_sdk:
res = client_sdk.balances.list(currency="EUR", limit=50, idempotency_key="123e4567-e89b-12d3-a456-426", x_client_signature="MEUCIQDx8sJvK3z...", x_client_signed_at="2025-01-01T12:00:00Z")
while res is not None:
# Handle items
res = res.next()
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the
returned response object will have a Next method that can be called to pull down the next group of results. If the
return value of Next is None, then there are no more pages to be fetched.
Here's an example of one such pagination call:
import mollie
from mollie import ClientSDK
import os
with ClientSDK(
testmode=True,
security=mollie.Security(
advanced_access_token=os.getenv("CLIENT_ADVANCED_ACCESS_TOKEN"),
),
) as client_sdk:
res = client_sdk.balances.list(currency="EUR", limit=50, idempotency_key="123e4567-e89b-12d3-a456-426", x_client_signature="MEUCIQDx8sJvK3z...", x_client_signed_at="2025-01-01T12:00:00Z")
while res is not None:
# Handle items
res = res.next()
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:
import mollie
from mollie import ClientSDK
from mollie.utils import BackoffStrategy, RetryConfig
with ClientSDK() as client_sdk:
res = client_sdk.oauth.generate(security=mollie.OauthGenerateTokensSecurity(
username="",
password="",
), idempotency_key="123e4567-e89b-12d3-a456-426", request_body={
"grant_type": mollie.OauthGrantType.AUTHORIZATION_CODE,
"code": "auth_...",
"refresh_token": "refresh_...",
"redirect_uri": "https://example.com/redirect",
},
RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))
# Handle response
print(res)
If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:
import mollie
from mollie import ClientSDK
from mollie.utils import BackoffStrategy, RetryConfig
with ClientSDK(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
) as client_sdk:
res = client_sdk.oauth.generate(security=mollie.OauthGenerateTokensSecurity(
username="",
password="",
), idempotency_key="123e4567-e89b-12d3-a456-426", request_body={
"grant_type": mollie.OauthGrantType.AUTHORIZATION_CODE,
"code": "auth_...",
"refresh_token": "refresh_...",
"redirect_uri": "https://example.com/redirect",
})
# Handle response
print(res)
Webhook Signature Validation
The SDK includes a helper to validate Mollie webhook signatures using HMAC-SHA256.
Use it with the raw request body exactly as received by your web framework and the value of the
X-Mollie-Signature header.
import os
from mollie.utils.webhooks import InvalidSignatureException, SignatureValidator
def handle_webhook(raw_body: str, signature_header: str | None) -> None:
validator = SignatureValidator(os.getenv("MOLLIE_WEBHOOK_SECRET", ""))
try:
is_verified = validator.validate_payload(raw_body, signature_header)
except InvalidSignatureException:
print("Webhook signature is invalid")
return
if not is_verified:
print("No signature header was provided; treating it as a legacy webhook")
return
print("Webhook signature is valid")
You can also use the static helper when you do not want to instantiate the validator yourself:
from mollie.utils.webhooks import SignatureValidator
SignatureValidator.validate(
payload=raw_body,
signing_secrets=["current_secret", "previous_secret"],
signatures=signature_header,
)
Notes:
validate_payload() returns True when at least one signature matches.
It returns False when no signature is present, which lets you support legacy webhooks.
It raises InvalidSignatureException when a signature is present but does not match.
Header values with the sha256= prefix are supported automatically.
Error Handling
ClientError is the base class for all HTTP error responses. It has the following properties:
Property
Type
Description
err.message
str
Error message
err.status_code
int
HTTP response status code eg 404
err.headers
httpx.Headers
HTTP response headers
err.body
str
HTTP body. Can be empty string if no body is returned.
err.raw_response
httpx.Response
Raw HTTP response
err.data
Optional. Some errors may contain structured data. See Error Classes.
Example
import mollie
from mollie import ClientSDK, models
with ClientSDK() as client_sdk:
res = None
try:
res = client_sdk.oauth.generate(security=mollie.OauthGenerateTokensSecurity(
username="",
password="",
), idempotency_key="123e4567-e89b-12d3-a456-426", request_body={
"grant_type": mollie.OauthGrantType.AUTHORIZATION_CODE,
"code": "auth_...",
"refresh_token": "refresh_...",
"redirect_uri": "https://example.com/redirect",
})
# Handle response
print(res)
except models.ClientError as e:
# The base class for HTTP error responses
print(e.message)
print(e.status_code)
print(e.body)
print(e.headers)
print(e.raw_response)
# Depending on the method different errors may be thrown
if isinstance(e, models.ErrorResponse):
print(e.data.status) # int
print(e.data.title) # str
print(e.data.detail) # str
print(e.data.field) # Optional[str]
print(e.data.links) # mollie.ErrorsLinks
Error Classes
Primary errors:
ClientError: The base class for HTTP error responses.
ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the cause attribute.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:
import mollie
from mollie import ClientSDK
with ClientSDK(
server_url="https://api.mollie.com",
) as client_sdk:
res = client_sdk.oauth.generate(security=mollie.OauthGenerateTokensSecurity(
username="",
password="",
), idempotency_key="123e4567-e89b-12d3-a456-426", request_body={
"grant_type": mollie.OauthGrantType.AUTHORIZATION_CODE,
"code": "auth_...",
"refresh_token": "refresh_...",
"redirect_uri": "https://example.com/redirect",
})
# Handle response
print(res)
Custom HTTP Client
The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance.
Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls.
This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.
For example, you could specify a header for every request that this sdk makes as follows:
from mollie import ClientSDK
import httpx
http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = ClientSDK(client=http_client)
or you could wrap the client with your own custom logic:
httpx2 is Pydantic's maintained fork of httpx. To run this SDK on httpx2, call alias_httpx() at your program's entry point, before importing the SDK, so every import httpx — including the ones inside the SDK — resolves to httpx2:
import httpx2
httpx2.alias_httpx()
from mollie import ClientSDK
s = ClientSDK()
An SDK can also be generated against httpx2 directly, so it depends on the fork instead of httpx, by setting python.httpClientLibrary: httpx2 in gen.yaml.
Resource Management
The ClientSDK class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.
from mollie import ClientSDK
def main():
with ClientSDK() as client_sdk:
# Rest of application here...
pass
# Or when using async:
async def amain():
async with ClientSDK() as client_sdk:
# Rest of application here...
pass
Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass your own logger class directly into your SDK.
from mollie import ClientSDK
import logging
logging.basicConfig(level=logging.DEBUG)
s = ClientSDK(debug_logger=logging.getLogger("mollie"))
You can also enable a default debug logger by setting an environment variable CLIENT_DEBUG to true, 1, yes or on (case-insensitive). Any other value leaves it off.
Development
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation.
We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.