SteadFast Courier Python Package
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
.envfiles viafrom_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
# 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
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
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
- Never hardcode API keys - Use environment variables
- Use .env files - Keep credentials out of version control
- Validate inputs - The package validates automatically, but check user inputs
- Use HTTPS - Always use secure connections
- 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
- Documentation: See USAGE.md
- Issue Tracking: GitHub Issues
- Developer: Rezwan Ahamed
- Official API Docs: SteadFast API Documentation
📄 License
This package is open-sourced software licensed under the MIT License. See the LICENSE file for details.
🙏 Credits
- Original PHP Package by Nayem Uddin (https://github.com/nayemuf)
- Python Port with Multi-Framework Support by Rezwan Ahamed (https://github.com/rezwanahamed)
- SteadFast Courier API by SteadFast Courier Ltd.
🤝 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
Metadata
Release files for steadfast-courier 1.1.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| steadfast_courier-1.1.3.tar.gz | 16.2 kB | Without provenance | Details for steadfast_courier-1.1.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| steadfast_courier-1.1.3-py3-none-any.whl | Python 3 | none | any | Details for steadfast_courier-1.1.3-py3-none-any.whl |
Total release size: 33.5 kB
Release files / steadfast_courier-1.1.3.tar.gz
| Download URL | steadfast_courier-1.1.3.tar.gz |
|---|---|
| Size | 16.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5c393686360ca0b5599df4e9b78a7e9c0783133017937ada99e7e9938d938eb7
|
|
BLAKE2b-256 checksum How to use checksums |
2dc700c0996fb1ff86f9658929d16115e4d2424a7c59ecfbfc46ca6c0fc263c5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.3
|
Release files / steadfast_courier-1.1.3-py3-none-any.whl
| Download URL | steadfast_courier-1.1.3-py3-none-any.whl |
|---|---|
| Size | 17.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e48e5005255f747dcc81a253232e6fd4414ded5d6e62871e504659201591c8ce
|
|
BLAKE2b-256 checksum How to use checksums |
afc5196f4d0ff239d1d450e39c5ca73d6eca35165744ddde82240eb9c7c8df90
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.3
|
Security for steadfast-courier 1.1.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.