Complete API Reference
🚀 Universal API Standards
All MyStoryFlow tools follow identical API patterns for consistency, maintainability, and developer experience. This reference covers all endpoints with complete request/response specifications.
📋 Response Format Standards
Universal Response Interface
interface UniversalApiResponse<T = any> {
success: boolean
data?: T
error?: {
code: string
message: string
details?: any
field?: string
timestamp: string
}
meta?: {
timestamp: string
requestId: string
processingTime: number
pagination?: PaginationMeta
rateLimit?: RateLimitMeta
conversionOpportunity?: boolean
debugInfo?: any
}
}
interface PaginationMeta {
page: number
limit: number
total: number
totalPages: number
hasNext: boolean
hasPrev: boolean
}
interface RateLimitMeta {
limit: number
remaining: number
resetTime: number
retryAfter?: number
}HTTP Status Codes
200- Success201- Created (for new resources)400- Bad Request (validation errors)401- Unauthorized403- Forbidden (access denied)404- Not Found429- Too Many Requests (rate limited)500- Internal Server Error
🤖 Generation Endpoints
POST /api/{tool}/generate
Generate AI-powered content for any tool.
Request Headers
Content-Type: application/json
X-Session-ID: sess_{timestamp}_{random} (required)Request Body
interface GenerateRequest {
sessionId: string // User session identifier
options: ToolSpecificOptions // Tool-specific generation parameters
humanVerification?: string // Optional human verification token
}
// Example for Plot Twist Generator
interface PlotTwistOptions {
genre: string // "mystery" | "thriller" | "romance" etc.
storyType: string // "novel" | "short-story" | "screenplay"
intensity: string // "subtle" | "dramatic" | "mind-blowing"
plotElements?: string[] // Optional specific elements to include
customContext?: string // Optional additional context
}Response
interface GenerateResponse {
success: true
data: {
id: string // Database ID
shareCode: string // Unique share identifier
title: string // Generated content title
content: ToolSpecificContent // Tool-specific generated content
seoMetadata: {
title: string
description: string
keywords: string[]
}
aiMetadata: {
model: string // AI model used
tokensUsed: number // Token consumption
processingTime: number // Generation time in ms
confidenceScore: number // Quality confidence (0-1)
}
}
meta: {
timestamp: string
requestId: string
processingTime: number
rateLimit: RateLimitMeta
conversionOpportunity: boolean
}
}Error Responses
// Rate Limit Exceeded (429)
{
success: false,
error: {
code: "RATE_LIMIT_EXCEEDED",
message: "Generation limit reached. Try again in 1 minute.",
details: {
currentUsage: 5,
dailyLimit: 5,
resetTime: 1642780800
},
timestamp: "2024-07-21T10:30:45Z"
},
meta: {
rateLimit: {
limit: 5,
remaining: 0,
resetTime: 1642780800,
retryAfter: 60
},
conversionOpportunity: true
}
}
// Invalid Input (400)
{
success: false,
error: {
code: "INVALID_INPUT",
message: "Genre is required",
field: "genre",
timestamp: "2024-07-21T10:30:45Z"
}
}
// Internal Error (500)
{
success: false,
error: {
code: "INTERNAL_ERROR",
message: "An unexpected error occurred. Please try again.",
timestamp: "2024-07-21T10:30:45Z"
}
}Rate Limits
- Anonymous users: 5 generations per hour per IP/session
- Authenticated users: 50 generations per hour
- Premium users: 500 generations per hour
cURL Example
curl -X POST "https://tools.mystoryflow.com/api/plot-twists/generate" \
-H "Content-Type: application/json" \
-H "X-Session-ID: sess_1642780800_abc123" \
-d '{
"sessionId": "sess_1642780800_abc123",
"options": {
"genre": "mystery",
"storyType": "novel",
"intensity": "dramatic",
"customContext": "Set in Victorian London"
}
}'📋 Browse & Discovery Endpoints
GET /api/{tool}
Browse and filter existing content for any tool.
Query Parameters
interface BrowseQuery {
page?: number // Page number (default: 1)
limit?: number // Items per page (default: 20, max: 100)
sort?: string // "newest" | "popular" | "featured" | "rating"
search?: string // Search query
public?: boolean // Filter public content only
featured?: boolean // Filter featured content only
category?: string // Tool-specific category filter
sessionId?: string // Include user's own content
}Response
interface BrowseResponse {
success: true
data: Array<{
id: string
shareCode: string
title: string
content: any // Tool-specific content structure
seoTitle: string
seoDescription: string
keywords: string[]
viewCount: number
shareCount: number
responseCount: number
averageRating: number
createdAt: string
updatedAt: string
isPublic: boolean
isFeatured: boolean
}>
meta: {
timestamp: string
processingTime: number
pagination: PaginationMeta
}
}Examples
# Get newest content
GET /api/story-prompts?page=1&limit=10&sort=newest
# Search for romance content
GET /api/story-prompts?search=romance&public=true
# Get user's own content
GET /api/story-prompts?sessionId=sess_123&public=false
# Get featured content only
GET /api/story-prompts?featured=true&sort=popular💬 User Response System Endpoints
POST /api/{tool}/{id}/responses
Create a user response to generated content.
Request Body
interface CreateResponseRequest {
sessionId: string // User session identifier
title: string // Response title (1-200 characters)
content: string // Response content (1-50,000 characters)
isPublic?: boolean // Make response public (default: false)
}Response
interface CreateResponseResponse {
success: true
data: {
id: string
title: string
content: string
wordCount: number
characterCount: number
isPublic: boolean
moderationStatus: string // "pending" | "approved" | "rejected"
createdAt: string
updatedAt: string
}
}GET /api/{tool}/{id}/responses
Get responses for a piece of content.
Query Parameters
page: Page number (default: 1)limit: Items per page (default: 10, max: 50)public: Show only public responsessessionId: Include user’s own responses
Response
interface GetResponsesResponse {
success: true
data: Array<{
id: string
title: string
content: string
wordCount: number
characterCount: number
isPublic: boolean
viewCount: number
likeCount: number
shareCount: number
qualityScore: number
createdAt: string
updatedAt: string
}>
meta: {
pagination: PaginationMeta
}
}PATCH /api/{tool}/responses/{responseId}
Update an existing response.
Request Body
interface UpdateResponseRequest {
sessionId: string // Required for ownership verification
title?: string // Optional title update
content?: string // Optional content update
isPublic?: boolean // Optional visibility update
}DELETE /api/{tool}/responses/{responseId}
Delete a response (soft delete).
Request Body
interface DeleteResponseRequest {
sessionId: string // Required for ownership verification
reason?: string // Optional deletion reason
}🔗 Sharing System Endpoints
POST /api/{tool}/share
Create a share link for content.
Request Body
interface CreateShareRequest {
contentId: string // Content to share
sessionId: string // User session
shareType?: string // "public" | "private" | "expiring"
expiresAt?: string // Optional expiration date
}Response
interface CreateShareResponse {
success: true
data: {
shareCode: string // Unique share identifier
shareUrl: string // Full shareable URL
expiresAt?: string // Expiration date if applicable
createdAt: string
}
}GET /api/{tool}/share/{shareCode}
View shared content.
Response
interface ShareViewResponse {
success: true
data: {
id: string
shareCode: string
title: string
content: any
seoMetadata: {
title: string
description: string
keywords: string[]
}
analytics: {
viewCount: number
shareCount: number
responseCount: number
averageRating: number
}
responses: Array<{
id: string
title: string
content: string
wordCount: number
isPublic: boolean
createdAt: string
}>
createdAt: string
expiresAt?: string
}
meta: {
conversionOpportunity: boolean
}
}📄 Export System Endpoints
POST /api/{tool}/{id}/export
Export content in various formats.
Request Body
interface ExportRequest {
format: "json" | "csv" | "pdf" | "html" | "docx"
options?: {
includeMetadata?: boolean // Include generation metadata
includeResponses?: boolean // Include user responses
theme?: "light" | "dark" // Visual theme for PDF/HTML
template?: string // Custom template name
pageSize?: "a4" | "letter" // PDF page size
fontSize?: number // Text size for PDF
}
}Response
Binary file download with appropriate headers:
Content-Type: application/json | text/csv | application/pdf | text/html | application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Disposition: attachment; filename="content-export.{ext}"
Content-Length: {file-size}Supported Export Formats
JSON Export:
{
"metadata": {
"tool": "plot-twists",
"title": "Generated Plot Twists",
"createdAt": "2024-07-21T10:30:45Z",
"shareCode": "twist-sunset-7k2m"
},
"content": {
// Tool-specific content structure
},
"responses": [
// User responses if included
],
"analytics": {
"viewCount": 156,
"shareCount": 23,
"responseCount": 8
}
}CSV Export (for tabular data):
Field,Value
Title,"Generated Plot Twists"
Created At,"2024-07-21T10:30:45Z"
Share Code,"twist-sunset-7k2m"
View Count,156
// Tool-specific rows...🔍 Search Endpoints
GET /api/search
Global search across all tools and content.
Query Parameters
interface SearchQuery {
q: string // Search query (required)
tools?: string[] // Filter by specific tools
type?: string // "content" | "responses" | "all"
public?: boolean // Public content only
page?: number // Page number
limit?: number // Results per page
sort?: string // "relevance" | "date" | "popular"
}Response
interface SearchResponse {
success: true
data: {
content: Array<{
id: string
tool: string
type: "content" | "response"
title: string
excerpt: string
shareCode?: string
createdAt: string
relevanceScore: number
}>
suggestions: string[] // Query suggestions
facets: {
tools: Array<{ name: string; count: number }>
types: Array<{ name: string; count: number }>
}
}
meta: {
query: string
totalResults: number
processingTime: number
pagination: PaginationMeta
}
}📊 Analytics Endpoints
POST /api/{tool}/{id}/analytics
Track user interactions and analytics events.
Request Body
interface AnalyticsEvent {
sessionId: string
eventType: string // "view" | "share" | "export" | "response_created"
eventData?: any // Optional event-specific data
timestamp?: string // Auto-generated if not provided
}Response
interface AnalyticsResponse {
success: true
data: {
eventId: string
recorded: boolean
}
}GET /api/{tool}/{id}/analytics
Get analytics data for content (admin only).
Response
interface ContentAnalytics {
success: true
data: {
views: {
total: number
unique: number
trend: Array<{ date: string; count: number }>
}
shares: {
total: number
platforms: Record<string, number>
}
responses: {
total: number
public: number
averageWordCount: number
}
exports: {
total: number
formats: Record<string, number>
}
engagement: {
averageTimeOnPage: number
bounceRate: number
conversionRate: number
}
}
}🔐 Authentication & Session Management
Session-Based Access
All tools use session-based authentication:
- Anonymous sessions:
sess_{timestamp}_{random} - Authenticated sessions: Linked to user accounts
- Session persistence: 30 days inactivity timeout
Headers
interface RequiredHeaders {
"X-Session-ID": string // Always required
"Content-Type": "application/json" // For POST/PATCH
"User-Agent": string // For rate limiting
}
interface OptionalHeaders {
"X-User-ID": string // For authenticated users
"X-Request-ID": string // For request tracing
"Accept-Language": string // For localization
}⚠️ Error Handling
Standard Error Codes
Client Errors (4xx)
MISSING_SESSION_ID- Session ID not providedINVALID_INPUT- Request validation failedINVALID_FORMAT- Unsupported format requestedRATE_LIMIT_EXCEEDED- Too many requestsCONTENT_NOT_FOUND- Requested content doesn’t existACCESS_DENIED- User lacks permissionPARENT_NOT_FOUND- Parent content for response not found
Server Errors (5xx)
INTERNAL_ERROR- Unexpected server errorAI_SERVICE_ERROR- AI generation failedDATABASE_ERROR- Database operation failedEXPORT_FAILED- File export failedSAVE_FAILED- Content save failed
Error Response Format
interface ErrorResponse {
success: false
error: {
code: string // Machine-readable error code
message: string // Human-readable error message
details?: any // Additional error context
field?: string // Field name for validation errors
timestamp: string // Error occurrence time
}
meta?: {
requestId: string // For error tracking
processingTime: number
rateLimit?: RateLimitMeta // For rate limit errors
retryAfter?: number // Retry delay in seconds
}
}🚀 SDK Integration
TypeScript SDK Example
import { MyStoryFlowTools } from '@mystoryflow/tools-sdk'
const client = new MyStoryFlowTools({
baseUrl: 'https://tools.mystoryflow.com',
sessionId: 'your-session-id'
})
// Generate content
const result = await client.plotTwists.generate({
genre: 'mystery',
storyType: 'novel',
intensity: 'dramatic'
})
// Browse content
const content = await client.plotTwists.browse({
page: 1,
limit: 10,
sort: 'popular'
})
// Create response
const response = await client.plotTwists.createResponse(result.id, {
title: 'My Story Response',
content: 'This is my creative response...',
isPublic: true
})This comprehensive API reference covers all endpoints, patterns, and integration methods for MyStoryFlow’s standardized tools infrastructure, enabling consistent development and seamless integration across all tools.