trustcafe-api-wrapper/docs/API_REFERENCE.md
Jezza Hehn 17d6ed69d1 docs: fix more parameter mismatches and job name inaccuracies
- Fix feed.following -> feed.followingfeed (actual function name)
- Fix branch.listbyname: doesn't filter by name, just lists branches with pagination
- Fix branch.get: parameter is branch_slug not branchName
- Fix follow.follow: takes payload dict, not username string
- Add pagination parameter docs for feed.cafefeed and feed.followingfeed
- Revert GitLab URL changes (correct - points to upstream repo)
2026-04-18 02:57:41 +00:00

882 lines
16 KiB
Markdown

# TrustCafé API Reference
Complete reference guide for all available jobs in the TrustCafé API wrapper.
## Table of Contents
- [Preparation](#preparation)
- [Authentication Jobs](#authentication-jobs)
- [Post Jobs](#post-jobs)
- [Comment Jobs](#comment-jobs)
- [UserProfile Jobs](#userprofile-jobs)
- [Follow Jobs](#follow-jobs)
- [Vote Jobs](#vote-jobs)
- [Reaction Jobs](#reaction-jobs)
- [Notification Jobs](#notification-jobs)
- [Trust Jobs](#trust-jobs)
- [Branch Jobs](#branch-jobs)
- [Feed Jobs](#feed-jobs)
- [Block Jobs](#block-jobs)
- [Mute Jobs](#mute-jobs)
- [Error Handling](#error-handling)
## Preparation
Before using jobs, initialize the API client:
```python
import trustcafeapiwrapper
import os
API = trustcafeapiwrapper.APIClient(
client_id=os.getenv("TRUSTCAFE_CLIENT_ID"),
client_secret=os.getenv("TRUSTCAFE_CLIENT_SECRET"),
env="alpha", # or "production"
debug=False
)
# Authenticate
API.handle_token()
```
## Authentication Jobs
### sign_in()
Obtains a new access token using OAuth2 client-credentials flow.
```python
token_data = API.sign_in()
```
**Returns:**
```python
{
"access_token": "string (3-month duration)",
"access_token_timeout": "integer (Unix timestamp)"
}
```
**Parameters:** None
**Error Cases:**
- Invalid client credentials
- Incorrect environment
- Network errors
---
## Post Jobs
Fetch, create, update, and manage posts.
### post.get()
Fetches a specific post by ID or slug.
```python
post_data = API.run_job('post.get', "post-slug-or-id")
```
**Parameters:**
- `post_slug` (str): The post identifier (slug or ID)
**Returns:** dict - Post data
**Example:**
```python
post = API.run_job('post.get', "my-first-post")
print(post.get('postText'))
```
---
### post.create()
Creates a new post.
```python
post = API.run_job('post.create', payload)
```
**Parameters:**
- `postText` (str): The text content of the post
- `parent` (dict, required): Parent object containing pk and sk
- `pk` (str): Partition key
- `sk` (str): Sort key
- `blurLabel` (str, optional): Label for blurring content
- `cardUrl` (str, optional): URL for link preview card
- `collaborative` (bool, optional): Enable collaborative editing (default: False)
**Returns:** dict - Created post data
**Example:**
```python
post = API.run_job('post.create', {
"postText": "This is a new post",
"parent": {
"pk": "maintrunk#maintrunk",
"sk": "maintrunk#maintrunk"
}
})
```
---
### post.update()
Updates an existing post.
```python
updated_post = API.run_job('post.update', payload)
```
**Parameters:**
- `pk` (str): Post partition key
- `sk` (str): Post sort key
- `newPostText` (str, optional): New post content
- Other optional fields to update
**Returns:** dict - Updated post data
**Example:**
```python
post = API.run_job('post.update', {
"pk": "post-id-123",
"sk": "post-id-123",
"newPostText": "Updated post content"
})
```
*Note: Full field list requires review of API documentation.*
---
### post.listall()
Lists all posts.
```python
posts = API.run_job('post.listall')
```
**Parameters:** None
**Returns:** dict - List of all posts
**Example:**
```python
all_posts = API.run_job('post.listall')
print(f"Total posts: {len(all_posts.get('Items', []))}")
```
---
### post.listpublic()
Lists public posts only.
```python
public_posts = API.run_job('post.listpublic')
```
**Parameters:** None
**Returns:** dict - List of public posts
**Example:**
```python
public_posts = API.run_job('post.listpublic')
for post in public_posts.get('Items', []):
print(post.get('pk'))
```
---
### post.listbybranch()
Lists posts in a specific branch.
```python
branch_posts = API.run_job('post.listbybranch', branch_name)
```
**Parameters:**
- `branchName` (str): The branch identifier
**Returns:** dict - List of posts in the branch
**Example:**
```python
music_posts = API.run_job('post.listbybranch', "music")
```
---
### post.listbyuserprofile()
Lists posts by a specific user profile.
```python
user_posts = API.run_job('post.listbyuserprofile', username)
```
**Parameters:**
- `username` (str): The username of the user
**Returns:** dict - List of posts by user
**Example:**
```python
journals = API.run_job('post.listbyuserprofile', "philosopher-jon")
```
---
### post.listremoved()
Lists removed/deleted posts.
```python
removed = API.run_job('post.listremoved', post_id)
```
**Parameters:**
- `postId` (str): The post identifier
**Returns:** dict - Removed post data
**Example:**
```python
removed_post = API.run_job('post.listremoved', "deleted-post-id")
```
---
## Comment Jobs
Manage comments on posts.
### comment.create()
Creates a new comment.
```python
comment = API.run_job('comment.create', payload)
```
**Parameters:**
- `commentText` (str): Comment content
- `parent` (dict, required): Parent object
- `pk` (str): Partition key
- `sk` (str): Sort key
- Other optional fields as API requires
**Returns:** dict - Created comment data
**Example:**
```python
comment = API.run_job('comment.create', {
"commentText": "Great post!",
"parent": {
"pk": "post-id",
"sk": "post-id"
}
})
```
---
### comment.listtbypostid()
Lists comments for a specific post.
```python
comments = API.run_job('comment.listtbypostid', post_id)
```
**Parameters:**
- `postId` (str): The post ID
**Returns:** dict - List of comments
**Example:**
```python
comments = API.run_job('comment.listtbypostid', "current-post-id")
for comment in comments.get('Items', []):
print(comment.get('commentText'))
```
---
## UserProfile Jobs
Retrieve user profile information.
### userprofile.get()
Retrieves a user profile.
```python
profile = API.run_job('userprofile.get', username)
```
**Parameters:**
- `username` (str): The username to retrieve
**Returns:** dict - User profile data
**Example:**
```python
profile = API.run_job('userprofile.get', "philosopher-jon")
print(profile.get('username'))
print(profile.get('trustScore'))
```
---
## Follow Jobs
Manage follow relationships.
### follow.follow()
Follow or unfollow a user or subwiki.
```python
result = API.run_job('follow.follow', payload)
```
**Parameters:**
- `payload` (dict): Follow payload containing:
- `isFollowing` (bool): `true` to follow, `false` to unfollow
- `parent` (dict): Object with `pk` and `sk` for the target
- `followType` (str): Entity type (`'userprofile'` or `'subwiki'`)
- `parentSlug` (str): Slug of the user or subwiki
- `preferences` (dict, optional): Notification preferences
**Returns:** dict - Follow relationship data
**Example:**
```python
# Follow a user
followed = API.run_job('follow.follow', {
"isFollowing": true,
"parent": {
"pk": "userprofile#philosopher-jon",
"sk": "userprofile#philosopher-jon"
},
"followType": "userprofile",
"parentSlug": "philosopher-jon",
"preferences": {
"notification": true,
"emailNew": false,
"emailDigest": true
}
})
```
---
## Vote Jobs
Cast votes on posts/content.
### vote.votecast()
Casts a vote on a post or comment.
```python
vote = API.run_job('vote.votecast', payload)
```
**Parameters:**
- `parent` (dict): Object containing vote target info
- `pk` (str): Object partition key
- `sk` (str): Object sort key
- `slug` (str): Object slug
- `entity` (str): Entity type (e.g., "post", "comment")
- `vote` (str): Vote type - "up" or "down"
**Returns:** dict - Vote status
**Example:**
```python
voted = API.run_job('vote.votecast', {
"parent": {
"pk": "post#abc123",
"sk": "post#abc123",
"slug": "my-post-slug",
"entity": "post"
},
"vote": "up"
})
```
---
## Reaction Jobs
Manage reactions to posts, comments, and other content.
### reaction.reacttosomething()
React to something (post, comment, etc.).
```python
reaction = API.run_job('reaction.reacttosomething', payload)
```
**Parameters:**
- `parent` (dict): Object containing `pk` and `sk` keys
- `pk` (str): Object partition key
- `sk` (str): Object sort key
- `reaction` (str): Reaction type (e.g., "like", "heart", "fire")
**Returns:** dict - Reaction status
**Example:**
```python
reacted = API.run_job('reaction.reacttosomething', {
"parent": {
"pk": "post-id",
"sk": "post-id"
},
"reaction": "like"
})
```
---
### reaction.getbyparent()
Get a specific reaction by parent sort key.
```python
reactions = API.run_job('reaction.getbyparent', parent_sk)
```
**Parameters:**
- `parent_sk` (str): Parent sort key (not full ID)
**Returns:** dict - Reaction data
**Example:**
```python
reaction = API.run_job('reaction.getbyparent', "post#my-post-slug")
```
---
### reaction.listbyparent()
List all reactions for a parent object.
```python
reactions = API.run_job('reaction.listbyparent', parent_sk)
```
**Parameters:**
- `parent_sk` (str): Parent sort key (not full ID)
**Returns:** dict - List of reactions
**Example:**
```python
reactions = API.run_job('reaction.listbyparent', "post#my-post-slug")
```
---
## Notification Jobs
Manage user notifications.
### notification.listnotifications()
Lists all notifications.
```python
notifications = API.run_job('notification.listnotifications')
```
**Parameters:** None
**Returns:** dict - List of notifications
**Example:**
```python
notifications = API.run_job('notification.listnotifications')
for notif in notifications.get('Items', []):
print(f"{notif.get('notificationType')}: {notif.get('text')}")
```
---
### notification.markallasread()
Marks all notifications as read.
```python
API.run_job('notification.markallasread')
```
**Parameters:** None
**Returns:** dict - Mark as read status
**Example:**
```python
API.run_job('notification.markallasread')
```
---
## Trust Jobs
Manage trust relationships.
### trust.createorupdate()
Create or update a trust relationship.
```python
trust = API.run_job('trust.createorupdate', payload)
```
**Parameters:**
- `parent` (dict): Object containing `pk` and `sk` for the userprofile
- `parentSlug` (str): Slug of the userprofile
- `trustLevel` (str): Trust level (e.g., "trusted", "neutral", "distrusted")
**Returns:** dict - Trust relationship status
**Example:**
```python
trust = API.run_job('trust.createorupdate', {
"parent": {
"pk": "userprofile#philosopher-jon",
"sk": "userprofile#philosopher-jon"
},
"parentSlug": "philosopher-jon",
"trustLevel": "trusted"
})
```
---
### trust.listbyusersinit()
Lists trust relationships initialized by a user.
```python
trusts = API.run_job('trust.listbyusersinit', user_id)
```
**Parameters:**
- `user_id` (str): The user ID (not username) whose trust relationships to list
- `lastEvaluatedKey` (dict, optional): Pagination key
**Returns:** dict - List of trust relationships
**Example:**
```python
my_trusts = API.run_job('trust.listbyusersinit', "user-id-123")
```
---
### trust.listbyuserhas()
Lists trust relationships where a user was the target.
```python
trusts = API.run_job('trust.listbyuserhas', user_id)
```
**Parameters:**
- `user_id` (str): The user ID (not username) who was targeted
**Returns:** dict - List of trust relationships
---
## Branch Jobs
Manage branches (platform branches or sub-wikis).
### branch.get()
Get a specific branch.
```python
branch = API.run_job('branch.get', branch_slug)
```
**Parameters:**
- `branch_slug` (str): The branch/subwiki slug identifier
**Returns:** dict - Branch data
**Example:**
```python
branch = API.run_job('branch.get', "music")
print(branch.get('slug'))
```
---
### branch.listbyname()
List all branches with pagination.
```python
branches = API.run_job('branch.listbyname', lastEvaluatedKey)
```
**Parameters:**
- `lastEvaluatedKey` (dict, optional): Pagination key for next page
**Returns:** dict - List of branches
**Note:** Despite the name, this does not filter by branch name. It lists all branches.
**Example:**
```python
# Get first page of branches
branches = API.run_job('branch.listbyname')
for branch in branches.get('Items', []):
print(branch.get('slug'))
# Get next page
if 'LastEvaluatedKey' in branches:
next_page = API.run_job('branch.listbyname', branches['LastEvaluatedKey'])
```
---
## Feed Jobs
Get content feeds from TrustCafé.
### feed.cafefeed()
Get the café-wide feed.
```python
feed = API.run_job('feed.cafefeed')
```
**Parameters:**
- `lastEvaluatedKey` (dict, optional): Pagination key
**Returns:** dict - Café feed content
**Example:**
```python
cafefeed = API.run_job('feed.cafefeed')
print(f"Feed items: {len(cafefeed.get('Items', []))}")
```
---
### feed.followingfeed()
Get feed for users you follow.
```python
feed = API.run_job('feed.followingfeed')
```
**Parameters:**
- `lastEvaluatedKey` (dict, optional): Pagination key
**Returns:** dict - Following feed content
**Example:**
```python
following_feed = API.run_job('feed.followingfeed')
print(f"Following feed items: {len(following_feed.get('Items', []))}")
```
---
## Block Jobs
### ⚠️ NOT IMPLEMENTED
Block functionality is not yet implemented in this wrapper. The TrustCafé API may support blocking, but no job or wrapper functions exist yet.
**Status:** TODO - See development.md for details
---
## Mute Jobs
### ⚠️ NOT IMPLEMENTED
Mute functionality is not yet implemented in this wrapper. The TrustCafé API may support muting, but no job or wrapper functions exist yet.
**Status:** TODO - See development.md for details
---
## Error Handling
### Common Error Cases
**Authentication Errors**
```python
try:
profile = API.run_job('userprofile.get', "username")
except Exception as e:
print(f"Authentication required: {e}")
API.handle_token()
profile = API.run_job('userprofile.get', "username")
```
**Invalid Parameters**
```python
try:
post = API.run_job('post.create', {
"postText": "Test",
# Missing required 'parent' field
})
except Exception as e:
print(f"Validation error: {e}")
```
**Network Errors**
```python
try:
result = API.make_request("GET", "content", "some/path")
except Exception as e:
print(f"Network error: {e}")
# Wait and retry
import time
time.sleep(1)
result = API.make_request("GET", "content", "some/path")
```
### Error Response Structure
API errors typically return:
```json
{
"error": "string",
"message": "string",
"details": {} // Optional details
}
```
---
## Response Structure
Most API responses follow a similar structure:
```python
{
"Items": [ // For list operations
{ /* item data */ }
],
"Count": int, // Number of items
"LastEvaluatedKey": { /* pagination key */ }, // For pagination
"ResponseMetadata": { /* AWS SDK metadata */ }
}
```
### Pagination
For large result sets, results may include pagination:
```python
def get_all_posts():
posts = []
paginator = None
while True:
response = API.run_job('post.listpublic', params)
posts.extend(response.get('Items', []))
has_more = 'LastEvaluatedKey' in response
if not has_more:
break
# Set params for next page
params = {
'ExclusiveStartKey': response['LastEvaluatedKey']
}
return posts
```
---
## Best Practices
### 1. Use Type Hints
```python
# Good
from typing import Optional, Dict, Any
def get_post(api: trustcafeapiwrapper.APIClient, post_id: str) -> Dict[str, Any]:
return api.run_job('post.get', post_id)
# Bad
def get_post(api, post_id):
return api.run_job('post.get', post_id)
```
### 2. Validate Responses
```python
post = API.run_job('post.get', "post-id")
if not post or 'Items' not in post:
raise ValueError("Invalid post data received")
item = post['Items'][0]
if not item:
raise ValueError("Post item is empty")
```
### 3. Error Logging
```python
import logging
logger = logging.getLogger(__name__)
try:
profile = API.run_job('userprofile.get', username)
logger.info(f"Successfully retrieved profile for {username}")
except Exception as e:
logger.error(f"Failed to get profile for {username}: {e}")
raise
```
### 4. Timeout Configurations
The API client has a default timeout of 20 seconds:
```python
# The make_request method accepts a timeout parameter
# However, current implementation doesn't expose it directly
# Consider updating the APIClient to accept custom timeouts
```
### 5. Rate Limiting
Implement rate limiting for production use (see main README for example).
---
## Next Steps
- [Wrappers Guide](wrappers.md) - High-level wrappers for common tasks
- [Custom Requests Guide](custom_requests.md) - Making advanced API calls
- [Troubleshooting Guide](troubleshooting.md) - Common issues and solutions