Developer-friendly & type-safe Python SDK specifically catered to leverage gr4vy API.
Important
This is a Beta release of our latest SDK. Please refer to the legacy Python SDK for the latest stable build.
Gr4vy Python SDK
The official Gr4vy SDK for Python provides a convenient way to interact with the Gr4vy API from your server-side application. This SDK allows you to seamlessly integrate Gr4vy's powerful payment orchestration capabilities, including:
- Creating Transactions: Initiate and process payments with various payment methods and services.
- Managing Buyers: Store and manage buyer information securely.
- Storing Payment Methods: Securely store and tokenize payment methods for future use.
- Handling Webhooks: Easily process and respond to webhook events from Gr4vy.
- And much more: Access the full suite of Gr4vy API payment features.
This SDK is designed to simplify development, reduce boilerplate code, and help you get up and running with Gr4vy quickly and efficiently. It handles authentication, request signing, and provides easy-to-use methods for most API endpoints.
Note
Python version upgrade policy
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 either pip or poetry package managers.
PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install gr4vy
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 gr4vy
You can use this SDK in a Python shell with uv and the uvx
command that comes with it like so:
uvx --from gr4vy python
It's also possible to write a standalone Python script without needing to set up a whole project like so:
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "gr4vy",
# ]
# ///
from gr4vy import Gr4vy
sdk = Gr4vy(
# SDK arguments
)
# Rest of script here...
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.
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
from gr4vy import Gr4vy, auth
import os
with Gr4vy(
id="example",
server="production",
merchant_account_id="default",
bearer_auth=auth.with_token(open("./private_key.pem").read())
) as g_client:
res = g_client.transactions.list()
assert res is not None
# Handle response
print(res)
The same SDK client can also be used to make asychronous requests by importing asyncio.
# Asynchronous Example
import asyncio
from gr4vy import Gr4vy, auth
import os
async def main():
async with Gr4vy(
id="example",
server="production",
merchant_account_id="default",
bearer_auth=auth.with_token(open("./private_key.pem").read())
) as g_client:
res = await g_client.transactions.list()
assert res is not None
# Handle response
print(res)
asyncio.run(main())
Important
Please use the auth.with_token
where the documentation mentions os.getenv("GR4VY_BEARER_AUTH", ""),
.
Alternatively, you can create a token for use with the SDK or with your own client library.
from gr4vy import Gr4vy, auth
auth.get_token(open("./private_key.pem").read()
Note: This will only create a token once. Use
auth.with_token
to dynamically generate a token for every request.
Alternatively, you can create a token for use with Embed as follows.
from gr4vy import Gr4vy, auth
private_key = open("./private_key.pem").read()
g_client = Gr4vy(
id="example",
server="production",
merchant_account_id="default",
bearer_auth=auth.with_token(private_key)
)
checkout_session = g_client.checkout_sessions.create()
auth.get_embed_token(
privatekey,
embed_params={
"amount": 1299,
"currency": 'USD',
"buyer_external_identifier": 'user-1234',
},
checkout_session_id=checkout_session.id
)
Note: This will only create a token once. Use
with_token
to dynamically generate a token for every request.
Depending on the key used, you might need to explicitly define a merchant account ID to use. In our API,
this uses the X-GR4VY-MERCHANT-ACCOUNT-ID
header. When using the SDK, you can set the merchant_account_id
on every request.
res = g_client.transactions.list(merchant_account_id: 'merchant-12345')
Alternatively, the merchant account ID can also be set when initializing the SDK.
with Gr4vy(
id="spider",
merchant_account_id="merchant-12345",
bearer_auth=auth.get_token(private_key)
) as g_client:
response = g_client.transactions.list()
The SDK makes it easy to verify that incoming webhooks were actually sent by Gr4vy. Once you have configured the webhook subscription with its corresponding secret, that can be verified the following way:
from gr4vy.webhooks import verify_webhook
# Webhook payload and headers
payload = 'your-webhook-payload'
secret = 'your-webhook-secret'
signature_header = 'signatures-from-header'
timestamp_header = 'timestamp-from-header'
timestamp_tolerance = 300 # optional, in seconds (default: 0)
try:
# Verify the webhook
verify_webhook(
payload=payload,
secret=secret,
signature_header=signature_header,
timestamp_header=timestamp_header,
timestamp_tolerance=timestamp_tolerance
)
print('Webhook verified successfully!')
except ValueError as error:
print(f'Webhook verification failed: {error}')
payload
: The raw payload string received in the webhook request.secret
: The secret used to sign the webhook. This is provided in your Gr4vy dashboard.signatureHeader
: TheX-Gr4vy-Signature
header from the webhook request.timestampHeader
: TheX-Gr4vy-Timestamp
header from the webhook request.timestampTolerance
: (Optional) The maximum allowed difference (in seconds) between the current time and the timestamp in the webhook. Defaults to0
(no tolerance).
Available methods
- create - Create account updater job
- list - List audit log entries
- list - List all buyers
- create - Add a buyer
- get - Get a buyer
- update - Update a buyer
- delete - Delete a buyer
- list - List gift cards for a buyer
- list - List payment methods for a buyer
- create - Add buyer shipping details
- list - List a buyer's shipping details
- get - Get buyer shipping details
- update - Update a buyer's shipping details
- delete - Delete a buyer's shipping details
- list - List card scheme definitions
- create - Create checkout session
- update - Update checkout session
- get - Get checkout session
- delete - Delete checkout session
- create - Register digital wallet
- list - List digital wallets
- get - Get digital wallet
- delete - Delete digital wallet
- update - Update digital wallet
- google_pay - Create a Google Pay session
- apple_pay - Create a Apple Pay session
- click_to_pay - Create a Click to Pay session
- list - List gift card balances
- list - List all merchant accounts
- create - Create a merchant account
- get - Get a merchant account
- update - Update a merchant account
- list - List all payment methods
- create - Create payment method
- get - Get payment method
- delete - Delete payment method
- list - List network tokens
- create - Provision network token
- suspend - Suspend network token
- resume - Resume network token
- delete - Delete network token
- create - Provision network token cryptogram
- list - List payment service tokens
- create - Create payment service token
- delete - Delete payment service token
- list - List payment options
- list - List payment service definitions
- get - Get a payment service definition
- session - Create a session for apayment service definition
- list - List payment services
- create - Update a configured payment service
- get - Get payment service
- update - Configure a payment service
- delete - Delete a configured payment service
- verify - Verify payment service credentials
- session - Create a session for apayment service definition
- get - Get refund
- list - List transactions
- create - Create transaction
- get - Get transaction
- capture - Capture transaction
- void - Void transaction
- summary - Get transaction summary
- sync - Sync transaction
- create - Create batch transaction refund
A parameter is configured globally. This parameter may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, This global value will be used as the default on the operations that use it. When such operations are called, there is a place in each to override the global value, if needed.
For example, you can set merchant_account_id
to "default"
at SDK initialization and then you do not have to pass the same value on calls to operations like get
. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.
The following global parameter is available. Global parameters can also be set via environment variable.
Name | Type | Description | Environment |
---|---|---|---|
merchant_account_id | str | The ID of the merchant account to use for this request. | GR4VY_MERCHANT_ACCOUNT_ID |
from gr4vy import Gr4vy
import os
with Gr4vy(
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
res = g_client.merchant_accounts.get(merchant_account_id="merchant-12345")
# Handle response
print(res)
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:
from gr4vy import Gr4vy
import os
with Gr4vy(
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
res = g_client.buyers.list(cursor="ZXhhbXBsZTE", search="John", external_identifier="buyer-12345", merchant_account_id="default")
while res is not None:
# Handle items
res = res.next()
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:
from gr4vy import Gr4vy
from gr4vy.utils import BackoffStrategy, RetryConfig
import os
with Gr4vy(
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
], merchant_account_id="default",
RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))
assert res is not None
# 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:
from gr4vy import Gr4vy
from gr4vy.utils import BackoffStrategy, RetryConfig
import os
with Gr4vy(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
], merchant_account_id="default")
assert res is not None
# Handle response
print(res)
Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.
By default, an API error will raise a errors.APIError exception, which has the following properties:
Property | Type | Description |
---|---|---|
.status_code |
int | The HTTP status code |
.message |
str | The error message |
.raw_response |
httpx.Response | The raw HTTP response |
.body |
str | The response content |
When custom error responses are specified for an operation, the SDK may also raise their associated exceptions. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the create_async
method may raise the following exceptions:
Error Type | Status Code | Content Type |
---|---|---|
errors.Error400 | 400 | application/json |
errors.Error401 | 401 | application/json |
errors.Error403 | 403 | application/json |
errors.Error404 | 404 | application/json |
errors.Error405 | 405 | application/json |
errors.Error409 | 409 | application/json |
errors.HTTPValidationError | 422 | application/json |
errors.Error425 | 425 | application/json |
errors.Error429 | 429 | application/json |
errors.Error500 | 500 | application/json |
errors.Error502 | 502 | application/json |
errors.Error504 | 504 | application/json |
errors.APIError | 4XX, 5XX | */* |
from gr4vy import Gr4vy, errors
import os
with Gr4vy(
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
res = None
try:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
], merchant_account_id="default")
assert res is not None
# Handle response
print(res)
except errors.Error400 as e:
# handle e.data: errors.Error400Data
raise(e)
except errors.Error401 as e:
# handle e.data: errors.Error401Data
raise(e)
except errors.Error403 as e:
# handle e.data: errors.Error403Data
raise(e)
except errors.Error404 as e:
# handle e.data: errors.Error404Data
raise(e)
except errors.Error405 as e:
# handle e.data: errors.Error405Data
raise(e)
except errors.Error409 as e:
# handle e.data: errors.Error409Data
raise(e)
except errors.HTTPValidationError as e:
# handle e.data: errors.HTTPValidationErrorData
raise(e)
except errors.Error425 as e:
# handle e.data: errors.Error425Data
raise(e)
except errors.Error429 as e:
# handle e.data: errors.Error429Data
raise(e)
except errors.Error500 as e:
# handle e.data: errors.Error500Data
raise(e)
except errors.Error502 as e:
# handle e.data: errors.Error502Data
raise(e)
except errors.Error504 as e:
# handle e.data: errors.Error504Data
raise(e)
except errors.APIError as e:
# handle exception
raise(e)
You can override the default server globally by passing a server name to the server: str
optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
Name | Server | Variables | Description |
---|---|---|---|
production |
https://api.{id}.gr4vy.app |
id |
|
sandbox |
https://api.sandbox.{id}.gr4vy.app |
id |
If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor:
Variable | Parameter | Default | Description |
---|---|---|---|
id |
id: str |
"example" |
The subdomain for your Gr4vy instance. |
from gr4vy import Gr4vy
import os
with Gr4vy(
server="sandbox",
id="<id>"
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
], merchant_account_id="default")
assert res is not None
# Handle response
print(res)
The default server can also be overridden globally by passing a URL to the server_url: str
optional parameter when initializing the SDK client instance. For example:
from gr4vy import Gr4vy
import os
with Gr4vy(
server_url="https://api.example.gr4vy.app",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
], merchant_account_id="default")
assert res is not None
# Handle response
print(res)
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 gr4vy import Gr4vy
import httpx
http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = Gr4vy(client=http_client)
or you could wrap the client with your own custom logic:
from gr4vy import Gr4vy
from gr4vy.httpclient import AsyncHttpClient
import httpx
class CustomClient(AsyncHttpClient):
client: AsyncHttpClient
def __init__(self, client: AsyncHttpClient):
self.client = client
async def send(
self,
request: httpx.Request,
*,
stream: bool = False,
auth: Union[
httpx._types.AuthTypes, httpx._client.UseClientDefault, None
] = httpx.USE_CLIENT_DEFAULT,
follow_redirects: Union[
bool, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
) -> httpx.Response:
request.headers["Client-Level-Header"] = "added by client"
return await self.client.send(
request, stream=stream, auth=auth, follow_redirects=follow_redirects
)
def build_request(
self,
method: str,
url: httpx._types.URLTypes,
*,
content: Optional[httpx._types.RequestContent] = None,
data: Optional[httpx._types.RequestData] = None,
files: Optional[httpx._types.RequestFiles] = None,
json: Optional[Any] = None,
params: Optional[httpx._types.QueryParamTypes] = None,
headers: Optional[httpx._types.HeaderTypes] = None,
cookies: Optional[httpx._types.CookieTypes] = None,
timeout: Union[
httpx._types.TimeoutTypes, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
extensions: Optional[httpx._types.RequestExtensions] = None,
) -> httpx.Request:
return self.client.build_request(
method,
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
s = Gr4vy(async_client=CustomClient(httpx.AsyncClient()))
The Gr4vy
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 gr4vy import Gr4vy
import os
def main():
with Gr4vy(
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
# Rest of application here...
# Or when using async:
async def amain():
async with Gr4vy(
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
merchant_account_id="default",
) as g_client:
# Rest of application here...
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 gr4vy import Gr4vy
import logging
logging.basicConfig(level=logging.DEBUG)
s = Gr4vy(debug_logger=logging.getLogger("gr4vy"))
You can also enable a default debug logger by setting an environment variable GR4VY_DEBUG
to true.
To run the tests, install Python and Poetry, ensure to download the private_key.pem
for the test environment, and run the following.
poetry install
poetry run pytest
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
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.