A Python client library for analyzing URL trust scores using AI-powered analysis
Project description
E-Commerce Trust Score
A Python client library for analyzing URL trust scores using AI-powered analysis.
Features
- 🔍 URL Analysis: Analyze URLs for trust and safety signals
- 🤖 AI-Powered: Intelligent analysis using advanced AI models
- 📊 Detailed Scoring: Comprehensive trust factors and explanations
- 🚀 Easy Integration: Simple Python API
- ⚡ Async Support: Built with async/await for high performance
Installation
pip install e-commerce-trust-score
Quick Start
import asyncio
from commerce_trust_score import TrustScoreAPIClient
async def main():
# Initialize the client with your API credentials
client = TrustScoreAPIClient(
api_url="https://your-trust-score-api.com",
api_key="your-api-key"
)
# Analyze a URL
result = await client.analyze_url("https://example.com")
# Check the results
print(f"Trust Score: {result.score}")
print(f"Risk Level: {result.label}")
print(f"\nExplanations:")
for explanation in result.explanations:
print(f" - {explanation}")
asyncio.run(main())
Configuration
Getting Your API Key
Contact your service provider to obtain:
- API URL: The endpoint URL for the trust score service
- API Key: Your authentication key
Basic Setup
from commerce_trust_score import TrustScoreAPIClient
client = TrustScoreAPIClient(
api_url="https://your-trust-score-api.com",
api_key="your-api-key",
timeout=30.0 # Optional: request timeout in seconds
)
Using Environment Variables
import os
from commerce_trust_score import TrustScoreAPIClient
client = TrustScoreAPIClient(
api_url=os.getenv("TRUST_SCORE_API_URL"),
api_key=os.getenv("TRUST_SCORE_API_KEY")
)
Usage Examples
Analyze a Single URL
import asyncio
from commerce_trust_score import TrustScoreAPIClient
async def analyze_url():
client = TrustScoreAPIClient(
api_url="https://your-api.com",
api_key="your-key"
)
result = await client.analyze_url("https://suspicious-site.com")
# Check if URL is safe
if result.score >= 0.8:
print("✅ URL appears safe")
elif result.score >= 0.4:
print("⚠️ Medium risk - proceed with caution")
else:
print("❌ High risk - not recommended")
return result
asyncio.run(analyze_url())
Analyze Multiple URLs
import asyncio
from commerce_trust_score import TrustScoreAPIClient
async def analyze_batch():
client = TrustScoreAPIClient(
api_url="https://your-api.com",
api_key="your-key"
)
urls = [
"https://example1.com",
"https://example2.com",
"https://example3.com"
]
results = await client.analyze_urls(urls)
for url, result in zip(urls, results):
print(f"{url}: {result.label} (score: {result.score:.2f})")
asyncio.run(analyze_batch())
Error Handling
import asyncio
from commerce_trust_score import TrustScoreAPIClient
import httpx
async def safe_analyze():
client = TrustScoreAPIClient(
api_url="https://your-api.com",
api_key="your-key"
)
try:
result = await client.analyze_url("https://example.com")
print(f"Score: {result.score}")
except httpx.HTTPStatusError as e:
print(f"API error: {e.response.status_code}")
except httpx.RequestError as e:
print(f"Connection error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
asyncio.run(safe_analyze())
Trust Score Interpretation
The API returns a score between 0 and 1, along with a risk label:
| Label | Score Range | Recommendation |
|---|---|---|
likely_safe |
≥ 0.8 | URL appears trustworthy |
medium_risk |
0.4 - 0.8 | Exercise caution |
high_risk |
< 0.4 | Not recommended |
Trust Factors
Each analysis includes detailed factors:
- domain_age_days: Age of the domain in days
- scam_reports: Number of reported scams
- whois_risk: Domain registration risk score (0-1)
- review_sentiment: Review sentiment score (0-1)
- social_reputation: Social media reputation (0-1)
- price_outlier_score: Price anomaly detection (0-1)
- payment_risk: Payment method risk (0-1)
- image_reuse_score: Stolen image detection (0-1)
- brand_typosquatting_score: Brand impersonation detection (0-1)
Integration Examples
Flask Application
from flask import Flask, request, jsonify
from commerce_trust_score import TrustScoreAPIClient
import asyncio
import os
app = Flask(__name__)
client = TrustScoreAPIClient(
api_url=os.getenv("TRUST_SCORE_API_URL"),
api_key=os.getenv("TRUST_SCORE_API_KEY")
)
@app.route('/check-url', methods=['POST'])
def check_url():
url = request.json.get('url')
if not url:
return jsonify({'error': 'URL required'}), 400
result = asyncio.run(client.analyze_url(url))
return jsonify({
'url': url,
'score': result.score,
'label': result.label,
'safe': result.score >= 0.8,
'factors': {
'domain_age': result.factors.domain_age_days,
'scam_reports': result.factors.scam_reports,
'whois_risk': result.factors.whois_risk
}
})
if __name__ == '__main__':
app.run(debug=True)
Django View
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from commerce_trust_score import TrustScoreAPIClient
import os
client = TrustScoreAPIClient(
api_url=os.getenv("TRUST_SCORE_API_URL"),
api_key=os.getenv("TRUST_SCORE_API_KEY")
)
@require_http_methods(["POST"])
async def analyze_url(request):
url = request.POST.get('url')
if not url:
return JsonResponse({'error': 'URL required'}, status=400)
result = await client.analyze_url(url)
return JsonResponse({
'score': result.score,
'label': result.label,
'explanations': result.explanations
})
FastAPI Application
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from commerce_trust_score import TrustScoreAPIClient
import os
app = FastAPI()
client = TrustScoreAPIClient(
api_url=os.getenv("TRUST_SCORE_API_URL"),
api_key=os.getenv("TRUST_SCORE_API_KEY")
)
class URLRequest(BaseModel):
url: str
@app.post("/analyze")
async def analyze_url(request: URLRequest):
try:
result = await client.analyze_url(request.url)
return {
'url': request.url,
'score': result.score,
'label': result.label,
'factors': result.factors.dict(),
'explanations': result.explanations
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Celery Task
from celery import shared_task
from commerce_trust_score import TrustScoreAPIClient
import asyncio
import os
client = TrustScoreAPIClient(
api_url=os.getenv("TRUST_SCORE_API_URL"),
api_key=os.getenv("TRUST_SCORE_API_KEY")
)
@shared_task
def analyze_url_task(url):
result = asyncio.run(client.analyze_url(url))
return {
'url': url,
'score': result.score,
'label': result.label,
'timestamp': datetime.now().isoformat()
}
API Reference
TrustScoreAPIClient
__init__(api_url: str, api_key: Optional[str] = None, timeout: float = 30.0)
Initialize the client.
Parameters:
api_url(str): Base URL of the trust score API serviceapi_key(str, optional): Your API authentication keytimeout(float): Request timeout in seconds (default: 30.0)
async analyze_url(url: str) -> TrustResponse
Analyze a single URL.
Parameters:
url(str): The URL to analyze
Returns:
TrustResponse: Analysis result with score, label, factors, and explanations
Raises:
httpx.HTTPError: If the API request fails
async analyze_urls(urls: list[str]) -> list[TrustResponse]
Analyze multiple URLs in batch.
Parameters:
urls(list[str]): List of URLs to analyze
Returns:
list[TrustResponse]: List of analysis results
async health_check() -> dict
Check if the API service is available.
Returns:
dict: Service health status
Response Models
TrustResponse
score(float): Trust score between 0 and 1label(str): Risk label (likely_safe,medium_risk,high_risk)factors(TrustFactors): Detailed scoring factorsexplanations(List[str]): Human-readable explanations
TrustFactors
domain_age_days(int): Domain age in daysscam_reports(int): Number of scam reportswhois_risk(float): WHOIS risk score (0-1)review_sentiment(float): Review sentiment (0-1)social_reputation(float): Social reputation (0-1)price_outlier_score(float): Price anomaly score (0-1)payment_risk(float): Payment risk score (0-1)image_reuse_score(float): Image theft detection (0-1)brand_typosquatting_score(float): Brand impersonation (0-1)
Best Practices
1. Secure API Key Storage
# ✅ Good: Use environment variables
import os
api_key = os.getenv("TRUST_SCORE_API_KEY")
# ❌ Bad: Hardcode in source
api_key = "your-api-key-12345" # Don't do this!
2. Implement Caching
from functools import lru_cache
import asyncio
@lru_cache(maxsize=1000)
def get_cached_score(url: str):
return asyncio.run(client.analyze_url(url))
3. Handle Timeouts
client = TrustScoreAPIClient(
api_url="https://your-api.com",
api_key="your-key",
timeout=10.0 # Adjust based on your needs
)
4. Batch Processing
# Process URLs in batches for better performance
batch_size = 10
for i in range(0, len(urls), batch_size):
batch = urls[i:i + batch_size]
results = await client.analyze_urls(batch)
process_results(results)
Performance Tips
- Batch Requests: Use
analyze_urls()for multiple URLs - Async/Await: Leverage async for better performance
- Caching: Cache results for frequently checked URLs
- Connection Pooling: Reuse the same client instance
- Timeout Management: Set appropriate timeouts for your use case
Troubleshooting
Connection Errors
# Check API connectivity
try:
health = await client.health_check()
print(f"API Status: {health}")
except Exception as e:
print(f"API unavailable: {e}")
Authentication Issues
- Verify your API key is correct
- Check that the API key has not expired
- Ensure the API URL is correct (including https://)
Timeout Issues
- Increase the timeout value if analyzing complex URLs
- Check your network connection
- Verify the API service is responding
Requirements
- Python 3.10+
- httpx (automatically installed)
- Valid API key from your service provider
Support
For API access, billing, or technical support:
- Contact your service provider
- Check service status page
- Review API documentation
License
MIT License - see LICENSE file for details.
Changelog
See CHANGELOG.md for version history.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file e_commerce_trust_score-0.1.0.tar.gz.
File metadata
- Download URL: e_commerce_trust_score-0.1.0.tar.gz
- Upload date:
- Size: 18.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
956dc86566f6328885090814fa5c517b10b4d270b184ff713d976569055089fb
|
|
| MD5 |
2386892605a147630a38002b346b4a4b
|
|
| BLAKE2b-256 |
ebd85c4813dcafe093e775982e4ca547e309dfa1c438799f6818a869afc0dcd7
|
File details
Details for the file e_commerce_trust_score-0.1.0-py3-none-any.whl.
File metadata
- Download URL: e_commerce_trust_score-0.1.0-py3-none-any.whl
- Upload date:
- Size: 15.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e9e9b63536f647b3503c7b48e8330d88eac94a1298beab9b1f0bbc46cd80b099
|
|
| MD5 |
65b71dda12a3d9fd3a0ba8f9e71517ad
|
|
| BLAKE2b-256 |
9ed599611cbd3749f6491afe3b060884275b50b77f489195a0e9b25d6ea9494a
|