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
  • 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

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

Note: You can obtain your API credentials from the SteadFast Courier Portal.

🚀 Quick Start

Basic Usage

from steadfast_courier import SteadfastCourier

# Initialize the client
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
STEADFAST_API_KEY = 'your-api-key'
STEADFAST_SECRET_KEY = 'your-secret-key'

# views.py
from steadfast_courier import SteadfastCourier
from django.conf import settings

def create_order(request):
    client = SteadfastCourier(
        api_key=settings.STEADFAST_API_KEY,
        secret_key=settings.STEADFAST_SECRET_KEY
    )

    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 steadfast_courier import SteadfastCourier

app = FastAPI()

STEADFAST_CLIENT = SteadfastCourier(
    api_key='your-api-key',
    secret_key='your-secret-key'
)

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 steadfast_courier import SteadfastCourier

app = Flask(__name__)

client = SteadfastCourier(
    api_key='your-api-key',
    secret_key='your-secret-key'
)

@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.0.tar.gz (15.8 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.0-py3-none-any.whl (17.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: steadfast_courier-1.1.0.tar.gz
  • Upload date:
  • Size: 15.8 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.0.tar.gz
Algorithm Hash digest
SHA256 2ffb250f072acf4d90fa145a538ce3fe6d129c0509ddf2fb08794a7a19694631
MD5 06812f2e1662bef8bf4ae55b246f3497
BLAKE2b-256 84b45b1931b36dbdae9a322283f6e2d4879a3e8c202e9bc607b9d43619f85e09

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for steadfast_courier-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 18c9eadfca080274a272a6cece9af60fc4f8363a1adba3157ad0c2564082e4d2
MD5 9bb7cce33675ff9999a303755b513f2c
BLAKE2b-256 39435bcf10c3f78eae73cce6f281297dd39d1ff1e127020ace5d58847604291f

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