8000 GitHub - goshippo/shippo-python-sdk
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

goshippo/shippo-python-sdk

Repository files navigation

Shippo logo Shippo Python SDK

Shippo is a shipping API that connects you with multiple shipping carriers (such as USPS, UPS, DHL, Canada Post, Australia Post, and many others) through one interface.

You must register for a Shippo account to use our API. It's free to sign up. Only pay to print a live label, test labels are free.

To use the API, you must generate an API Token. In the following examples, replace <YOUR_API_KEY_HERE> with your own token.

For example.

api_key_header="shippo_test_595d9cb0c0e14497bf07e75ecfec6c6d"

Summary

Shippo external API.: Use this API to integrate with the Shippo service

Table of Contents

SDK Installation

Python version upgrade policy

Once a Python version reaches its official end of life date, a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.

The SDK can be installed with either pip or poetry package managers.

PIP

PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.

pip install shippo

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 shippo

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 shippo 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 = [
#     "shippo",
# ]
# ///

from shippo import Shippo

sdk = Shippo(
  # 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.

SDK Reinstallation to a specific version

pip install --force-reinstall -I shippo==3.4.4

SDK Example Usage

Example

import shippo

shippo_sdk = shippo.Shippo(
    api_key_header="<YOUR_API_KEY_HERE>",
    # the API version can be globally set, though this is normally not required
    # shippo_api_version='<YYYY-MM-DD>',
)

address_list = shippo_sdk.addresses.list()

if address_list is not None:
    # handle response
    pass

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 shippo import Shippo
from shippo.utils import BackoffStrategy, RetryConfig


with Shippo(
    api_key_header="<YOUR_API_KEY_HERE>",
    shippo_api_version="2018-02-08",
) as s_client:

    res = s_client.addresses.list(,
        RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))

    assert res is not None

    # Handle response
    print(res)

If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:

from shippo import Shippo
from shippo.utils import BackoffStrategy, RetryConfig


with Shippo(
    retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
    api_key_header="<YOUR_API_KEY_HERE>",
    shippo_api_version="2018-02-08",
) as s_client:

    res = s_client.addresses.list()

    assert res is not None

    # Handle response
    print(res)

Custom HTTP Client

The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.

For example, you could specify a header for every request that this sdk makes as follows:

from shippo import Shippo
import httpx

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

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

from shippo import Shippo
from shippo.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 = Shippo(async_client=CustomClient(httpx.AsyncClient()))

Debug HTTP Client

The Shippo Python SDK returns schema models directly rather than wrapping the response in an envelope along with additional request/response details (status code, raw json, etc). However, there are times when the underlying http information is useful so a 'debug' client is provided. Using this client, you can retrieve the requests.PreparedRequest and requests.Response from the most recent API call.

import shippo
from shippo.debug import DebugSession

debug_session = DebugSession()
shippo_sdk = shippo.Shippo(api_key_header="<YOUR_API_KEY_HERE>", client=debug_session)

shippo_sdk.addresses.list()

# print the previous request http headers
print(debug_session.last_request.headers)  
# print the previous response status code and raw json
print(debug_session.last_response.status_code, debug_session.last_response.text)

Documentation

Review our full guides and references at https://docs.goshippo.com/.

Resource Management

The Shippo 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 shippo import Shippo
def main():

    with Shippo(
        api_key_header="<YOUR_API_KEY_HERE>",
        shippo_api_version="2018-02-08",
    ) as s_client:
        # Rest of application here...


# Or when using async:
async def amain():

    async with Shippo(
        api_key_header="<YOUR_API_KEY_HERE>",
        shippo_api_version="2018-02-08",
    ) as s_client:
        # Rest of application here...

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass your own logger class directly into your SDK.

from shippo import Shippo
import logging

logging.basicConfig(level=logging.DEBUG)
s = Shippo(debug_logger=logging.getLogger("shippo"))

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.

Available Resources and Operations

Available methods
  • list - List all addresses
  • create - Create a new address
  • get - Retrieve an address
  • validate - Validate an address
  • list - List all carrier parcel templates
  • get - Retrieve a carrier parcel templates
  • list - List all customs declarations
  • create - Create a new customs declaration
  • get - Retrieve a customs declaration
  • list - List all customs items
  • create - Create a new customs item
  • get - Retrieve a customs item
  • list - List all manifests
  • create - Create a new manifest
  • get - Retrieve a manifest
  • list - List all orders
  • create - Create a new order
  • get - Retrieve an order
  • list - List all parcels
  • create - Create a new parcel
  • get - Retrieve an existing parcel
  • create - Create a refund
  • list - List all refunds
  • get - Retrieve a refund
  • list - List all service groups
  • create - Create a new service group
  • update - Update an existing service group
  • delete - Delete a service group
  • list - List all shipments
  • create - Create a new shipment
  • get - Retrieve a shipment
  • list - List all Shippo Accounts
  • create - Create a Shippo Account
  • get - Retrieve a Shippo Account
  • update - Update a Shippo Account
  • create - Register a tracking webhook
  • get - Get a tracking status
  • list - List all shipping labels
  • create - Create a shipping label
  • get - Retrieve a shipping label
  • list - List all user parcel templates
  • create - Create a new user parcel template
  • delete - Delete a user parcel template
  • get - Retrieves a user parcel template
  • update - Update an existing user parcel template

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

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.

About Shippo

Connect with multiple different carriers, get discounted shipping labels, track parcels, and much more with just one integration. You can use your own carrier accounts or take advantage of our discounted rates with the Shippo carrier accounts. Using Shippo makes it easy to deal with multiple carrier integrations, rate shopping, tracking and other parts of the shipping workflow. We provide the API and web app for all your shipping needs.

0