Skip to content

How to use?

Essential steps:

Before you start using this wrapper, you should perform these essential steps:

  1. Create a virtual environment:

    • Using python:
    python -m venv .venv
    source .venv/bin/activate
    
    • Using uv:
    uv python pin 3.11
    uv init
    uv sync
    
  2. Create .env and put your customer number, contract id and api key in there as followed:

    CUSTOMER_NUMBER=12345667
    CONTRACT_ID=12344556
    API_KEY=ewfghui34hto34ghui34g:ewghui234h23oih34uigh423
    

    To test this app, you will need some test credentials. You can get them here.

    If you would like to obtain your own, you can register your business and join the Developer Program.

Quick start

To use this wrapper, you will need 3.11+ python version and pip.

Install from PyPi

pip install py-canada-post
or
uv add py-canada-post

Install from source

  1. Clone the repository:
git clone https://github.com/joludyaster/py-canada-post.git
  1. Run:

pip install .
or
uv pip install .

Getting started

You could define the client object yourself:

import os

from py_canada_post.client import PyCanadaPost
from py_canada_post.services.rating import Destination, DomesticDestination, ParcelCharacteristics
from dotenv import load_dotenv

load_dotenv()

customer_number = os.getenv("CUSTOMER_NUMBER", 0)
api_key = os.getenv("API_KEY", "")
contract_id = os.getenv("CONTRACT_ID", 0)

def main():
    py_canada_post_client = PyCanadaPost(
        customer_number=customer_number,
        api_key=api_key,
        contract_id=contract_id
    )
    rates = py_canada_post_client.rating.rates.get_rates(
        origin_postal_code="E4M8S3",
        destination=Destination(
            domestic=DomesticDestination("T3Z1C8")
        ),
        parcel_characteristics=ParcelCharacteristics(
            weight=13.2
        )
    )
    print(rates)

if __name__ == "__main__":
    main()

Or you could use a shortcut:

from py_canada_post.client import PyCanadaPost
from py_canada_post.services.rating import Destination, DomesticDestination, ParcelCharacteristics

def main():
    py_canada_post_client = PyCanadaPost.from_env()
    rates = py_canada_post_client.rating.rates.get_rates(
        origin_postal_code="E4M8S3",
        destination=Destination(
            domestic=DomesticDestination("T3Z1C8")
        ),
        parcel_characteristics=ParcelCharacteristics(
            weight=13.2
        )
    )
    print(rates)

if __name__ == "__main__":
    main()

See usage documentation to learn more about the commands.