trustcafe-api-wrapper/docs/GETTING_STARTED.md
BarnacleBoy a223bcb27a doc: audit pass — fix env= bug, params, pagination, missing wrappers, broken examples
- env= -> environment= across all docs (Pydantic silently ignores env=)
- Remove __version__ check (doesn't exist in module)
- Fix APIClient(debug=True) missing required client_id/secret
- Fix post.listremoved usage (takes no postId, just lists removed posts)
- Fix JS true/false -> Python True/False in code blocks
- Fix parameter names: branchName->branch_slug, username->user_slug, postId->post_id
- Add missing lastEvaluatedKey param docs for list jobs
- Note post.listpublic as unauthenticated endpoint
- Fix pagination examples (LastEvaluatedKey, not ExclusiveStartKey dict)
- Remove non-existent headers param from make_request example
- Fix branch.listbyname example (takes no name arg)
- Add 4 missing wrapper docs: follow, react, trust, votecast
- Fix broken internal links (case-sensitive filenames)
- Fix <environment>_handle_token template artifact
- Add CODE_BUGS.md documenting 4 code bugs found during audit
2026-04-18 22:58:33 +00:00

472 lines
11 KiB
Markdown

# 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
# Verify the module imported successfully
from trustcafeapiwrapper import APIClient
print("trustcafeapiwrapper installed successfully")
```
## 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"),
environment="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"),
environment="production" # Production environment
)
```
### Switching Environments
```python
# Initialize with alpha
API = APIClient(client_id="id", client_secret="secret", environment="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"),
environment="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", environment="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"),
environment="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",
environment="alpha", # "alpha" or "production"
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)