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:
BarnacleBoy 2026-04-18 01:44:49 +00:00
parent 14346ed02e
commit fd1a1566e9
8 changed files with 4909 additions and 61 deletions

847
docs/API_REFERENCE.md Normal file
View file

@ -0,0 +1,847 @@
# 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()
Follows a user.
```python
result = API.run_job('follow.follow', username)
```
**Parameters:**
- `username` (str): The username to follow
**Returns:** dict - Follow status
**Example:**
```python
followed = API.run_job('follow.follow', "another-user")
print(f"Follow status: {followed}")
```
---
## Vote Jobs
Cast votes on posts/content.
### vote.votecast()
Casts a vote on a post.
```python
vote = API.run_job('vote.votecast', payload)
```
**Parameters:**
- `pk` (str): Object partition key
- `sk` (str): Object sort key
- `voteType` (str): Vote type - "up" or "down"
**Returns:** dict - Vote status
**Example:**
```python
voted = API.run_job('vote.votecast', {
"pk": "post-id",
"sk": "post-id",
"voteType": "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:**
- `objectPK` (str): Object partition key
- `objectSK` (str): Object sort key
- `objectType` (str): Type of object ("post", "comment", etc.)
- `reactionType` (str): Reaction type (depends on API)
**Returns:** dict - Reaction status
**Example:**
```python
reacted = API.run_job('reaction.reacttosomething', {
"objectPK": "post-id",
"objectSK": "post-id",
"objectType": "post",
"reactionType": "like"
})
```
---
### reaction.getbyparent()
Get reactions by parent object.
```python
reactions = API.run_job('reaction.getbyparent', parent_id)
```
**Parameters:**
- `objectId` (str): Parent object ID
**Returns:** dict - List of reactions
---
### reaction.listbyparent()
List all reactions for a parent object.
```python
reactions = API.run_job('reaction.listbyparent', parent_id)
```
**Parameters:**
- `parentPK` (str): Parent partition key
- `parentSK` (str): Parent sort key
**Returns:** dict - List of reactions
---
## 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:**
- `pk` (str): Trust identifier (partition key)
- `sk` (str): Trust identifier (sort key)
- `trustType` (str): Trust type ("positive", "negative", etc.)
- Other optional fields
**Returns:** dict - Trust relationship status
**Example:**
```python
trust = API.run_job('trust.createorupdate', {
"pk": "trust-id-123",
"sk": "trust-id-123",
"trustType": "positive"
})
```
---
### trust.listbyusersinit()
Lists trust relationships initialized by a user.
```python
trusts = API.run_job('trust.listbyusersinit', username)
```
**Parameters:**
- `username` (str): The user whose trust relationships to list
**Returns:** dict - List of trust relationships
**Example:**
```python
my_trusts = API.run_job('trust.listbyusersinit', "your-username")
```
---
### trust.listbyuserhas()
Lists trust relationships where a user was the target.
```python
trusts = API.run_job('trust.listbyuserhas', username)
```
**Parameters:**
- `username` (str): The user 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_name)
```
**Parameters:**
- `branchName` (str): The branch identifier
**Returns:** dict - Branch data
**Example:**
```python
branch = API.run_job('branch.get', "main")
print(branch.get('branchName'))
```
---
### branch.listbyname()
List branches by name prefix.
```python
branches = API.run_job('branch.listbyname', prefix)
```
**Parameters:**
- `prefix` (str): String prefix for branch names
**Returns:** dict - List of matching branches
**Example:**
```python
music_branches = API.run_job('branch.listbyname', "music")
```
---
## Feed Jobs
Get content feeds from TrustCafé.
### feed.cafefeed()
Get the café-wide feed.
```python
feed = API.run_job('feed.cafefeed')
```
**Parameters:** None
**Returns:** dict - Café feed content
**Example:**
```python
cafefeed = API.run_job('feed.cafefeed')
print(f"Feed items: {len(cafefeed.get('Items', []))}")
```
---
### feed.following()
Get feed for users you follow.
```python
feed = API.run_job('feed.following')
```
**Parameters:** None
**Returns:** dict - Following feed content
**Example:**
```python
following_feed = API.run_job('feed.following')
print(f"Following feed items: {len(following_feed.get('Items', []))}")
```
---
## Block Jobs
Block users or content.
### block.[notimplemented]
Block functionality is defined in the backend but not yet implemented in the wrapper.
**Status:** TODO
**Implementation needed:**
- Job function creation
- Payload structure definition
- Error handling
---
## Mute Jobs
Mute users or content.
### mute.[notimplemented]
Mute functionality is pending implementation.
**Status:** TODO
**Implementation needed:**
- Job function creation
- Payload structure definition
- Error handling
---
## 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