Skip to main content

Professional Python package for SteadFast Courier API integration

Project description

SteadFast Courier Python Package

Python Version License Status Author

A professional Python package for integrating with SteadFast Courier API. This package provides a clean, well-structured interface for all SteadFast API endpoints with built-in validation, rate limiting, and comprehensive error handling. Works seamlessly with Django, FastAPI, Flask, and all Python frameworks.

✨ Features

  • Complete API Coverage - All SteadFast Courier API endpoints implemented
  • Multi-Framework Support - Django, FastAPI, Flask, and any Python framework
  • Environment Variable Support - Secure credential management with .env files via from_env() method
  • API Key Authentication - Secure authentication with API Key and Secret Key
  • Rate Limiting - Built-in protection against API abuse (configurable)
  • Input Validation - Comprehensive validation before API calls
  • Error Handling - Detailed exception messages with field-level errors
  • Type Hints - Full type hints for better IDE support
  • Zero Configuration - Works out of the box with sensible defaults
  • Production Ready - Battle-tested in production environments
  • Logging Support - Built-in logging for debugging and monitoring

📋 Requirements

  • Python >= 3.8
  • requests >= 2.28.0

📦 Installation

Install the package via pip:

pip install steadfast-courier

⚙️ Configuration

Setup Environment Variables

Create a .env file in your project root:

STEADFAST_API_KEY=your-api-key
STEADFAST_SECRET_KEY=your-secret-key
STEADFAST_BASE_URL=https://portal.packzy.com/api/v1  # Optional
STEADFAST_TIMEOUT=30  # Optional

Or copy the provided template:

cp .env.example .env

Then edit .env with your credentials. Note: You can obtain your API credentials from the SteadFast Courier Portal.

🚀 Quick Start

Option 1: Using Environment Variables (Recommended)

from steadfast_courier import SteadfastCourier
from dotenv import load_dotenv

# Load environment variables from .env
load_dotenv()

# Initialize client from environment variables
client = SteadfastCourier.from_env()

# Place an order
order_data = {
    'invoice': 'ORD-123456',
    'recipient_name': 'John Doe',
    'recipient_phone': '01712345678',
    'recipient_address': 'House 44, Road 2/A, Dhanmondi, Dhaka 1209',
    'cod_amount': 1000.00,
    'note': 'Handle with care',
}

try:
    response = client.order().place_order(order_data)
    print(f"Order created! Consignment ID: {response['consignment']['consignment_id']}")
except Exception as e:
    print(f"Error: {e}")

Option 2: Using Explicit Credentials

from steadfast_courier import SteadfastCourier

# Initialize the client with explicit credentials
client = SteadfastCourier(
    api_key='your-api-key',
    secret_key='your-secret-key'
)

# Place an order
order_data = {
    'invoice': 'ORD-123456',
    'recipient_name': 'John Doe',
    'recipient_phone': '01712345678',
    'recipient_address': 'House 44, Road 2/A, Dhanmondi, Dhaka 1209',
    'cod_amount': 1000.00,
    'note': 'Handle with care',
}

try:
    response = client.order().place_order(order_data)
    print(f"Order created! Consignment ID: {response['consignment']['consignment_id']}")
except Exception as e:
    print(f"Error: {e}")

Django Integration

See Django Integration Guide

# settings.py - Add at the top
from dotenv import load_dotenv
load_dotenv()

# views.py
from steadfast_courier import SteadfastCourier

def create_order(request):
    # Initialize from environment variables
    client = SteadfastCourier.from_env()

    order_data = {
        'invoice': f'ORD-{request.POST.get("invoice")}',
        'recipient_name': request.POST.get('name'),
        'recipient_phone': request.POST.get('phone'),
        'recipient_address': request.POST.get('address'),
        'cod_amount': float(request.POST.get('cod_amount')),
    }

    try:
        response = client.order().place_order(order_data)
        return {'success': True, 'data': response}
    except Exception as e:
        return {'success': False, 'error': str(e)}

FastAPI Integration

See FastAPI Integration Guide

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from dotenv import load_dotenv
from steadfast_courier import SteadfastCourier

load_dotenv()

app = FastAPI()

# Initialize client from environment variables
STEADFAST_CLIENT = SteadfastCourier.from_env()

class OrderRequest(BaseModel):
    invoice: str
    recipient_name: str
    recipient_phone: str
    recipient_address: str
    cod_amount: float

@app.post("/orders/")
async def create_order(order: OrderRequest):
    try:
        response = STEADFAST_CLIENT.order().place_order(order.dict())
        return {"success": True, "data": response}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

Flask Integration

See Flask Integration Guide

from flask import Flask, request, jsonify
from dotenv import load_dotenv
from steadfast_courier import SteadfastCourier

load_dotenv()

app = Flask(__name__)

# Initialize client from environment variables
client = SteadfastCourier.from_env()

@app.route('/orders', methods=['POST'])
def create_order():
    data = request.json
    order_data = {
        'invoice': data.get('invoice'),
        'recipient_name': data.get('recipient_name'),
        'recipient_phone': data.get('recipient_phone'),
        'recipient_address': data.get('recipient_address'),
        'cod_amount': float(data.get('cod_amount')),
    }

    try:
        response = client.order().place_order(order_data)
        return jsonify({"success": True, "data": response})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 400

if __name__ == '__main__':
    app.run(debug=True)

📚 API Documentation

Order Management

Place Single Order

client.order().place_order({
    'invoice': 'ORD-123456',
    'recipient_name': 'John Doe',
    'recipient_phone': '01712345678',
    'recipient_address': 'House 44, Road 2/A, Dhanmondi, Dhaka 1209',
    'cod_amount': 1000.00,
    'note': 'Handle with care',  # Optional
    'recipient_email': 'john@example.com',  # Optional
    'alternative_phone': '01812345678',  # Optional
    'item_description': 'Product description',  # Optional
    'total_lot': 1,  # Optional
    'delivery_type': 0,  # Optional: 0=home, 1=hub
})

Place Bulk Orders

orders = [
    {
        'invoice': 'ORD-001',
        'recipient_name': 'Customer 1',
        'recipient_phone': '01712345678',
        'recipient_address': 'Address 1',
        'cod_amount': 500.00,
    },
    {
        'invoice': 'ORD-002',
        'recipient_name': 'Customer 2',
        'recipient_phone': '01812345678',
        'recipient_address': 'Address 2',
        'cod_amount': 1000.00,
    }
]

client.order().place_bulk_orders(orders)

Status Tracking

# Check status by consignment ID
client.status().get_status_by_consignment_id(12345)

# Check status by invoice
client.status().get_status_by_invoice('ORD-123456')

# Check status by tracking code
client.status().get_status_by_tracking_code('TRAC123456789')

Account Balance

balance = client.balance().get_current_balance()
print(f"Current balance: {balance['balance']}")

Payment Management

# Get all payments
client.payment().get_payments()

# Get specific payment
client.payment().get_payment(123)

Return Management

# Create return request
client.return_api().create_return_request({
    'invoice': 'ORD-123456',
    'reason': 'Customer requested return'
})

# Get return requests
client.return_api().get_return_requests()

# Get specific return request
client.return_api().get_return_request(123)

Police Stations

# Get list of police stations
stations = client.police_station().get_police_stations()

🔧 Error Handling

from steadfast_courier import SteadfastCourier, SteadfastException

client = SteadfastCourier(api_key='key', secret_key='secret')

try:
    response = client.order().place_order(order_data)
except SteadfastException as e:
    print(f"API Error: {e}")
    print(f"Status Code: {e.code}")
    print(f"Errors: {e.get_errors()}")
except Exception as e:
    print(f"Unexpected error: {e}")

🔐 Security Best Practices

  1. Never hardcode API keys - Use environment variables
  2. Use .env files - Keep credentials out of version control
  3. Validate inputs - The package validates automatically, but check user inputs
  4. Use HTTPS - Always use secure connections
  5. Rate limiting - Be aware of rate limits to avoid blocking

📝 Logging

Enable logging to monitor API calls:

import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('steadfast_courier')

🧪 Testing

import unittest
from steadfast_courier import SteadfastCourier, SteadfastException

class TestSteadfastCourier(unittest.TestCase):
    def setUp(self):
        self.client = SteadfastCourier(
            api_key='test-key',
            secret_key='test-secret'
        )

    def test_invalid_phone(self):
        with self.assertRaises(SteadfastException):
            self.client.order().place_order({
                'invoice': 'ORD-001',
                'recipient_name': 'Test User',
                'recipient_phone': '123',  # Invalid
                'recipient_address': 'Test Address',
                'cod_amount': 100,
            })

if __name__ == '__main__':
    unittest.main()

📞 Support

📄 License

This package is open-sourced software licensed under the MIT License. See the LICENSE file for details.

🙏 Credits

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📦 Version History

  • 1.0.0 (2024-05-29) - Initial Python port with full API coverage and framework integrations

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

steadfast_courier-1.1.1.tar.gz (16.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

steadfast_courier-1.1.1-py3-none-any.whl (17.2 kB view details)

Uploaded Python 3

File details

Details for the file steadfast_courier-1.1.1.tar.gz.

File metadata

  • Download URL: steadfast_courier-1.1.1.tar.gz
  • Upload date:
  • Size: 16.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for steadfast_courier-1.1.1.tar.gz
Algorithm Hash digest
SHA256 73e12b0042794d9eda6aa3830c478400bc102fcc5cac8a4eabf4fc0091f88535
MD5 402b04d460e27ff54e66af17f1185ded
BLAKE2b-256 db64c254977926c6feed19d959c158aa011825517edbe795823affc5689fdc12

See more details on using hashes here.

File details

Details for the file steadfast_courier-1.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for steadfast_courier-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 823c0435cfa9c4ad14ebdbea1128eadb8cfb4d7ee1419d1113b08540505c4adc
MD5 658ebdf4f8894c89b1a663656b7c5498
BLAKE2b-256 7c6188b1a1ede6441fda7d8cc706af3c9e332fa8ec2e260c4059ae4c074ff820

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page