Python Client SDK Generated by Speakeasy.
Project description
Gr4vy Python SDK
Developer-friendly & type-safe Python SDK specifically catered to leverage Gr4vy API.
Summary
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.
Table of Contents
SDK Installation
[!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
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
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
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 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.
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.
SDK Example Usage
Example
# 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 mentionsos.getenv("GR4VY_BEARER_AUTH", ""),
.
Bearer token generation
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.
Embed token generation
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.
Merchant account ID selection
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()
Webhooks verification
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}')
Parameters
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 Resources and Operations
Available methods
account_updater
account_updater.jobs
- create - Create account updater job
audit_logs
- list - List audit log entries
buyers
- list - List all buyers
- create - Add a buyer
- get - Get a buyer
- update - Update a buyer
- delete - Delete a buyer
buyers.gift_cards
- list - List gift cards for a buyer
buyers.payment_methods
- list - List payment methods for a buyer
buyers.shipping_details
- 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
card_scheme_definitions
- list - List card scheme definitions
checkout_sessions
- create - Create checkout session
- update - Update checkout session
- get - Get checkout session
- delete - Delete checkout session
digital_wallets
- create - Register digital wallet
- list - List digital wallets
- get - Get digital wallet
- delete - Delete digital wallet
- update - Update digital wallet
digital_wallets.domains
digital_wallets.sessions
- google_pay - Create a Google Pay session
- apple_pay - Create a Apple Pay session
- click_to_pay - Create a Click to Pay session
gift_cards
gift_cards.balances
- list - List gift card balances
merchant_accounts
- list - List all merchant accounts
- create - Create a merchant account
- get - Get a merchant account
- update - Update a merchant account
payment_links
- create - Add a payment link
- list - List all payment links
- expire - Expire a payment link
- get - Get payment link
payment_methods
- list - List all payment methods
- create - Create payment method
- get - Get payment method
- delete - Delete payment method
payment_methods.network_tokens
- list - List network tokens
- create - Provision network token
- suspend - Suspend network token
- resume - Resume network token
- delete - Delete network token
payment_methods.network_tokens.cryptogram
- create - Provision network token cryptogram
payment_methods.payment_service_tokens
- list - List payment service tokens
- create - Create payment service token
- delete - Delete payment service token
payment_options
- list - List payment options
payment_service_definitions
- list - List payment service definitions
- get - Get a payment service definition
- session - Create a session for apayment service definition
payment_services
- 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
payouts
refunds
- get - Get refund
report_executions
- list - List executed reports
reports
reports.executions
transactions
- list - List transactions
- create - Create transaction
- get - Get transaction
- capture - Capture transaction
- void - Void transaction
- sync - Sync transaction
transactions.events
- list - List transaction events
transactions.refunds
transactions.refunds.all
- create - Create batch transaction refund
transactions.settlements
Global Parameters
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 `` 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.
Available Globals
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 |
Example
from gr4vy import Gr4vy
import os
with Gr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
res = g_client.merchant_accounts.get(merchant_account_id="merchant-12345")
# Handle response
print(res)
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:
from gr4vy import Gr4vy
import os
with Gr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
res = g_client.buyers.list(cursor="ZXhhbXBsZTE", limit=20, search="John", external_identifier="buyer-12345")
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:
from gr4vy import Gr4vy
from gr4vy.utils import BackoffStrategy, RetryConfig
import os
with Gr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
],
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),
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
])
assert res is not None
# Handle response
print(res)
Error Handling
Gr4vyError
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
from gr4vy import Gr4vy, errors
import os
from typing import Literal
with Gr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) 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",
])
assert res is not None
# Handle response
print(res)
except errors.Gr4vyError 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, errors.Error400):
print(e.data.type) # Optional[Literal["error"]]
print(e.data.code) # Optional[str]
print(e.data.status) # Optional[int]
print(e.data.message) # Optional[str]
print(e.data.details) # Optional[List[models.ErrorDetail]]
Error Classes
Primary errors:
Gr4vyError
: The base class for HTTP error responses.Error400
: The request was invalid. Status code400
.Error401
: The request was unauthorized. Status code401
.Error403
: The credentials were invalid or the caller did not have permission to act on the resource. Status code403
.Error404
: The resource was not found. Status code404
.Error405
: The request method was not allowed. Status code405
.Error409
: A duplicate record was found. Status code409
.Error425
: The request was too early. Status code425
.Error429
: Too many requests were made. Status code429
.Error500
: The server encountered an error. Status code500
.Error502
: The server encountered an error. Status code502
.Error504
: The server encountered an error. Status code504
.HTTPValidationError
: Validation Error. Status code422
. *
Less common errors (5)
Network errors:
httpx.RequestError
: Base class for request errors.httpx.ConnectError
: HTTP client was unable to make a request to a server.httpx.TimeoutException
: HTTP request timed out.
Inherit from Gr4vyError
:
ResponseValidationError
: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via thecause
attribute.
* Check the method documentation to see if the error is applicable.
Server Selection
Select Server by Name
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 |
---|---|---|---|
sandbox |
https://api.sandbox.{id}.gr4vy.app |
id |
|
production |
https://api.{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. |
Example
from gr4vy import Gr4vy
import os
with Gr4vy(
server="production",
id="<id>"
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
])
assert res is not None
# Handle response
print(res)
Override Server URL Per-Client
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.sandbox.example.gr4vy.app",
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
res = g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
])
assert res is not None
# 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 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()))
Resource Management
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(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
# Rest of application here...
# Or when using async:
async def amain():
async with Gr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
# Rest of application here...
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 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.
Development
Testing
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
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.
SDK Created by Speakeasy
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file gr4vy-1.1.4.tar.gz
.
File metadata
- Download URL: gr4vy-1.1.4.tar.gz
- Upload date:
- Size: 173.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.3 CPython/3.9.23 Linux/6.8.0-1030-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 |
64046346e5b0ad6edb35e590b46a8b34adeb3a59877c169f240a6246ea254694
|
|
MD5 |
257afe944b282d495973c764be285a9f
|
|
BLAKE2b-256 |
988783f909a26cf8fff288333793f5ab5ed2026945dec4c470cc91f892dead79
|
File details
Details for the file gr4vy-1.1.4-py3-none-any.whl
.
File metadata
- Download URL: gr4vy-1.1.4-py3-none-any.whl
- Upload date:
- Size: 414.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.3 CPython/3.9.23 Linux/6.8.0-1030-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 |
432cb41094edacea314cc9a6328e163165be2c98f138762c805d01d7c79da088
|
|
MD5 |
cd3374fbd4b9338da8d770a8d4eae446
|
|
BLAKE2b-256 |
15809b20e205d0ed42a9bb59f7cf007b025631a008c39261d06d0b39f047481c
|