Python SDK for FlexPrice API
Project description
FlexPrice Python SDK
This is the Python client library for the FlexPrice API.
Installation
pip install flexprice
Usage
"""
FlexPrice Python SDK Example
This example demonstrates how to use the FlexPrice Python SDK
to interact with the FlexPrice API.
"""
import os
import time
import datetime
from pprint import pprint
# Import the FlexPrice SDK
import flexprice
from flexprice.api import customers_api, events_api
from flexprice.models.dto_create_customer_request import DtoCreateCustomerRequest
from flexprice.models.dto_ingest_event_request import DtoIngestEventRequest
# Optional: Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()
def run_example():
"""Main example function demonstrating FlexPrice SDK usage."""
print("Starting FlexPrice Python SDK example...")
try:
# Configure the API client
api_key = os.getenv("FLEXPRICE_API_KEY")
api_host = os.getenv("FLEXPRICE_API_HOST", "api.cloud.flexprice.io")
if not api_key:
raise ValueError("FLEXPRICE_API_KEY environment variable is required")
print("Using API Key:", api_key[:4] + "..." + api_key[-4:]) # Show just the start and end for security
# Configure API key authorization
configuration = flexprice.Configuration(
host=f"https://{api_host}/v1"
)
configuration.api_key['x-api-key'] = api_key
# Create API client
with flexprice.ApiClient(configuration) as api_client:
# Set the API key header
api_client.default_headers['x-api-key'] = api_key
# Add User-Agent header
configuration.user_agent = "FlexPricePythonSDK/1.0.0 Example"
# Print actual headers for debugging
# Create API instances
events_api_instance = events_api.EventsApi(api_client)
# Generate a unique customer ID for this example
customer_id = f"sample-customer-{int(time.time())}"
print(f"Creating customer with ID: {customer_id}...")
# Step 1: Create an event
print("Creating event...")
event_request = DtoIngestEventRequest(
event_name="Sample Event",
external_customer_id=customer_id,
properties={
"source": "python_sample_app",
"environment": "test",
"timestamp": datetime.datetime.now().isoformat()
},
source="python_sample_app"
)
event_result = events_api_instance.events_post(event=event_request)
print(f"Event created successfully! ID: {event_result.event_id if hasattr(event_result, 'event_id') else 'unknown'}")
# Step 2: Retrieve events for this customer
print(f"Retrieving events for customer {customer_id}...")
events_response = events_api_instance.events_get(external_customer_id=customer_id)
# Check if events are available in the response
if hasattr(events_response, 'events') and events_response.events:
print(f"Found {len(events_response.events)} events:")
for i, event in enumerate(events_response.events):
print(f"Event {i+1}: {event.id if hasattr(event, 'id') else 'unknown'} - {event.event_name if hasattr(event, 'event_name') else 'unknown'}")
print(f"Properties: {event.properties if hasattr(event, 'properties') else {}}")
else:
print("No events found or events not available in response.")
print("Example completed successfully!")
except flexprice.ApiException as e:
print(f"\n=== API Exception ===")
print(f"Status code: {e.status}")
print(f"Reason: {e.reason}")
print(f"HTTP response headers: {e.headers}")
print(f"HTTP response body: {e.body}")
except ValueError as e:
print(f"Value error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
Asynchronous Event Submission
The FlexPrice SDK provides asynchronous event submission functionality that allows you to:
- Submit events in a non-blocking manner with "fire-and-forget" capability
- Include optional callbacks to handle success/failure responses
- Automatically retry failed event submissions with exponential backoff
- Process events in background threads
Basic Async Usage
from flexprice import Configuration, ApiClient, EventsApi
from flexprice.models import DtoIngestEventRequest
# Configure the client
configuration = Configuration(api_key={'ApiKeyAuth': 'YOUR_API_KEY'})
configuration.host = "https://api.cloud.flexprice.io/v1"
# Create API client and event API instance
api_client = ApiClient(configuration)
events_api = EventsApi(api_client)
# Create an event
event = DtoIngestEventRequest(
external_customer_id="customer123",
event_name="api_call",
properties={"region": "us-west", "method": "GET"},
source="my_application"
)
# Submit asynchronously (fire-and-forget)
events_api.events_post_async(event)
Using Callbacks
# Define a callback function
def on_event_processed(result, error, success):
if success:
print(f"Event processed successfully: {result}")
else:
print(f"Event processing failed: {error}")
# Create and submit event with callback
event = DtoIngestEventRequest(
external_customer_id="customer123",
event_name="user_action",
properties={"action": "login", "device": "mobile"},
source="user_portal"
)
# Submit with callback
events_api.events_post_async(event, callback=on_event_processed)
Complete Example
For a complete example of asynchronous event submission, see the async_event_example.py file in the examples directory.
Running the Example
To run the provided example:
-
Clone the repository:
git clone https://github.com/flexprice/python-sdk.git cd python-sdk/examples
-
Create a virtual environment and install dependencies:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt
-
Create a
.envfile with your API credentials:cp .env.sample .env # Edit .env with your API key
-
Run the example:
python example.py -
Run the async example:
python async_event_example.py
Features
- Complete API coverage
- Strong type hints
- Detailed documentation
- Error handling
- Asynchronous support for event submission
Documentation
For detailed API documentation, refer to the code comments and the official FlexPrice API documentation.
Advanced Usage
Handling Errors
The SDK provides detailed error information through exceptions:
try:
# API call
result = client.some_api_call()
except flexprice.ApiException as e:
print(f"API exception: {e}")
print(f"Status code: {e.status}")
print(f"Response body: {e.body}")
except Exception as e:
print(f"General exception: {e}")
Asynchronous API Usage with asyncio
In addition to the built-in asynchronous event submission, the SDK can be used with libraries like asyncio for other operations:
import asyncio
import flexprice
from flexprice.api import customers_api
async def get_customer(customer_id):
configuration = flexprice.Configuration(
host="https://api.cloud.flexprice.io/v1"
)
configuration.api_key['x-api-key'] = "your-api-key"
async with flexprice.ApiClient(configuration) as api_client:
api = customers_api.CustomersApi(api_client)
return await api.customers_id_get(id=customer_id)
# Run with asyncio
customer = asyncio.run(get_customer("customer-123"))
print(customer)
Summary
FlexPrice API: FlexPrice API Service
Table of Contents
SDK Installation
[!TIP] To finish publishing your SDK to PyPI you must run your first generation action.
[!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 git+<UNSET>.git
PIP
PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install git+<UNSET>.git
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 git+<UNSET>.git
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 flexprice-sdk-test 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 = [
# "flexprice-sdk-test",
# ]
# ///
from flexprice_sdk_test import FlexPrice
sdk = FlexPrice(
# 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 flexprice_sdk_test import FlexPrice
with FlexPrice(
server_url="https://api.example.com",
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
res = flex_price.addons.get_addons()
# Handle response
print(res)
The same SDK client can also be used to make asynchronous requests by importing asyncio.
# Asynchronous Example
import asyncio
from flexprice_sdk_test import FlexPrice
async def main():
async with FlexPrice(
server_url="https://api.example.com",
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
res = await flex_price.addons.get_addons_async()
# Handle response
print(res)
asyncio.run(main())
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
api_key_auth |
apiKey | API key |
To authenticate with the API the api_key_auth parameter must be set when initializing the SDK client instance. For example:
from flexprice_sdk_test import FlexPrice
with FlexPrice(
server_url="https://api.example.com",
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
res = flex_price.addons.get_addons()
# Handle response
print(res)
Available Resources and Operations
Available methods
Addons
- get_addons - List addons
- post_addons - Create addon
- get_addons_lookup_lookup_key_ - Get addon by lookup key
- post_addons_search - List addons by filter
- get_addons_id_ - Get addon
- put_addons_id_ - Update addon
- delete_addons_id_ - Delete addon
AlertLogs
- post_alert_search - List alert logs by filter
Auth
- post_auth_login - Login
- post_auth_signup - Sign up
Connections
- get_connections - Get connections
- post_connections_search - List connections by filter
- get_connections_id_ - Get a connection
- put_connections_id_ - Update a connection
- delete_connections_id_ - Delete a connection
Costs
- post_costs - Create a new costsheet
- get_costs_active - Get active costsheet for tenant
- post_costs_analytics - Get combined revenue and cost analytics
- post_costs_analytics_v2 - Get combined revenue and cost analytics
- post_costs_search - List costsheets by filter
- get_costs_id_ - Get a costsheet by ID
- put_costs_id_ - Update a costsheet
- delete_costs_id_ - Delete a costsheet
Coupons
- get_coupons - List coupons with filtering
- post_coupons - Create a new coupon
- get_coupons_id_ - Get a coupon by ID
- put_coupons_id_ - Update a coupon
- delete_coupons_id_ - Delete a coupon
CreditNotes
- get_creditnotes - List credit notes with filtering
- post_creditnotes - Create a new credit note
- get_creditnotes_id_ - Get a credit note by ID
- post_creditnotes_id_finalize - Process a draft credit note
- post_creditnotes_id_void - Void a credit note
CreditGrants
- get_creditgrants - Get credit grants
- post_creditgrants - Create a new credit grant
- get_creditgrants_id_ - Get a credit grant by ID
- put_creditgrants_id_ - Update a credit grant
- delete_creditgrants_id_ - Delete a credit grant
- get_plans_id_creditgrants - Get plan credit grants
Customers
- get_customers - Get customers
- post_customers - Create a customer
- get_customers_external_external_id_ - Get a customer by external id
- post_customers_search - List customers by filter
- get_customers_usage - Get customer usage summary
- get_customers_id_ - Get a customer
- put_customers_id_ - Update a customer
- delete_customers_id_ - Delete a customer
- get_customers_id_entitlements - Get customer entitlements
- get_customers_id_grants_upcoming - Get upcoming credit grant applications
Entitlements
- get_addons_id_entitlements - Get addon entitlements
- get_entitlements - Get entitlements
- post_entitlements - Create a new entitlement
- post_entitlements_bulk - Create multiple entitlements in bulk
- post_entitlements_search - List entitlements by filter
- get_entitlements_id_ - Get an entitlement by ID
- put_entitlements_id_ - Update an entitlement
- delete_entitlements_id_ - Delete an entitlement
- get_plans_id_entitlements - Get plan entitlements
EntityIntegrationMappings
- get_entity_integration_mappings - List entity integration mappings
- post_entity_integration_mappings - Create entity integration mapping
- get_entity_integration_mappings_id_ - Get entity integration mapping
- delete_entity_integration_mappings_id_ - Delete entity integration mapping
Environments
- get_environments - Get environments
- post_environments - Create an environment
- get_environments_id_ - Get an environment
- put_environments_id_ - Update an environment
Events
- post_events - Ingest event
- post_events_analytics - Get usage analytics
- post_events_bulk - Bulk Ingest events
- post_events_huggingface_inference - Get hugging face inference data
- get_events_monitoring - Get monitoring data
- post_events_query - List raw events
- post_events_usage - Get usage statistics
- post_events_usage_meter - Get usage by meter
Features
- get_features - List features
- post_features - Create a new feature
- post_features_search - List features by filter
- get_features_id_ - Get a feature by ID
- put_features_id_ - Update a feature
- delete_features_id_ - Delete a feature
Groups
- post_groups - Create a group
- post_groups_search - Get groups
- get_groups_id_ - Get a group
- delete_groups_id_ - Delete a group
Integrations
- get_secrets_integrations_by_provider_provider_ - Get integration details
- post_secrets_integrations_create_provider_ - Create or update an integration
- get_secrets_integrations_linked - List linked integrations
- delete_secrets_integrations_id_ - Delete an integration
Invoices
- get_customers_id_invoices_summary - Get a customer invoice summary
- get_invoices - List invoices
- post_invoices - Create a new one off invoice
- post_invoices_preview - Get a preview invoice
- post_invoices_search - List invoices by filter
- get_invoices_id_ - Get an invoice by ID
- put_invoices_id_ - Update an invoice
- post_invoices_id_comms_trigger - Trigger communication webhook for an invoice
- post_invoices_id_finalize - Finalize an invoice
- put_invoices_id_payment - Update invoice payment status
- post_invoices_id_payment_attempt - Attempt payment for an invoice
- get_invoices_id_pdf - Get PDF for an invoice
- post_invoices_id_recalculate - Recalculate invoice totals and line items
- post_invoices_id_void - Void an invoice
Payments
- get_payments - List payments
- post_payments - Create a new payment
- get_payments_id_ - Get a payment by ID
- put_payments_id_ - Update a payment
- delete_payments_id_ - Delete a payment
- post_payments_id_process - Process a payment
Plans
- get_plans - Get plans
- post_plans - Create a new plan
- post_plans_search - List plans by filter
- get_plans_id_ - Get a plan
- put_plans_id_ - Update a plan
- delete_plans_id_ - Delete a plan
- post_plans_id_sync_subscriptions - Synchronize plan prices
PriceUnits
- get_prices_units - List price units
- post_prices_units - Create a new price unit
- get_prices_units_code_code_ - Get a price unit by code
- post_prices_units_search - List price units by filter
- get_prices_units_id_ - Get a price unit by ID
- put_prices_units_id_ - Update a price unit
- delete_prices_units_id_ - Delete a price unit
Prices
- get_prices - Get prices
- post_prices - Create a new price
- post_prices_bulk - Create multiple prices in bulk
- get_prices_id_ - Get a price by ID
- put_prices_id_ - Update a price
- delete_prices_id_ - Delete a price
Rbac
- get_rbac_roles - List all RBAC roles
- get_rbac_roles_id_ - Get a specific RBAC role
ScheduledTasks
- get_tasks_scheduled - List scheduled tasks
- post_tasks_scheduled - Create a scheduled task
- post_tasks_scheduled_schedule_update_billing_period - Schedule update billing period
- get_tasks_scheduled_id_ - Get a scheduled task
- put_tasks_scheduled_id_ - Update a scheduled task
- delete_tasks_scheduled_id_ - Delete a scheduled task
- post_tasks_scheduled_id_run - Trigger force run
Secrets
- get_secrets_api_keys - List API keys
- post_secrets_api_keys - Create a new API key
- delete_secrets_api_keys_id_ - Delete an API key
Subscriptions
- get_subscriptions - List subscriptions
- post_subscriptions - Create subscription
- post_subscriptions_addon - Add addon to subscription
- delete_subscriptions_addon - Remove addon from subscription
- put_subscriptions_lineitems_id_ - Update subscription line item
- delete_subscriptions_lineitems_id_ - Delete subscription line item
- post_subscriptions_search - List subscriptions by filter
- post_subscriptions_usage - Get usage by subscription
- get_subscriptions_id_ - Get subscription
- post_subscriptions_id_activate - Activate draft subscription
- get_subscriptions_id_addons_associations - Get active addon associations
- post_subscriptions_id_cancel - Cancel subscription
- post_subscriptions_id_change_execute - Execute subscription plan change
- post_subscriptions_id_change_preview - Preview subscription plan change
- get_subscriptions_id_entitlements - Get subscription entitlements
- get_subscriptions_id_grants_upcoming - Get upcoming credit grant applications
- post_subscriptions_id_pause - Pause a subscription
- get_subscriptions_id_pauses - List all pauses for a subscription
- post_subscriptions_id_resume - Resume a paused subscription
Tasks
- get_tasks - List tasks
- post_tasks - Create a new task
- get_tasks_result - Get task processing result
- get_tasks_id_ - Get a task
- put_tasks_id_status - Update task status
TaxAssociations
- get_taxes_associations - List tax associations
- post_taxes_associations - Create Tax Association
- get_taxes_associations_id_ - Get Tax Association
- put_taxes_associations_id_ - Update tax association
- delete_taxes_associations_id_ - Delete tax association
TaxRates
- get_taxes_rates - Get tax rates
- post_taxes_rates - Create a tax rate
- get_taxes_rates_id_ - Get a tax rate
- put_taxes_rates_id_ - Update a tax rate
- delete_taxes_rates_id_ - Delete a tax rate
Tenants
- get_tenant_billing - Get billing usage for the current tenant
- post_tenants - Create a new tenant
- put_tenants_update - Update a tenant
- get_tenants_id_ - Get tenant by ID
Users
- post_users - Create service account
- get_users_me - Get user info
- post_users_search - List users with filters
Wallets
- get_customers_wallets - Get Customer Wallets
- get_customers_id_wallets - Get wallets by customer ID
- get_wallets - List wallets
- post_wallets - Create a new wallet
- post_wallets_search - List wallets by filter
- post_wallets_transactions_search - List wallet transactions by filter
- get_wallets_id_ - Get wallet by ID
- put_wallets_id_ - Update a wallet
- get_wallets_id_balance_real_time - Get wallet balance
- post_wallets_id_terminate - Terminate a wallet
- post_wallets_id_top_up - Top up wallet
- get_wallets_id_transactions - Get wallet transactions
Webhooks
- post_webhooks_chargebee_tenant_id_environment_id_ - Handle Chargebee webhook events
- post_webhooks_hubspot_tenant_id_environment_id_ - Handle HubSpot webhook events
- post_webhooks_nomod_tenant_id_environment_id_ - Handle Nomod webhook events
- post_webhooks_quickbooks_tenant_id_environment_id_ - Handle QuickBooks webhook events
- post_webhooks_razorpay_tenant_id_environment_id_ - Handle Razorpay webhook events
- post_webhooks_stripe_tenant_id_environment_id_ - Handle Stripe webhook events
File uploads
Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
[!TIP]
For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.
from flexprice_sdk_test import FlexPrice
with FlexPrice(
server_url="https://api.example.com",
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
res = flex_price.events.post_events_analytics(request=open("example.file", "rb"))
# Handle response
print(res)
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 flexprice_sdk_test import FlexPrice
from flexprice_sdk_test.utils import BackoffStrategy, RetryConfig
with FlexPrice(
server_url="https://api.example.com",
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
res = flex_price.addons.get_addons(,
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:
from flexprice_sdk_test import FlexPrice
from flexprice_sdk_test.utils import BackoffStrategy, RetryConfig
with FlexPrice(
server_url="https://api.example.com",
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
res = flex_price.addons.get_addons()
# Handle response
print(res)
Error Handling
FlexPriceError 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 flexprice_sdk_test import FlexPrice
from flexprice_sdk_test.models import errors
with FlexPrice(
server_url="https://api.example.com",
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
res = None
try:
res = flex_price.addons.get_addons()
# Handle response
print(res)
except errors.FlexPriceError 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.ErrorsErrorResponse):
print(e.data.error) # Optional[components.ErrorsErrorDetail]
print(e.data.success) # Optional[bool]
Error Classes
Primary errors:
FlexPriceError: The base class for HTTP error responses.
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 FlexPriceError:
ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via thecauseattribute.
* Check the method documentation to see if the error is applicable.
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 flexprice_sdk_test import FlexPrice
import httpx
http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = FlexPrice(client=http_client)
or you could wrap the client with your own custom logic:
from flexprice_sdk_test import FlexPrice
from flexprice_sdk_test.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 = FlexPrice(async_client=CustomClient(httpx.AsyncClient()))
Resource Management
The FlexPrice 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 flexprice_sdk_test import FlexPrice
def main():
with FlexPrice(
server_url="https://api.example.com",
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
# Rest of application here...
# Or when using async:
async def amain():
async with FlexPrice(
server_url="https://api.example.com",
api_key_auth="<YOUR_API_KEY_HERE>",
) as flex_price:
# 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 flexprice_sdk_test import FlexPrice
import logging
logging.basicConfig(level=logging.DEBUG)
s = FlexPrice(server_url="https://example.com", debug_logger=logging.getLogger("flexprice_sdk_test"))
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
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file flexprice_sdk_test-2.0.20260104134957.tar.gz.
File metadata
- Download URL: flexprice_sdk_test-2.0.20260104134957.tar.gz
- Upload date:
- Size: 213.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e584d6516824c79f78f8ebe56eec03b73bdb45bc9cb3e1de39525f6f394f2d83
|
|
| MD5 |
9f20b62a7a1a3745f3512f87beea258f
|
|
| BLAKE2b-256 |
e60a1dab7d70dc814e8c5ef19c3242b73a5859fca6e879b30ea7e5fd2c49927a
|
File details
Details for the file flexprice_sdk_test-2.0.20260104134957-py3-none-any.whl.
File metadata
- Download URL: flexprice_sdk_test-2.0.20260104134957-py3-none-any.whl
- Upload date:
- Size: 460.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5460769d7e247bf1cad0fad6157552e526e18223d39259b8b51c7b4a1f4bc551
|
|
| MD5 |
d56b2ca7fc5cc67b0e2a75c16e013b3f
|
|
| BLAKE2b-256 |
1a282e79f96fc9a303446c32e3d82cbea67521713bfbb14a3a05d94d375b31f7
|