chore: add comprehensive API wrapper documentation
- Add docs/ directory with 6 comprehensive documentation files: * INDEX.md - Main navigation and documentation index * GETTING_STARTED.md - Setup and configuration guide * API_REFERENCE.md - Complete API documentation * WRAPPERS.md - High-level wrappers guide * CUSTOM_REQUESTS.md - Advanced usage patterns * TROUBLESHOOTING.md - Problem-solving guide - Update README.md with enhanced project information - Update development.md with expanded documentation context Extends previous session's documentation work with complete developer and user-facing documentation. Closes previous documentation issue.
This commit is contained in:
parent
14346ed02e
commit
fd1a1566e9
8 changed files with 4909 additions and 61 deletions
469
docs/GETTING_STARTED.md
Normal file
469
docs/GETTING_STARTED.md
Normal file
|
|
@ -0,0 +1,469 @@
|
|||
# TrustCafé API Wrapper - Getting Started Guide
|
||||
|
||||
This guide will help you quickly set up the TrustCafé API wrapper and start making API calls.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Installation](#installation)
|
||||
2. [API Credentials Setup](#api-credentials-setup)
|
||||
3. [Environment Configuration](#environment-configuration)
|
||||
4. [First API Call](#first-api-call)
|
||||
5. [Token Management](#token-management)
|
||||
6. [Best Practices](#best-practices)
|
||||
7. [Next Steps](#next-steps)
|
||||
|
||||
## Installation
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Ensure you have:
|
||||
- Python 3.11 or higher installed
|
||||
- pip or uv package manager
|
||||
|
||||
### Installing via pip
|
||||
|
||||
```bash
|
||||
pip install trustcafeapiwrapper
|
||||
```
|
||||
|
||||
### Installing via uv (Recommended)
|
||||
|
||||
```bash
|
||||
uv add trustcafeapiwrapper
|
||||
```
|
||||
|
||||
### Installation Verification
|
||||
|
||||
```python
|
||||
import trustcafeapiwrapper
|
||||
print(trustcafeapiwrapper.__version__) # Should print the version
|
||||
```
|
||||
|
||||
## API Credentials Setup
|
||||
|
||||
### Step 1: Generate Client Credentials
|
||||
|
||||
1. Visit the TrustCafé API Access page:
|
||||
- **Production**: [https://trustcafe.io/en/myaccount/apiaccess](https://trustcafe.io/en/myaccount/apiaccess)
|
||||
- **Alpha/Development**: [https://alpha.wts2.net/en/myaccount/apiaccess](https://alpha.wts2.net/en/myaccount/apiaccess)
|
||||
|
||||
2. Click "Create new client credentials key pair"
|
||||
|
||||
3. Select your desired scopes:
|
||||
- **Full Access**: Select all scopes for maximum flexibility
|
||||
- **Limited Access**: Choose specific scopes if you only need certain features
|
||||
|
||||
4. Click "Save"
|
||||
|
||||
5. Record your credentials:
|
||||
- **Client ID**: Your unique application identifier
|
||||
- **Client Secret**: Your application secret (save this securely!)
|
||||
|
||||
### Step 2: Store Credentials Securely
|
||||
|
||||
**Option A: Environment Variables (Recommended)**
|
||||
|
||||
Use environment variables for production code:
|
||||
|
||||
```bash
|
||||
# .env file (add to .gitignore)
|
||||
export TRUSTCAFE_CLIENT_ID="your-client-id-here"
|
||||
export TRUSTCAFE_CLIENT_SECRET="your-client-secret-here"
|
||||
export TRUSTCAFE_ENV="production"
|
||||
```
|
||||
|
||||
Load the environment variables in your Python code:
|
||||
|
||||
```python
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
client_id = os.getenv("TRUSTCAFE_CLIENT_ID")
|
||||
client_secret = os.getenv("TRUSTCAFE_CLIENT_SECRET")
|
||||
env = os.getenv("TRUSTCAFE_ENV", "alpha")
|
||||
```
|
||||
|
||||
**Option B: Configuration Files**
|
||||
|
||||
For development, you can use configuration files:
|
||||
|
||||
```python
|
||||
# config.py
|
||||
CLIENT_ID = "your-client-id"
|
||||
CLIENT_SECRET = "your-client-secret"
|
||||
ENVIRONMENT = "alpha"
|
||||
```
|
||||
|
||||
**Option C: Secrets Management (Production)**
|
||||
|
||||
For production deployments, use a secrets management system:
|
||||
|
||||
- AWS Secrets Manager
|
||||
- HashiCorp Vault
|
||||
- Kubernetes Secrets
|
||||
- Environment-specific config files in CI/CD
|
||||
|
||||
**Important: Never commit credentials to version control!**
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
The TrustCafé API wrapper supports two environments:
|
||||
|
||||
### Alpha Environment (Development)
|
||||
|
||||
- **Purpose**: Testing, development, staging
|
||||
- **URL**: `alpha.wts2.net`
|
||||
- **Best for**: Development and testing before production
|
||||
|
||||
```python
|
||||
API = APIClient(
|
||||
client_id=os.getenv("TRUSTCAFE_CLIENT_ID"),
|
||||
client_secret=os.getenv("TRUSTCAFE_CLIENT_SECRET"),
|
||||
env="alpha" # Alpha environment
|
||||
)
|
||||
```
|
||||
|
||||
### Production Environment
|
||||
|
||||
- **Purpose**: Actual production usage
|
||||
- **URL**: `trustcafe.io`
|
||||
- **Best for**: Production deployments
|
||||
|
||||
```python
|
||||
API = APIClient(
|
||||
client_id=os.getenv("TRUSTCAFE_CLIENT_ID"),
|
||||
client_secret=os.getenv("TRUSTCAFE_CLIENT_SECRET"),
|
||||
env="production" # Production environment
|
||||
)
|
||||
```
|
||||
|
||||
### Switching Environments
|
||||
|
||||
```python
|
||||
# Initialize with alpha
|
||||
API = APIClient(client_id="id", client_secret="secret", env="alpha")
|
||||
|
||||
# Later, switch to production
|
||||
API.set_environment("production")
|
||||
```
|
||||
|
||||
## First API Call
|
||||
|
||||
### Example: Get Your Profile
|
||||
|
||||
```python
|
||||
import trustcafeapiwrapper
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
# Initialize the API client
|
||||
API = trustcafeapiwrapper.APIClient(
|
||||
client_id=os.getenv("TRUSTCAFE_CLIENT_ID"),
|
||||
client_secret=os.getenv("TRUSTCAFE_CLIENT_SECRET"),
|
||||
env="alpha", # or "production"
|
||||
debug=True # Set to True to see request/response details
|
||||
)
|
||||
|
||||
# Authenticate and get an access token
|
||||
API.handle_token()
|
||||
|
||||
# Get your profile using a job
|
||||
profile = API.run_job('userprofile.get', "your-username")
|
||||
|
||||
print("Profile Data:")
|
||||
print(profile)
|
||||
```
|
||||
|
||||
### Example: Create Your First Post
|
||||
|
||||
```python
|
||||
from trustcafeapiwrapper.wrappers.post.create_post import create_post
|
||||
|
||||
# Create a new post
|
||||
API.wrapped(create_post(
|
||||
"Hey there! This is my first post via the API.",
|
||||
parent_path="/", # Root path
|
||||
blur_label=None, # Optional: blur content
|
||||
card_url=None, # Optional: link preview card
|
||||
collaborative=False # Optional: enable collaboration
|
||||
))
|
||||
|
||||
print("Post created successfully!")
|
||||
```
|
||||
|
||||
## Token Management
|
||||
|
||||
### Automatic Token Management
|
||||
|
||||
The wrapper automatically manages access tokens:
|
||||
|
||||
```python
|
||||
# First request - gets and saves token
|
||||
API.handle_token()
|
||||
|
||||
# Subsequent requests - uses cached token if still valid
|
||||
API.handle_token() # Returns cached token
|
||||
```
|
||||
|
||||
**How it works:**
|
||||
1. Checks for `token_data_{env}.json` file
|
||||
2. Verifies token expiration (tokens last ~3 months)
|
||||
3. Obtains new token if expired
|
||||
4. Saves token to file for caching
|
||||
|
||||
### Manual Token Control
|
||||
|
||||
For more control:
|
||||
|
||||
```python
|
||||
# Check if token is valid before making requests
|
||||
if not API.is_token_valid():
|
||||
API.sign_in() # Get new token
|
||||
|
||||
# Or manually set token
|
||||
API.set_token({
|
||||
"access_token": "your_access_token",
|
||||
"access_token_timeout": 9999999999 # Unix timestamp
|
||||
})
|
||||
|
||||
# Verify token validity
|
||||
if API.is_token_valid():
|
||||
print("Token is valid - safe to make requests")
|
||||
else:
|
||||
print("Token expired - get a new one")
|
||||
```
|
||||
|
||||
### Environment-Specific Tokens
|
||||
|
||||
Different environments use separate token files:
|
||||
|
||||
- `token_data_alpha.json` - Alpha environment tokens
|
||||
- `token_data_production.json` - Production environment tokens
|
||||
|
||||
This prevents token mixing between environments.
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Environment Variables
|
||||
|
||||
Always use environment variables for credentials:
|
||||
|
||||
```bash
|
||||
# .env file
|
||||
TRUSTCAFE_CLIENT_ID=
|
||||
TRUSTCAFE_CLIENT_SECRET=
|
||||
TRUSTCAFE_ENV=alpha
|
||||
```
|
||||
|
||||
### 2. Error Handling
|
||||
|
||||
Always wrap API calls in try-except blocks:
|
||||
|
||||
```python
|
||||
try:
|
||||
API.handle_token()
|
||||
profile = API.run_job('userprofile.get', "username")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
# Handle error appropriately
|
||||
```
|
||||
|
||||
### 3. Token Refresh Strategy
|
||||
|
||||
For long-running applications:
|
||||
|
||||
```python
|
||||
# Before making API calls
|
||||
if not API.is_token_valid():
|
||||
API.handle_token()
|
||||
# Optionally pre-fetch critical data
|
||||
user_profile = API.run_job('userprofile.get', "username")
|
||||
```
|
||||
|
||||
### 4. Logging
|
||||
|
||||
Implement appropriate logging:
|
||||
|
||||
```python
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
API.handle_token()
|
||||
profile = API.run_job('userprofile.get', "username")
|
||||
logger.info(f"Successfully retrieved profile: {profile.get('username')}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get profile: {e}")
|
||||
raise
|
||||
```
|
||||
|
||||
### 5. Testing Credentials
|
||||
|
||||
Always test in alpha before production:
|
||||
|
||||
```python
|
||||
# Test with alpha first
|
||||
API = APIClient(client_id="test-id", client_secret="test-secret", env="alpha")
|
||||
|
||||
# Verify token works
|
||||
results = API.handle_token()
|
||||
print("Alpha environment works!")
|
||||
|
||||
# Then configure production
|
||||
API = APIClient(
|
||||
client_id=os.getenv("PROD_CLIENT_ID"),
|
||||
client_secret=os.getenv("PROD_CLIENT_SECRET"),
|
||||
env="production"
|
||||
)
|
||||
```
|
||||
|
||||
### 6. Rate Limiting Considerations
|
||||
|
||||
The TrustCafé API may have rate limits. Implement if needed:
|
||||
|
||||
```python
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
def rate_limit(max_calls=10, period=60):
|
||||
def decorator(func):
|
||||
calls = [0]
|
||||
times = [time.time()]
|
||||
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
now = time.time()
|
||||
calls[0] += 1
|
||||
|
||||
# Reset if period has passed
|
||||
if times[0] + period < now:
|
||||
times[0] = now
|
||||
calls[0] = 1
|
||||
|
||||
# Sleep if necessary
|
||||
if calls[0] > max_calls:
|
||||
waited = time.time() - times[0] + 1
|
||||
time.sleep(waited)
|
||||
|
||||
times[0] = time.time()
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
# Apply rate limiting
|
||||
@rate_limit(max_calls=30, period=60)
|
||||
def api_call():
|
||||
return API.make_request(...)
|
||||
```
|
||||
|
||||
### 7. Debug Mode in Development
|
||||
|
||||
Use debug mode during development:
|
||||
|
||||
```python
|
||||
API = APIClient(
|
||||
client_id="your-id",
|
||||
client_secret="your-secret",
|
||||
env="internal",
|
||||
debug=True # Prints request/response details
|
||||
)
|
||||
```
|
||||
|
||||
## Common Configuration Patterns
|
||||
|
||||
### Production Deployment
|
||||
|
||||
```python
|
||||
# config.py
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
class Config:
|
||||
# Production credentials from environment
|
||||
CLIENT_ID = os.getenv("TRUSTCAFE_PROD_CLIENT_ID")
|
||||
CLIENT_SECRET = os.getenv("TRUSTCAFE_PROD_CLIENT_SECRET")
|
||||
ENVIRONMENT = os.getenv("TRUSTCAFE_ENV", "production")
|
||||
|
||||
# Other config
|
||||
DEBUG = os.getenv("DEBUG", "False") == "True"
|
||||
```
|
||||
|
||||
```python
|
||||
# app.py
|
||||
from config import Config
|
||||
import trustcafeapiwrapper
|
||||
|
||||
API = trustcafeapiwrapper.APIClient(
|
||||
client_id=Config.CLIENT_ID,
|
||||
client_secret=Config.CLIENT_SECRET,
|
||||
env=Config.ENVIRONMENT,
|
||||
debug=Config.DEBUG
|
||||
)
|
||||
|
||||
API.handle_token()
|
||||
```
|
||||
|
||||
### Development/Local
|
||||
|
||||
```python
|
||||
# config_dev.py
|
||||
CLASS Config:
|
||||
CLIENT_ID = "dev-client-id"
|
||||
CLIENT_SECRET = "dev-client-secret"
|
||||
ENVIRONMENT = "alpha"
|
||||
DEBUG = True
|
||||
```
|
||||
|
||||
```
|
||||
# .env file
|
||||
DEBUG=True
|
||||
LOG_LEVEL=INFO
|
||||
```
|
||||
|
||||
## Troubleshooting Setup Issues
|
||||
|
||||
### Issue: "Client ID not found"
|
||||
|
||||
**Solution**: Ensure you've generated client credentials from the TrustCafé admin page.
|
||||
|
||||
### Issue: "Client secret cannot be retrieved"
|
||||
|
||||
**Solution**: Client secrets can only be retrieved when first created. Create a new pair if needed.
|
||||
|
||||
### Issue: "Invalid client credentials"
|
||||
|
||||
**Solution**: Double-check client_id and client_secret. Verify you're using the correct environment.
|
||||
|
||||
### Issue: "Token expired"
|
||||
|
||||
**Solution**: Call `API.handle_token()` to get a new token. Check your token file is writable.
|
||||
|
||||
### Issue: "Permission denied" when writing token file
|
||||
|
||||
**Solution**: Ensure the working directory is writable. Use absolute paths or configure a writable location.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Now that you're set up:
|
||||
|
||||
1. **Read the API Reference**: Learn about all available jobs and wrappers
|
||||
- [API Reference](api_reference.md)
|
||||
|
||||
2. **Explore Wrappers**: Try the high-level wrappers for common tasks
|
||||
- [Wrappers Guide](wrappers.md)
|
||||
|
||||
3. **Make Custom Requests**: Learn to make advanced API calls manually
|
||||
- [Custom Requests Guide](custom_requests.md)
|
||||
|
||||
4. **Handle Errors**: Learn about common errors and how to handle them
|
||||
- [Troubleshooting Guide](troubleshooting.md)
|
||||
|
||||
5. **Contribute**: Help complete the wrapper with additional jobs
|
||||
- [Development Guide](development.md)
|
||||
Loading…
Add table
Add a link
Reference in a new issue