<div align="center">
<img src="https://github.com/dubinc/dub/assets/28986134/3815d859-afaa-48f9-a9b3-c09964e4d404" alt="Dub.co Python SDK to interact with APIs.">
<h3>Dub.co Python SDK</h3>
<a href="https://speakeasyapi.dev/"><img src="https://custom-icon-badges.demolab.com/badge/-Built%20By%20Speakeasy-212015?style=for-the-badge&logoColor=FBE331&logo=speakeasy&labelColor=545454" /></a>
<a href="https://opensource.org/licenses/MIT">
<img src="https://img.shields.io/badge/License-MIT-blue.svg" style="width: 100px; height: 28px;" />
</a>
</div>
<br/>
Learn more about the Dub.co Python SDK in the [official documentation](https://dub.co/docs/sdks/python/overview).
<!-- Start Summary [summary] -->
## Summary
Dub API: Dub is the modern link attribution platform for short links, conversion tracking, and affiliate programs.
<!-- End Summary [summary] -->
<!-- Start Table of Contents [toc] -->
## Table of Contents
<!-- $toc-max-depth=2 -->
* [SDK Installation](https://github.com/dubinc/dub-python/blob/master/#sdk-installation)
* [SDK Example Usage](https://github.com/dubinc/dub-python/blob/master/#sdk-example-usage)
* [Available Resources and Operations](https://github.com/dubinc/dub-python/blob/master/#available-resources-and-operations)
* [Error Handling](https://github.com/dubinc/dub-python/blob/master/#error-handling)
* [Server Selection](https://github.com/dubinc/dub-python/blob/master/#server-selection)
* [Custom HTTP Client](https://github.com/dubinc/dub-python/blob/master/#custom-http-client)
* [Authentication](https://github.com/dubinc/dub-python/blob/master/#authentication)
* [Retries](https://github.com/dubinc/dub-python/blob/master/#retries)
* [Pagination](https://github.com/dubinc/dub-python/blob/master/#pagination)
* [Resource Management](https://github.com/dubinc/dub-python/blob/master/#resource-management)
* [Debugging](https://github.com/dubinc/dub-python/blob/master/#debugging)
* [IDE Support](https://github.com/dubinc/dub-python/blob/master/#ide-support)
* [Development](https://github.com/dubinc/dub-python/blob/master/#development)
* [Contributions](https://github.com/dubinc/dub-python/blob/master/#contributions)
<!-- End Table of Contents [toc] -->
<!-- Start SDK Installation [installation] -->
## SDK Installation
> [!NOTE]
> **Python version upgrade policy**
>
> Once a Python version reaches its [official end of life date](https://devguide.python.org/versions/), 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.
```bash
uv add dub
```
### PIP
*PIP* is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
```bash
pip install dub
```
### 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.
```bash
poetry add dub
```
### Shell and script usage with `uv`
You can use this SDK in a Python shell with [uv](https://docs.astral.sh/uv/) and the `uvx` command that comes with it like so:
```shell
uvx --from dub python
```
It's also possible to write a standalone Python script without needing to set up a whole project like so:
```python
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "dub",
# ]
# ///
from dub import Dub
sdk = Dub(
# 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.
<!-- End SDK Installation [installation] -->
<!-- Start SDK Example Usage [usage] -->
## SDK Example Usage
### Example 1
```python
# Synchronous Example
from dub import Dub
with Dub(
token="DUB_API_KEY",
) as d_client:
res = d_client.links.create(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
})
assert res is not None
# Handle response
print(res)
```
</br>
The same SDK client can also be used to make asynchronous requests by importing asyncio.
```python
# Asynchronous Example
import asyncio
from dub import Dub
async def main():
async with Dub(
token="DUB_API_KEY",
) as d_client:
res = await d_client.links.create_async(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
})
assert res is not None
# Handle response
print(res)
asyncio.run(main())
```
### Example 2
```python
# Synchronous Example
from dub import Dub
with Dub(
token="DUB_API_KEY",
) as d_client:
res = d_client.links.upsert(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
})
assert res is not None
# Handle response
print(res)
```
</br>
The same SDK client can also be used to make asynchronous requests by importing asyncio.
```python
# Asynchronous Example
import asyncio
from dub import Dub
async def main():
async with Dub(
token="DUB_API_KEY",
) as d_client:
res = await d_client.links.upsert_async(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
})
assert res is not None
# Handle response
print(res)
asyncio.run(main())
```
<!-- End SDK Example Usage [usage] -->
<!-- Start Available Resources and Operations [operations] -->
## Available Resources and Operations
<details open>
<summary>Available methods</summary>
### [analytics](https://github.com/dubinc/dub-python/blob/master/docs/sdks/analytics/README.md)
* [retrieve](https://github.com/dubinc/dub-python/blob/master/docs/sdks/analytics/README.md#retrieve) - Retrieve analytics for a link, a domain, or the authenticated workspace.
### [commissions](https://github.com/dubinc/dub-python/blob/master/docs/sdks/commissions/README.md)
* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/commissions/README.md#list) - Get commissions for a program.
* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/commissions/README.md#update) - Update a commission.
### [customers](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md)
* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#list) - Retrieve a list of customers
* [~~create~~](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#create) - Create a customer :warning: **Deprecated**
* [get](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#get) - Retrieve a customer
* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#update) - Update a customer
* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#delete) - Delete a customer
### [domains](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md)
* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#create) - Create a domain
* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#list) - Retrieve a list of domains
* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#update) - Update a domain
* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#delete) - Delete a domain
* [register](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#register) - Register a domain
* [check_status](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#check_status) - Check the availability of one or more domains
### [embed_tokens](https://github.com/dubinc/dub-python/blob/master/docs/sdks/embedtokens/README.md)
* [referrals](https://github.com/dubinc/dub-python/blob/master/docs/sdks/embedtokens/README.md#referrals) - Create a referrals embed token
### [events](https://github.com/dubinc/dub-python/blob/master/docs/sdks/events/README.md)
* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/events/README.md#list) - Retrieve a list of events
### [folders](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md)
* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md#create) - Create a folder
* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md#list) - Retrieve a list of folders
* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md#update) - Update a folder
* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md#delete) - Delete a folder
### [links](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md)
* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#create) - Create a link
* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#list) - Retrieve a list of links
* [count](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#count) - Retrieve links count
* [get](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#get) - Retrieve a link
* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#update) - Update a link
* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#delete) - Delete a link
* [create_many](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#create_many) - Bulk create links
* [update_many](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#update_many) - Bulk update links
* [delete_many](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#delete_many) - Bulk delete links
* [upsert](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#upsert) - Upsert a link
### [partners](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md)
* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#create) - Create a partner
* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#list) - List all partners
* [create_link](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#create_link) - Create a link for a partner
* [retrieve_links](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#retrieve_links) - Retrieve a partner's links.
* [upsert_link](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#upsert_link) - Upsert a link for a partner
* [analytics](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#analytics) - Retrieve analytics for a partner
### [qr_codes](https://github.com/dubinc/dub-python/blob/master/docs/sdks/qrcodes/README.md)
* [get](https://github.com/dubinc/dub-python/blob/master/docs/sdks/qrcodes/README.md#get) - Retrieve a QR code
### [tags](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md)
* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md#create) - Create a tag
* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md#list) - Retrieve a list of tags
* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md#update) - Update a tag
* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md#delete) - Delete a tag
### [track](https://github.com/dubinc/dub-python/blob/master/docs/sdks/track/README.md)
* [lead](https://github.com/dubinc/dub-python/blob/master/docs/sdks/track/README.md#lead) - Track a lead
* [sale](https://github.com/dubinc/dub-python/blob/master/docs/sdks/track/README.md#sale) - Track a sale
### [workspaces](https://github.com/dubinc/dub-python/blob/master/docs/sdks/workspaces/README.md)
* [get](https://github.com/dubinc/dub-python/blob/master/docs/sdks/workspaces/README.md#get) - Retrieve a workspace
* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/workspaces/README.md#update) - Update a workspace
</details>
<!-- End Available Resources and Operations [operations] -->
<!-- Start Error Handling [errors] -->
## Error Handling
[`DubError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/duberror.py) 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](https://github.com/dubinc/dub-python/blob/master/#error-classes). |
### Example
```python
from dub import Dub
from dub.models import errors
with Dub(
token="DUB_API_KEY",
) as d_client:
res = None
try:
res = d_client.links.create(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
})
assert res is not None
# Handle response
print(res)
except errors.DubError 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.BadRequest):
print(e.data.error) # errors.Error
```
### Error Classes
**Primary errors:**
* [`DubError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/duberror.py): The base class for HTTP error responses.
* [`BadRequest`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/badrequest.py): The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Status code `400`.
* [`Unauthorized`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/unauthorized.py): Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. Status code `401`.
* [`Forbidden`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/forbidden.py): The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the client's identity is known to the server. Status code `403`.
* [`NotFound`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/notfound.py): The server cannot find the requested resource. Status code `404`.
* [`Conflict`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/conflict.py): This response is sent when a request conflicts with the current state of the server. Status code `409`.
* [`InviteExpired`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/inviteexpired.py): This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Status code `410`.
* [`UnprocessableEntity`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/unprocessableentity.py): The request was well-formed but was unable to be followed due to semantic errors. Status code `422`.
* [`RateLimitExceeded`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/ratelimitexceeded.py): The user has sent too many requests in a given amount of time ("rate limiting"). Status code `429`.
* [`InternalServerError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/internalservererror.py): The server has encountered a situation it does not know how to handle. Status code `500`.
<details><summary>Less common errors (5)</summary>
<br />
**Network errors:**
* [`httpx.RequestError`](https://www.python-httpx.org/exceptions/#httpx.RequestError): Base class for request errors.
* [`httpx.ConnectError`](https://www.python-httpx.org/exceptions/#httpx.ConnectError): HTTP client was unable to make a request to a server.
* [`httpx.TimeoutException`](https://www.python-httpx.org/exceptions/#httpx.TimeoutException): HTTP request timed out.
**Inherit from [`DubError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/duberror.py)**:
* [`ResponseValidationError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/responsevalidationerror.py): Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the `cause` attribute.
</details>
<!-- End Error Handling [errors] -->
<!-- Start Server Selection [server] -->
## Server Selection
### Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example:
```python
from dub import Dub
with Dub(
server_url="https://api.dub.co",
token="DUB_API_KEY",
) as d_client:
res = d_client.links.create(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
})
assert res is not None
# Handle response
print(res)
```
<!-- End Server Selection [server] -->
<!-- Start Custom HTTP Client [http-client] -->
## Custom HTTP Client
The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) 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:
```python
from dub import Dub
import httpx
http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = Dub(client=http_client)
```
or you could wrap the client with your own custom logic:
```python
from dub import Dub
from dub.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 = Dub(async_client=CustomClient(httpx.AsyncClient()))
```
<!-- End Custom HTTP Client [http-client] -->
<!-- Start Authentication [security] -->
## Authentication
### Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
| ------- | ---- | ----------- |
| `token` | http | HTTP Bearer |
To authenticate with the API the `token` parameter must be set when initializing the SDK client instance. For example:
```python
from dub import Dub
with Dub(
token="DUB_API_KEY",
) as d_client:
res = d_client.links.create(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
})
assert res is not None
# Handle response
print(res)
```
<!-- End Authentication [security] -->
<!-- Start Retries [retries] -->
## 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:
```python
from dub import Dub
from dub.utils import BackoffStrategy, RetryConfig
with Dub(
token="DUB_API_KEY",
) as d_client:
res = d_client.links.create(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
},
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:
```python
from dub import Dub
from dub.utils import BackoffStrategy, RetryConfig
with Dub(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
token="DUB_API_KEY",
) as d_client:
res = d_client.links.create(request={
"url": "https://google.com",
"external_id": "123456",
"tag_ids": [
"clux0rgak00011...",
],
"test_variants": [
{
"url": "https://example.com/variant-1",
"percentage": 50,
},
{
"url": "https://example.com/variant-2",
"percentage": 50,
},
],
})
assert res is not None
# Handle response
print(res)
```
<!-- End Retries [retries] -->
<!-- Start Pagination [pagination] -->
## 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:
```python
from dub import Dub
with Dub(
token="DUB_API_KEY",
) as d_client:
res = d_client.links.list(request={
"page_size": 50,
})
while res is not None:
# Handle items
res = res.next()
```
<!-- End Pagination [pagination] -->
<!-- Start Resource Management [resource-management] -->
## Resource Management
The `Dub` 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][context-manager] and reuse it across the application.
[context-manager]: https://docs.python.org/3/reference/datamodel.html#context-managers
```python
from dub import Dub
def main():
with Dub(
token="DUB_API_KEY",
) as d_client:
# Rest of application here...
# Or when using async:
async def amain():
async with Dub(
token="DUB_API_KEY",
) as d_client:
# Rest of application here...
```
<!-- End Resource Management [resource-management] -->
<!-- Start Debugging [debug] -->
## 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.
```python
from dub import Dub
import logging
logging.basicConfig(level=logging.DEBUG)
s = Dub(debug_logger=logging.getLogger("dub"))
```
<!-- End Debugging [debug] -->
<!-- Start IDE Support [idesupport] -->
## 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.
- [PyCharm Pydantic Plugin](https://docs.pydantic.dev/latest/integrations/pycharm/)
<!-- End IDE Support [idesupport] -->
<!-- Placeholder for Future Speakeasy SDK Sections -->
# Development
## Contributions
While we value open-source contributions to this SDK, this library is generated programmatically.
Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!
### SDK Created by [Speakeasy](https://docs.speakeasyapi.dev/docs/using-speakeasy/client-sdks)
Raw data
{
"_id": null,
"home_page": "https://github.com/dubinc/dub-python.git",
"name": "dub",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9.2",
"maintainer_email": null,
"keywords": null,
"author": "Speakeasy",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/2a/04/9150b21f0b06277f174eb8fa0b30d6bd5a81226428e83e3515d8148021d9/dub-0.29.3.tar.gz",
"platform": null,
"description": "<div align=\"center\">\n <img src=\"https://github.com/dubinc/dub/assets/28986134/3815d859-afaa-48f9-a9b3-c09964e4d404\" alt=\"Dub.co Python SDK to interact with APIs.\">\n <h3>Dub.co Python SDK</h3>\n <a href=\"https://speakeasyapi.dev/\"><img src=\"https://custom-icon-badges.demolab.com/badge/-Built%20By%20Speakeasy-212015?style=for-the-badge&logoColor=FBE331&logo=speakeasy&labelColor=545454\" /></a>\n <a href=\"https://opensource.org/licenses/MIT\">\n <img src=\"https://img.shields.io/badge/License-MIT-blue.svg\" style=\"width: 100px; height: 28px;\" />\n </a>\n</div>\n\n<br/>\n\nLearn more about the Dub.co Python SDK in the [official documentation](https://dub.co/docs/sdks/python/overview).\n\n<!-- Start Summary [summary] -->\n## Summary\n\nDub API: Dub is the modern link attribution platform for short links, conversion tracking, and affiliate programs.\n<!-- End Summary [summary] -->\n\n<!-- Start Table of Contents [toc] -->\n## Table of Contents\n<!-- $toc-max-depth=2 -->\n * [SDK Installation](https://github.com/dubinc/dub-python/blob/master/#sdk-installation)\n * [SDK Example Usage](https://github.com/dubinc/dub-python/blob/master/#sdk-example-usage)\n * [Available Resources and Operations](https://github.com/dubinc/dub-python/blob/master/#available-resources-and-operations)\n * [Error Handling](https://github.com/dubinc/dub-python/blob/master/#error-handling)\n * [Server Selection](https://github.com/dubinc/dub-python/blob/master/#server-selection)\n * [Custom HTTP Client](https://github.com/dubinc/dub-python/blob/master/#custom-http-client)\n * [Authentication](https://github.com/dubinc/dub-python/blob/master/#authentication)\n * [Retries](https://github.com/dubinc/dub-python/blob/master/#retries)\n * [Pagination](https://github.com/dubinc/dub-python/blob/master/#pagination)\n * [Resource Management](https://github.com/dubinc/dub-python/blob/master/#resource-management)\n * [Debugging](https://github.com/dubinc/dub-python/blob/master/#debugging)\n * [IDE Support](https://github.com/dubinc/dub-python/blob/master/#ide-support)\n* [Development](https://github.com/dubinc/dub-python/blob/master/#development)\n * [Contributions](https://github.com/dubinc/dub-python/blob/master/#contributions)\n\n<!-- End Table of Contents [toc] -->\n\n<!-- Start SDK Installation [installation] -->\n## SDK Installation\n\n> [!NOTE]\n> **Python version upgrade policy**\n>\n> Once a Python version reaches its [official end of life date](https://devguide.python.org/versions/), 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.\n\nThe SDK can be installed with *uv*, *pip*, or *poetry* package managers.\n\n### uv\n\n*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.\n\n```bash\nuv add dub\n```\n\n### PIP\n\n*PIP* is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.\n\n```bash\npip install dub\n```\n\n### Poetry\n\n*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.\n\n```bash\npoetry add dub\n```\n\n### Shell and script usage with `uv`\n\nYou can use this SDK in a Python shell with [uv](https://docs.astral.sh/uv/) and the `uvx` command that comes with it like so:\n\n```shell\nuvx --from dub python\n```\n\nIt's also possible to write a standalone Python script without needing to set up a whole project like so:\n\n```python\n#!/usr/bin/env -S uv run --script\n# /// script\n# requires-python = \">=3.9\"\n# dependencies = [\n# \"dub\",\n# ]\n# ///\n\nfrom dub import Dub\n\nsdk = Dub(\n # SDK arguments\n)\n\n# Rest of script here...\n```\n\nOnce that is saved to a file, you can run it with `uv run script.py` where\n`script.py` can be replaced with the actual file name.\n<!-- End SDK Installation [installation] -->\n\n<!-- Start SDK Example Usage [usage] -->\n## SDK Example Usage\n\n### Example 1\n\n```python\n# Synchronous Example\nfrom dub import Dub\n\n\nwith Dub(\n token=\"DUB_API_KEY\",\n) as d_client:\n\n res = d_client.links.create(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n })\n\n assert res is not None\n\n # Handle response\n print(res)\n```\n\n</br>\n\nThe same SDK client can also be used to make asynchronous requests by importing asyncio.\n```python\n# Asynchronous Example\nimport asyncio\nfrom dub import Dub\n\nasync def main():\n\n async with Dub(\n token=\"DUB_API_KEY\",\n ) as d_client:\n\n res = await d_client.links.create_async(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n })\n\n assert res is not None\n\n # Handle response\n print(res)\n\nasyncio.run(main())\n```\n\n### Example 2\n\n```python\n# Synchronous Example\nfrom dub import Dub\n\n\nwith Dub(\n token=\"DUB_API_KEY\",\n) as d_client:\n\n res = d_client.links.upsert(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n })\n\n assert res is not None\n\n # Handle response\n print(res)\n```\n\n</br>\n\nThe same SDK client can also be used to make asynchronous requests by importing asyncio.\n```python\n# Asynchronous Example\nimport asyncio\nfrom dub import Dub\n\nasync def main():\n\n async with Dub(\n token=\"DUB_API_KEY\",\n ) as d_client:\n\n res = await d_client.links.upsert_async(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n })\n\n assert res is not None\n\n # Handle response\n print(res)\n\nasyncio.run(main())\n```\n<!-- End SDK Example Usage [usage] -->\n\n<!-- Start Available Resources and Operations [operations] -->\n## Available Resources and Operations\n\n<details open>\n<summary>Available methods</summary>\n\n### [analytics](https://github.com/dubinc/dub-python/blob/master/docs/sdks/analytics/README.md)\n\n* [retrieve](https://github.com/dubinc/dub-python/blob/master/docs/sdks/analytics/README.md#retrieve) - Retrieve analytics for a link, a domain, or the authenticated workspace.\n\n### [commissions](https://github.com/dubinc/dub-python/blob/master/docs/sdks/commissions/README.md)\n\n* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/commissions/README.md#list) - Get commissions for a program.\n* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/commissions/README.md#update) - Update a commission.\n\n### [customers](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md)\n\n* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#list) - Retrieve a list of customers\n* [~~create~~](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#create) - Create a customer :warning: **Deprecated**\n* [get](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#get) - Retrieve a customer\n* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#update) - Update a customer\n* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/customers/README.md#delete) - Delete a customer\n\n### [domains](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md)\n\n* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#create) - Create a domain\n* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#list) - Retrieve a list of domains\n* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#update) - Update a domain\n* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#delete) - Delete a domain\n* [register](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#register) - Register a domain\n* [check_status](https://github.com/dubinc/dub-python/blob/master/docs/sdks/domains/README.md#check_status) - Check the availability of one or more domains\n\n\n### [embed_tokens](https://github.com/dubinc/dub-python/blob/master/docs/sdks/embedtokens/README.md)\n\n* [referrals](https://github.com/dubinc/dub-python/blob/master/docs/sdks/embedtokens/README.md#referrals) - Create a referrals embed token\n\n### [events](https://github.com/dubinc/dub-python/blob/master/docs/sdks/events/README.md)\n\n* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/events/README.md#list) - Retrieve a list of events\n\n### [folders](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md)\n\n* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md#create) - Create a folder\n* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md#list) - Retrieve a list of folders\n* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md#update) - Update a folder\n* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/folders/README.md#delete) - Delete a folder\n\n### [links](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md)\n\n* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#create) - Create a link\n* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#list) - Retrieve a list of links\n* [count](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#count) - Retrieve links count\n* [get](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#get) - Retrieve a link\n* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#update) - Update a link\n* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#delete) - Delete a link\n* [create_many](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#create_many) - Bulk create links\n* [update_many](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#update_many) - Bulk update links\n* [delete_many](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#delete_many) - Bulk delete links\n* [upsert](https://github.com/dubinc/dub-python/blob/master/docs/sdks/links/README.md#upsert) - Upsert a link\n\n### [partners](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md)\n\n* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#create) - Create a partner\n* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#list) - List all partners\n* [create_link](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#create_link) - Create a link for a partner\n* [retrieve_links](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#retrieve_links) - Retrieve a partner's links.\n* [upsert_link](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#upsert_link) - Upsert a link for a partner\n* [analytics](https://github.com/dubinc/dub-python/blob/master/docs/sdks/partners/README.md#analytics) - Retrieve analytics for a partner\n\n### [qr_codes](https://github.com/dubinc/dub-python/blob/master/docs/sdks/qrcodes/README.md)\n\n* [get](https://github.com/dubinc/dub-python/blob/master/docs/sdks/qrcodes/README.md#get) - Retrieve a QR code\n\n### [tags](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md)\n\n* [create](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md#create) - Create a tag\n* [list](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md#list) - Retrieve a list of tags\n* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md#update) - Update a tag\n* [delete](https://github.com/dubinc/dub-python/blob/master/docs/sdks/tags/README.md#delete) - Delete a tag\n\n### [track](https://github.com/dubinc/dub-python/blob/master/docs/sdks/track/README.md)\n\n* [lead](https://github.com/dubinc/dub-python/blob/master/docs/sdks/track/README.md#lead) - Track a lead\n* [sale](https://github.com/dubinc/dub-python/blob/master/docs/sdks/track/README.md#sale) - Track a sale\n\n### [workspaces](https://github.com/dubinc/dub-python/blob/master/docs/sdks/workspaces/README.md)\n\n* [get](https://github.com/dubinc/dub-python/blob/master/docs/sdks/workspaces/README.md#get) - Retrieve a workspace\n* [update](https://github.com/dubinc/dub-python/blob/master/docs/sdks/workspaces/README.md#update) - Update a workspace\n\n</details>\n<!-- End Available Resources and Operations [operations] -->\n\n<!-- Start Error Handling [errors] -->\n## Error Handling\n\n[`DubError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/duberror.py) is the base class for all HTTP error responses. It has the following properties:\n\n| Property | Type | Description |\n| ------------------ | ---------------- | --------------------------------------------------------------------------------------- |\n| `err.message` | `str` | Error message |\n| `err.status_code` | `int` | HTTP response status code eg `404` |\n| `err.headers` | `httpx.Headers` | HTTP response headers |\n| `err.body` | `str` | HTTP body. Can be empty string if no body is returned. |\n| `err.raw_response` | `httpx.Response` | Raw HTTP response |\n| `err.data` | | Optional. Some errors may contain structured data. [See Error Classes](https://github.com/dubinc/dub-python/blob/master/#error-classes). |\n\n### Example\n```python\nfrom dub import Dub\nfrom dub.models import errors\n\n\nwith Dub(\n token=\"DUB_API_KEY\",\n) as d_client:\n res = None\n try:\n\n res = d_client.links.create(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n })\n\n assert res is not None\n\n # Handle response\n print(res)\n\n\n except errors.DubError as e:\n # The base class for HTTP error responses\n print(e.message)\n print(e.status_code)\n print(e.body)\n print(e.headers)\n print(e.raw_response)\n\n # Depending on the method different errors may be thrown\n if isinstance(e, errors.BadRequest):\n print(e.data.error) # errors.Error\n```\n\n### Error Classes\n**Primary errors:**\n* [`DubError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/duberror.py): The base class for HTTP error responses.\n * [`BadRequest`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/badrequest.py): The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Status code `400`.\n * [`Unauthorized`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/unauthorized.py): Although the HTTP standard specifies \"unauthorized\", semantically this response means \"unauthenticated\". That is, the client must authenticate itself to get the requested response. Status code `401`.\n * [`Forbidden`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/forbidden.py): The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the client's identity is known to the server. Status code `403`.\n * [`NotFound`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/notfound.py): The server cannot find the requested resource. Status code `404`.\n * [`Conflict`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/conflict.py): This response is sent when a request conflicts with the current state of the server. Status code `409`.\n * [`InviteExpired`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/inviteexpired.py): This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Status code `410`.\n * [`UnprocessableEntity`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/unprocessableentity.py): The request was well-formed but was unable to be followed due to semantic errors. Status code `422`.\n * [`RateLimitExceeded`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/ratelimitexceeded.py): The user has sent too many requests in a given amount of time (\"rate limiting\"). Status code `429`.\n * [`InternalServerError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/internalservererror.py): The server has encountered a situation it does not know how to handle. Status code `500`.\n\n<details><summary>Less common errors (5)</summary>\n\n<br />\n\n**Network errors:**\n* [`httpx.RequestError`](https://www.python-httpx.org/exceptions/#httpx.RequestError): Base class for request errors.\n * [`httpx.ConnectError`](https://www.python-httpx.org/exceptions/#httpx.ConnectError): HTTP client was unable to make a request to a server.\n * [`httpx.TimeoutException`](https://www.python-httpx.org/exceptions/#httpx.TimeoutException): HTTP request timed out.\n\n\n**Inherit from [`DubError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/duberror.py)**:\n* [`ResponseValidationError`](https://github.com/dubinc/dub-python/blob/master/./src/dub/models/errors/responsevalidationerror.py): Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the `cause` attribute.\n\n</details>\n<!-- End Error Handling [errors] -->\n\n<!-- Start Server Selection [server] -->\n## Server Selection\n\n### Override Server URL Per-Client\n\nThe default server can be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example:\n```python\nfrom dub import Dub\n\n\nwith Dub(\n server_url=\"https://api.dub.co\",\n token=\"DUB_API_KEY\",\n) as d_client:\n\n res = d_client.links.create(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n })\n\n assert res is not None\n\n # Handle response\n print(res)\n\n```\n<!-- End Server Selection [server] -->\n\n<!-- Start Custom HTTP Client [http-client] -->\n## Custom HTTP Client\n\nThe Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) 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.\nDepending 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.\nThis 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.\n\nFor example, you could specify a header for every request that this sdk makes as follows:\n```python\nfrom dub import Dub\nimport httpx\n\nhttp_client = httpx.Client(headers={\"x-custom-header\": \"someValue\"})\ns = Dub(client=http_client)\n```\n\nor you could wrap the client with your own custom logic:\n```python\nfrom dub import Dub\nfrom dub.httpclient import AsyncHttpClient\nimport httpx\n\nclass CustomClient(AsyncHttpClient):\n client: AsyncHttpClient\n\n def __init__(self, client: AsyncHttpClient):\n self.client = client\n\n async def send(\n self,\n request: httpx.Request,\n *,\n stream: bool = False,\n auth: Union[\n httpx._types.AuthTypes, httpx._client.UseClientDefault, None\n ] = httpx.USE_CLIENT_DEFAULT,\n follow_redirects: Union[\n bool, httpx._client.UseClientDefault\n ] = httpx.USE_CLIENT_DEFAULT,\n ) -> httpx.Response:\n request.headers[\"Client-Level-Header\"] = \"added by client\"\n\n return await self.client.send(\n request, stream=stream, auth=auth, follow_redirects=follow_redirects\n )\n\n def build_request(\n self,\n method: str,\n url: httpx._types.URLTypes,\n *,\n content: Optional[httpx._types.RequestContent] = None,\n data: Optional[httpx._types.RequestData] = None,\n files: Optional[httpx._types.RequestFiles] = None,\n json: Optional[Any] = None,\n params: Optional[httpx._types.QueryParamTypes] = None,\n headers: Optional[httpx._types.HeaderTypes] = None,\n cookies: Optional[httpx._types.CookieTypes] = None,\n timeout: Union[\n httpx._types.TimeoutTypes, httpx._client.UseClientDefault\n ] = httpx.USE_CLIENT_DEFAULT,\n extensions: Optional[httpx._types.RequestExtensions] = None,\n ) -> httpx.Request:\n return self.client.build_request(\n method,\n url,\n content=content,\n data=data,\n files=files,\n json=json,\n params=params,\n headers=headers,\n cookies=cookies,\n timeout=timeout,\n extensions=extensions,\n )\n\ns = Dub(async_client=CustomClient(httpx.AsyncClient()))\n```\n<!-- End Custom HTTP Client [http-client] -->\n\n<!-- Start Authentication [security] -->\n## Authentication\n\n### Per-Client Security Schemes\n\nThis SDK supports the following security scheme globally:\n\n| Name | Type | Scheme |\n| ------- | ---- | ----------- |\n| `token` | http | HTTP Bearer |\n\nTo authenticate with the API the `token` parameter must be set when initializing the SDK client instance. For example:\n```python\nfrom dub import Dub\n\n\nwith Dub(\n token=\"DUB_API_KEY\",\n) as d_client:\n\n res = d_client.links.create(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n })\n\n assert res is not None\n\n # Handle response\n print(res)\n\n```\n<!-- End Authentication [security] -->\n\n<!-- Start Retries [retries] -->\n## Retries\n\nSome 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.\n\nTo change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call:\n```python\nfrom dub import Dub\nfrom dub.utils import BackoffStrategy, RetryConfig\n\n\nwith Dub(\n token=\"DUB_API_KEY\",\n) as d_client:\n\n res = d_client.links.create(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n },\n RetryConfig(\"backoff\", BackoffStrategy(1, 50, 1.1, 100), False))\n\n assert res is not None\n\n # Handle response\n print(res)\n\n```\n\nIf 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:\n```python\nfrom dub import Dub\nfrom dub.utils import BackoffStrategy, RetryConfig\n\n\nwith Dub(\n retry_config=RetryConfig(\"backoff\", BackoffStrategy(1, 50, 1.1, 100), False),\n token=\"DUB_API_KEY\",\n) as d_client:\n\n res = d_client.links.create(request={\n \"url\": \"https://google.com\",\n \"external_id\": \"123456\",\n \"tag_ids\": [\n \"clux0rgak00011...\",\n ],\n \"test_variants\": [\n {\n \"url\": \"https://example.com/variant-1\",\n \"percentage\": 50,\n },\n {\n \"url\": \"https://example.com/variant-2\",\n \"percentage\": 50,\n },\n ],\n })\n\n assert res is not None\n\n # Handle response\n print(res)\n\n```\n<!-- End Retries [retries] -->\n\n<!-- Start Pagination [pagination] -->\n## Pagination\n\nSome of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the\nreturned response object will have a `Next` method that can be called to pull down the next group of results. If the\nreturn value of `Next` is `None`, then there are no more pages to be fetched.\n\nHere's an example of one such pagination call:\n```python\nfrom dub import Dub\n\n\nwith Dub(\n token=\"DUB_API_KEY\",\n) as d_client:\n\n res = d_client.links.list(request={\n \"page_size\": 50,\n })\n\n while res is not None:\n # Handle items\n\n res = res.next()\n\n```\n<!-- End Pagination [pagination] -->\n\n<!-- Start Resource Management [resource-management] -->\n## Resource Management\n\nThe `Dub` 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][context-manager] and reuse it across the application.\n\n[context-manager]: https://docs.python.org/3/reference/datamodel.html#context-managers\n\n```python\nfrom dub import Dub\ndef main():\n\n with Dub(\n token=\"DUB_API_KEY\",\n ) as d_client:\n # Rest of application here...\n\n\n# Or when using async:\nasync def amain():\n\n async with Dub(\n token=\"DUB_API_KEY\",\n ) as d_client:\n # Rest of application here...\n```\n<!-- End Resource Management [resource-management] -->\n\n<!-- Start Debugging [debug] -->\n## Debugging\n\nYou can setup your SDK to emit debug logs for SDK requests and responses.\n\nYou can pass your own logger class directly into your SDK.\n```python\nfrom dub import Dub\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\ns = Dub(debug_logger=logging.getLogger(\"dub\"))\n```\n<!-- End Debugging [debug] -->\n\n<!-- Start IDE Support [idesupport] -->\n## IDE Support\n\n### PyCharm\n\nGenerally, 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.\n\n- [PyCharm Pydantic Plugin](https://docs.pydantic.dev/latest/integrations/pycharm/)\n<!-- End IDE Support [idesupport] -->\n\n<!-- Placeholder for Future Speakeasy SDK Sections -->\n\n# Development\n\n## Contributions\n\nWhile we value open-source contributions to this SDK, this library is generated programmatically.\nFeel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!\n\n### SDK Created by [Speakeasy](https://docs.speakeasyapi.dev/docs/using-speakeasy/client-sdks)\n",
"bugtrack_url": null,
"license": null,
"summary": "Python Client SDK Generated by Speakeasy",
"version": "0.29.3",
"project_urls": {
"Homepage": "https://github.com/dubinc/dub-python.git",
"Repository": "https://github.com/dubinc/dub-python.git"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "5c938431c3bef4bead56419e4eb5991155e7c0b54032bb30f32822b335799eb0",
"md5": "07b0bc7ae2022eef3ce40f418533cb30",
"sha256": "86b4fa6aa03f598da35600fe4f2dd7ac359d710471689b0acc04e3c5746dece4"
},
"downloads": -1,
"filename": "dub-0.29.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "07b0bc7ae2022eef3ce40f418533cb30",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9.2",
"size": 223613,
"upload_time": "2025-09-12T16:28:59",
"upload_time_iso_8601": "2025-09-12T16:28:59.821797Z",
"url": "https://files.pythonhosted.org/packages/5c/93/8431c3bef4bead56419e4eb5991155e7c0b54032bb30f32822b335799eb0/dub-0.29.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "2a049150b21f0b06277f174eb8fa0b30d6bd5a81226428e83e3515d8148021d9",
"md5": "27d511d42086fa36a97ed39774c82a72",
"sha256": "f65f9b54ea1c7dc4a5efa8eb0f67515fbaf0d0b652605d00b70f7f8b7c2a284a"
},
"downloads": -1,
"filename": "dub-0.29.3.tar.gz",
"has_sig": false,
"md5_digest": "27d511d42086fa36a97ed39774c82a72",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9.2",
"size": 119411,
"upload_time": "2025-09-12T16:29:01",
"upload_time_iso_8601": "2025-09-12T16:29:01.477391Z",
"url": "https://files.pythonhosted.org/packages/2a/04/9150b21f0b06277f174eb8fa0b30d6bd5a81226428e83e3515d8148021d9/dub-0.29.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-12 16:29:01",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "dubinc",
"github_project": "dub-python",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "dub"
}