Skip to content

Repository files navigation

Gr4vy Python SDK

Developer-friendly & type-safe Python SDK specifically catered to leverage Gr4vy API.

PyPI - Version

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 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 gr4vy

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.10"# dependencies = [# "gr4vy",# ]# ///fromgr4vyimportGr4vysdk=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 Examplefromgr4vyimportGr4vy, authimportoswithGr4vy(
id="example",
server="production",
merchant_account_id="default",
bearer_auth=auth.with_token(open("./private_key.pem").read())
) asg_client:
res=g_client.transactions.list()
assertresisnotNone# Handle responseprint(res)

The same SDK client can also be used to make asychronous requests by importing asyncio.

# Asynchronous Exampleimportasynciofromgr4vyimportGr4vy, authimportosasyncdefmain():
asyncwithGr4vy(
id="example",
server="production",
merchant_account_id="default",
bearer_auth=auth.with_token(open("./private_key.pem").read())
) asg_client:
res=awaitg_client.transactions.list()
assertresisnotNone# Handle responseprint(res)
asyncio.run(main())



Important

Please use the auth.with_token where the documentation mentions os.getenv("GR4VY_BEARER_AUTH", ""),.

Bearer token generation

Alternatively, you can create a token for use with the SDK or with your own client library.

fromgr4vyimportGr4vy, authauth.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.

fromgr4vyimportGr4vy, authprivate_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.

Attaching a checkout session automatically

For Embed, it is recommended to attach a checkout session to every transaction. The auth.get_embed_token_with_checkout_session helper creates a checkout session using your SDK client and returns an Embed token with the resulting checkout_session_id already pinned, in a single call.

fromgr4vyimportGr4vy, authprivate_key=open("./private_key.pem").read()
g_client=Gr4vy(
id="example",
server="production",
merchant_account_id="default",
bearer_auth=auth.with_token(private_key)
)
token=auth.get_embed_token_with_checkout_session(
g_client,
private_key,
embed_params={
"amount": 1299,
"currency": "USD",
"buyer_external_identifier": "user-1234",
},
)

You can optionally pass a checkout_session_create body to seed the session (for example with cart items or metadata), and a merchant_account_id to override the client's configured merchant account.

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.

withGr4vy(
id="spider",
merchant_account_id="merchant-12345",
bearer_auth=auth.get_token(private_key)
) asg_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:

fromgr4vy.webhooksimportverify_webhook# Webhook payload and headerspayload='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 webhookverify_webhook(
payload=payload,
secret=secret,
signature_header=signature_header,
timestamp_header=timestamp_header,
timestamp_tolerance=timestamp_tolerance
)
print('Webhook verified successfully!')
exceptValueErroraserror:
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: The X-Gr4vy-Signature header from the webhook request.
  • timestampHeader: The X-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 to 0 (no tolerance).

Available Resources and Operations

Available methods
  • create - Create account updater job
  • list - List all API key pairs
  • create - Create an API key pair
  • get - Get an API key pair
  • update - Update an API key pair
  • delete - Delete an API key pair
  • list - List audit log entries
  • 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
  • create - Register a digital wallet domain
  • delete - Remove a digital wallet domain
  • 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
  • create - Create 3DS configuration for merchant
  • list - List 3DS configurations for merchant
  • update - Edit 3DS configuration
  • delete - Delete 3DS configuration for a merchant
  • create - Add a payment link
  • list - List all payment links
  • expire - Expire a payment link
  • get - Get payment link
  • list - List all payment methods
  • create - Create payment method
  • get - Get payment method
  • update - Update 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 a payment service definition
  • list - List payment services
  • create - Configure a payment service
  • get - Get payment service
  • update - Update a configured payment service
  • delete - Delete a configured payment service
  • verify - Verify payment service credentials
  • session - Create a session for a payment service definition
  • list - List payouts created
  • create - Create a payout
  • get - Get a payout
  • get - Get refund
  • list - List executed reports
  • list - List configured reports
  • create - Add a report
  • get - Get a report
  • put - Update a report
  • list - List executions for report
  • url - Create URL for executed report
  • get - Get executed report
  • create - Create a 3DS scenario
  • list - List 3DS scenario
  • update - Update a 3DS scenario
  • delete - Delete a 3DS scenario
  • list - List transaction Flow rules
  • list - List transaction captures
  • get - Get transaction capture
  • list - List transaction events
  • get - Get transaction refund settlement
  • list - List transaction refund settlements
  • list - List transaction refunds
  • create - Create transaction refund
  • get - Get transaction refund
  • create - Create batch transaction refund
  • get - Get transaction settlement
  • list - List transaction 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.

NameTypeDescriptionEnvironment
merchant_account_idstrThe ID of the merchant account to use for this request.GR4VY_MERCHANT_ACCOUNT_ID

Example

fromgr4vyimportGr4vyimportoswithGr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_client:
res=g_client.merchant_accounts.get(merchant_account_id="merchant-12345")
# Handle responseprint(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:

fromgr4vyimportGr4vyimportoswithGr4vy(
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_client:
res=g_client.api_key_pairs.list(limit=20)
whileresisnotNone:
# Handle itemsres=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:

fromgr4vyimportGr4vyfromgr4vy.utilsimportBackoffStrategy, RetryConfigimportoswithGr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_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))
assertresisnotNone# Handle responseprint(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:

fromgr4vyimportGr4vyfromgr4vy.utilsimportBackoffStrategy, RetryConfigimportoswithGr4vy(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_client:
res=g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
])
assertresisnotNone# Handle responseprint(res)

Error Handling

Gr4vyError is the base class for all HTTP error responses. It has the following properties:

PropertyTypeDescription
err.messagestrError message
err.status_codeintHTTP response status code eg 404
err.headershttpx.HeadersHTTP response headers
err.bodystrHTTP body. Can be empty string if no body is returned.
err.raw_responsehttpx.ResponseRaw HTTP response
err.dataOptional. Some errors may contain structured data. See Error Classes.

Example

fromgr4vyimportGr4vy, errorsimportosfromtypingimportLiteralwithGr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_client:
res=Nonetry:
res=g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
])
assertresisnotNone# Handle responseprint(res)
excepterrors.Gr4vyErrorase:
# The base class for HTTP error responsesprint(e.message)
print(e.status_code)
print(e.body)
print(e.headers)
print(e.raw_response)
# Depending on the method different errors may be thrownifisinstance(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 code 400.
    • Error401: The request was unauthorized. Status code 401.
    • Error403: The credentials were invalid or the caller did not have permission to act on the resource. Status code 403.
    • Error404: The resource was not found. Status code 404.
    • Error405: The request method was not allowed. Status code 405.
    • Error409: A duplicate record was found. Status code 409.
    • Error425: The request was too early. Status code 425.
    • Error429: Too many requests were made. Status code 429.
    • Error500: The server encountered an error. Status code 500.
    • Error502: The server encountered an error. Status code 502.
    • Error504: The server encountered an error. Status code 504.
    • HTTPValidationError: Validation Error. Status code 422. *
Less common errors (5)

Network errors:

Inherit from Gr4vyError:

  • ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the cause 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:

NameServerVariablesDescription
sandboxhttps://api.sandbox.{id}.gr4vy.appid
productionhttps://api.{id}.gr4vy.appid

If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor:

VariableParameterDefaultDescription
idid: str"example"The subdomain for your Gr4vy instance.

Example

fromgr4vyimportGr4vyimportoswithGr4vy(
server="sandbox",
id="example",
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_client:
res=g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
])
assertresisnotNone# Handle responseprint(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:

fromgr4vyimportGr4vyimportoswithGr4vy(
server_url="https://api.sandbox.example.gr4vy.app",
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_client:
res=g_client.account_updater.jobs.create(payment_method_ids=[
"ef9496d8-53a5-4aad-8ca2-00eb68334389",
"f29e886e-93cc-4714-b4a3-12b7a718e595",
])
assertresisnotNone# Handle responseprint(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:

fromgr4vyimportGr4vyimporthttpxhttp_client=httpx.Client(headers={"x-custom-header": "someValue"})
s=Gr4vy(client=http_client)

or you could wrap the client with your own custom logic:

fromgr4vyimportGr4vyfromgr4vy.httpclientimportAsyncHttpClientimporthttpxclassCustomClient(AsyncHttpClient):
client: AsyncHttpClientdef__init__(self, client: AsyncHttpClient):
self.client=clientasyncdefsend(
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"returnawaitself.client.send(
request, stream=stream, auth=auth, follow_redirects=follow_redirects
)
defbuild_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:
returnself.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.

fromgr4vyimportGr4vyimportosdefmain():
withGr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_client:
# Rest of application here...# Or when using async:asyncdefamain():
asyncwithGr4vy(
merchant_account_id="default",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) asg_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.

fromgr4vyimportGr4vyimportlogginglogging.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

About

Gr4vy SDK for Python

Topics

Resources

Contributing

Stars

1 star

Watchers

3 watching

Forks

Releases

Used by

Contributors

Languages