PreEmpt.life API Documentation
Technical Specifications and Integration Guide
Version: 1.0
Effective Date: January 19, 2026
1. INTRODUCTION
The PreEmpt.Life API provides programmatic access to the platform's strategic foresight capabilities, enabling automated workflow integration, report generation, survey management, and custom application development.
API Base Implementation
- Architecture: AWS Serverless (Lambda + API Gateway)
- Runtime: Node.js 16.x
- Database: MySQL/PostgreSQL
- Cloud Provider: AWS (ap-southeast-2 region)
API Capabilities:
- User authentication and management
- Report generation and retrieval
- Story/synthesis generation using AI (OpenAI)
- Survey and question management
- Challenge and coupon management
- Document management
- Team session management
- Sharing and collaboration features
- PDF generation
- Payment processing via PayPal
2. AUTHENTICATION
2.1 JWT COOKIE AUTHENTICATION
The API uses JWT (JSON Web Token) authentication with HTTP-only cookies for secure session management.
Authentication Flow:
- User submits credentials to
/user_login - Server validates credentials and generates JWT
- JWT is set as an HTTP-only cookie
- Subsequent requests include the cookie automatically
Cookie Configuration:
Secure: true
SameSite: Strict
Path: /
Max-Age: 14 days (1,209,600 seconds)Example Login Request:
curl -X POST https://api.preempt.life/user_login \
-H "Content-Type: application/json" \
-d '{
"user": "user@example.com",
"password": "your_password",
"version": 1
}'2.2 PROTECTED ENDPOINTS
Protected endpoints require Cookie-based authentication and are accessed via the PreemptAuthAPI gateway. The authorizer validates the JWT token from the Cookie header.
Authentication Header (for protected endpoints):
Cookie: preempt_auth_token=<JWT_TOKEN>2.3 API GATEWAYS
The API has three distinct gateways:
| Gateway | Purpose | Authentication |
|---|---|---|
ResultsPlusGatewayAPI | Public endpoints | None |
PreemptAuthAPI | Protected endpoints | Cookie-based JWT |
PreemptGatewayBinaryAPI | Binary data (images, PDFs) | None |
3. REQUEST FORMAT
3.1 REQUEST HEADERS
Required Headers:
Content-Type: application/json
Accept: application/jsonOptional Headers (for protected endpoints):
Cookie: preempt_auth_token=<JWT_TOKEN>
Origin: https://your-domain.com3.2 REQUEST BODY
All POST, PUT, and PATCH requests use JSON format:
{
"userid": 123,
"reportId": 456,
"version": 1
}3.3 API VERSIONING
The API supports versioning through the version parameter:
{
"version": 1,
"userid": 123
}- v0 (default): Legacy implementation
- v1: Latest stable implementation
- v2/v3: Extended functionality for specific endpoints
3.4 DATE/TIME FORMAT
All dates use ISO 8601 format:
{
"created_at": "2026-01-17T14:30:00Z",
"date": "January 17, 2026, 14:30"
}4. RESPONSE FORMAT
4.1 STANDARD RESPONSE STRUCTURE
All API responses follow a consistent JSON structure:
{
"status": "success",
"messageid": "MSG_001",
"message": "Operation completed successfully",
"data": { }
}Response Fields:
| Field | Type | Description |
|---|---|---|
status | string | success or error |
messageid | string | Unique message identifier |
message | string | Human-readable message |
data | object/array | Response payload (optional) |
4.2 SUCCESS RESPONSES
{
"status": "success",
"messageid": "SUCCESSFULLY_LOGIN",
"message": "User logged in successfully",
"data": {
"userInfo": {
"userId": 123,
"email": "user@example.com",
"username": "johndoe",
"name": "John Doe",
"role": "user"
}
}
}4.3 ERROR RESPONSES
{
"status": "error",
"messageid": "INVALID_PAYLOAD",
"message": "Invalid request payload"
}4.4 COMMON MESSAGE IDS
| Message ID | Status | Description |
|---|---|---|
SUCCESSFULLY_LOGIN | success | User authenticated |
FAILED_TO_LOGIN | error | Authentication failed |
USER_NOT_FOUND | error | User does not exist |
UNVERIFIED_LOGIN | error | Email not verified |
INVALID_PAYLOAD | error | Missing/invalid parameters |
SUCCESSFULLY_LOAD_STORIES | success | Reports retrieved |
FAILED_TO_LOAD_STORIES | error | Report retrieval failed |
5. API ENDPOINTS
5.1 AUTHENTICATION ENDPOINTS
User Login
POST /user_loginDescription: Authenticate user with email/username and password
Request Body:
{
"user": "user@example.com",
"password": "password123",
"version": 1
}Response:
{
"status": "success",
"messageid": "SUCCESSFULLY_LOGIN",
"message": "User logged in successfully",
"data": {
"userInfo": {
"userId": 123,
"email": "user@example.com",
"username": "johndoe",
"name": "John Doe",
"role": "user"
}
}
}Email Login
POST /email_loginDescription: Login using email and password only
Request Body:
{
"email": "user@example.com",
"password": "password123"
}Username Login
POST /username_loginDescription: Login using username and password
Request Body:
{
"username": "johndoe",
"password": "password123"
}User Registration
POST /user_registerDescription: Register a new user account
Request Body:
{
"email": "user@example.com",
"username": "johndoe",
"password": "password123",
"name": "John Doe"
}Email Registration
POST /email_registerDescription: Register using email only
Username Registration
POST /username_registerDescription: Register using username only
Email Verification
POST /email_verificationDescription: Send OTP to email for verification
Request Body:
{
"email": "user@example.com"
}OTP Verification
POST /OTP_verificationDescription: Verify the OTP sent to email
Request Body:
{
"email": "user@example.com",
"otp": "123456"
}User Verify
POST /user_verifyDescription: Verify user account
User Cancel
POST /user_cancelDescription: Cancel user verification
Forgot Password Verification
POST /forgotpassword_verificationDescription: Send OTP for password reset
Request Body:
{
"email": "user@example.com"
}Change Password
POST /change_passwordDescription: Update user password
Request Body:
{
"userid": 123,
"old_password": "oldpass",
"new_password": "newpass"
}Resend Email Verification
POST /resend_email_verificationDescription: Resend verification email
Update Profile
POST /update_profileDescription: Update user profile information
Request Body:
{
"userid": 123,
"name": "John Doe",
"email": "new@example.com"
}Get User Profile
POST /get_user_profileDescription: Retrieve user profile details
Request Body:
{
"userid": 123
}5.2 REPORT ENDPOINTS
Get Reports
POST /get_reportDescription: Get all reports for a user
Request Body:
{
"userid": 123,
"version": 1
}Response:
{
"status": "success",
"messageid": "SUCCESSFULLY_LOAD_STORIES",
"message": "Reports loaded successfully",
"data": [
{
"id": 456,
"title": "Strategic Analysis 2026",
"status": "done",
"progress": 100,
"date": "January 17, 2026, 14:30",
"kg_progress": true
}
]
}Get Report Info
POST /get_report_infoDescription: Get detailed information about a specific report
Request Body:
{
"reportId": 456
}Get Report Count
POST /get_report_countDescription: Get total number of reports for a user
Request Body:
{
"userid": 123
}Get Report Table Data
GET /get_report_table_dataDescription: Get all reports for admin dashboard display
Get Report Order Info
POST /get_report_order_infoDescription: Get order information about a report
Delete Report
POST /delete_reportDescription: Delete a specific report
Request Body:
{
"reportId": 456
}Archive Report
POST /archive_reportDescription: Archive a report
Request Body:
{
"reportId": 456
}Get Archive Report
POST /get_archive_reportDescription: Get archived reports
Get Admin Report
POST /get_admin_reportDescription: Get admin-level report data (Protected)
5.3 STORY/AI GENERATION ENDPOINTS
Queue Generate Story (Protected)
POST /queue_generatestoryDescription: Queue a story generation request
Authentication: Cookie-based JWT required
Request Body:
{
"reportId": 456,
"userid": 123
}Latest Generate Story (Protected)
POST /latest_generate_storyDescription: Generate story using latest AI model (GPT 3.5+)
Authentication: Cookie-based JWT required
Get AI Story
POST /get_aistoryDescription: Retrieve AI-generated story content
Request Body:
{
"reportId": 456,
"storyId": 789
}Get Generation Status
GET /get_generationstatusDescription: Check the status of report generation
Query Parameters:
?reportId=456Save Story
POST /save_storyDescription: Save user's created story
Request Body:
{
"userid": 123,
"story": "Story content here..."
}Get Save Story
POST /get_savestoryDescription: Retrieve saved story data
Update User Story
POST /update_userstoryDescription: Update existing user story
5.4 TEAM/SESSION ENDPOINTS
Queue Generate Team (Protected)
POST /queue_generateteamDescription: Queue team answer generation
Authentication: Cookie-based JWT required
Save Session
POST /save_sessionDescription: Save a team session
Request Body:
{
"sessionName": "Q1 Strategy Session",
"participants": ["user1@example.com", "user2@example.com"]
}Continue Save Session
GET /continuesavesessionDescription: Continue saved session workflow
Get Sessions
POST /get_sessionsDescription: Get all sessions for a user
Request Body:
{
"userid": 123
}Get Session ID
POST /get_sessionIDDescription: Get specific session by ID
5.5 PROMPT MANAGEMENT ENDPOINTS
Create Prompt
POST /create_promptDescription: Create a new prompt template
Request Body:
{
"name": "New Prompt",
"content": "Prompt content...",
"categoryId": 1
}Edit Prompt
POST /edit_promptDescription: Edit existing prompt template
Delete Prompt
POST /delete_promptDescription: Delete a prompt template
Get Prompt
POST /get_promptDescription: Retrieve prompt details
Get Prompt Types
POST /get_prompt_typesDescription: Get all prompt types
Get Prompt Chapters
POST /get_prompt_chaptersDescription: Get prompt chapters
Get Active Chapters
POST /get_active_chaptersDescription: Get chapters with at least one active prompt
Get Archived Chapters
POST /get_archived_chaptersDescription: Get archived chapters
Get Archived Prompts
POST /get_archived_promptsDescription: Get archived prompts
Archive Prompt
POST /archive_promptDescription: Archive a prompt
Restore Prompt
POST /restore_promptDescription: Restore archived prompt
Create Prompt Type
POST /create_prompt_typeDescription: Create new prompt type/chapter
Edit Prompt Type
POST /edit_prompt_typeDescription: Edit prompt type
Archive Prompt Type
POST /archive_prompt_typeDescription: Archive a prompt type
Restore Prompt Type
POST /restore_prompt_typeDescription: Restore archived prompt type
Update Prompt Order
POST /update_promptorderDescription: Update the order of prompts
Update Prompt Status
POST /update_promptstatusDescription: Update prompt active/inactive status
Update Chapter Order
POST /update_chapterorderDescription: Update the order of chapters
Update Prompt Category
POST /update_promptcategoryDescription: Update prompt category
Delete Prompt Category
POST /delete_promptcategoryDescription: Delete a prompt category
Restore Prompt Category
POST /restore_promptcategoryDescription: Restore deleted category
Test Prompt
POST /test_promptDescription: Test a prompt with AI
Queue Test Prompt (Protected)
POST /queue_testpromptDescription: Queue a test prompt execution
Authentication: Cookie-based JWT required
Get Test Status
GET /get_teststatusDescription: Get test prompt execution status
5.6 QUESTION MANAGEMENT ENDPOINTS
Create Question
POST /create_questionDescription: Create new questions in a category
Request Body:
{
"questions": ["Question 1?", "Question 2?"],
"categoryid": 1
}Edit Question
POST /edit_questionDescription: Edit an existing question
Request Body:
{
"questionid": 123,
"question": "Updated question text?",
"categoryid": 1
}Delete Question
POST /delete_questionDescription: Delete a question
Get Questions
POST /get_questionsDescription: Get questions by category
Request Body:
{
"categoryID": 1
}Create Question Category
POST /create_question_categoryDescription: Create new question category
Request Body:
{
"name": "Category Name",
"description": "Category description",
"type": "survey"
}Edit Question Category
POST /edit_question_categoryDescription: Edit question category
Delete Question Category
POST /delete_question_categoryDescription: Delete category and its questions
Get Question Categories
GET /get_question_categoriesDescription: Get all question categories
Get Question Categories By Type
POST /get_question_categories_by_typeDescription: Get categories filtered by type
Request Body:
{
"Type": "survey"
}Valid Types: mylife, myteam, survey, ct
Update Category Priority
POST /update_category_priorityDescription: Update category ordering
Request Body:
[
{"categoryid": 1, "priority": 1},
{"categoryid": 2, "priority": 2}
]Update Question Priority
POST /update_question_priorityDescription: Update question ordering
5.7 REPORT ANSWER ENDPOINTS
Save Report Answer
POST /save_report_answerDescription: Save user answers to report questions
Request Body:
{
"reportID": 456,
"userID": 123,
"questionAnswers": [
{"questionid": 1, "answer": "User's answer"},
{"questionid": 2, "answer": "Another answer"}
]
}Get Report Answers By Category
POST /get_report_answers_by_categoryDescription: Get answers by category
Request Body:
{
"reportID": 456,
"userID": 123,
"categoryID": 1
}Get Report Answers From Story
POST /get_report_answers_from_storyDescription: Get answers associated with a story
Get All Report Answers By Owner
POST /get_all_report_answers_by_ownerDescription: Get all answers by report owner
Get All Answers By Report
POST /get_all_answers_by_reportDescription: Get all answers for a specific report
5.8 SHARING ENDPOINTS
Share Report
POST /share_reportDescription: Create shareable link for report
Request Body:
{
"reportId": 456,
"emails": ["recipient@example.com"]
}Verify Share ID
POST /verify_shareidDescription: Verify a share link is valid
Request Body:
{
"shareId": "abc123xyz"
}Save Share Report Answer
POST /save_share_report_answerDescription: Save answers from shared report
Get Share Report Answer
POST /get_share_report_answerDescription: Get answers from shared report
Save Public Report Answer
POST /save_public_report_answerDescription: Save answers for public reports
Get Public Report Answer
POST /get_public_report_answerDescription: Get public report answers
Get All Shared Report Responses
POST /get_all_shared_report_responsesDescription: Get all shared responses for a report
Get All Shared Report Responses By Question
POST /get_all_shared_report_responses_by_questionDescription: Get shared responses filtered by question
Get All Shared Report Responses By Category
POST /get_all_shared_report_responses_by_categoryDescription: Get shared responses filtered by category
Get All Shared Report Responses By Share ID
POST /get_all_shared_report_responses_by_share_idDescription: Get responses for specific share ID
5.9 DOCUMENT MANAGEMENT ENDPOINTS
Create Document
POST /create_documentDescription: Create a new document
Edit Document
POST /edit_documentDescription: Edit existing document
Get All Documents
POST /get_all_documentsDescription: Get all documents
Get Document By ID
POST /get_document_by_idDescription: Get specific document
Get Document Content
POST /get_document_contentDescription: Get document contents
Get Shared Document Content
POST /get_shared_document_contentDescription: Get shared document contents
Get Included Documents
GET /get_included_documentsDescription: Get included documents
Update Document Order
POST /update_document_orderDescription: Update document ordering
Upload Document Image
POST /upload_document_imageDescription: Upload image for document
5.10 SURVEY ENDPOINTS
Save Survey
POST /save_surveyDescription: Save survey data
Save Survey Answers
POST /save_survey_answersDescription: Store survey responses
Survey Response Queue
POST /survey_responseDescription: Queue survey response generation
Get Survey Status
POST /get_survey_statusDescription: Get survey generation status
Get Survey Answers
GET /get_survey_answersDescription: Get survey answers
Get All Survey Answers
GET /get_all_survey_answersDescription: Get all Have Your Say answers
Delete Have Your Say Answers
POST /delete_have_your_say_answersDescription: Delete survey responses
Get Survey Response Story
GET /get_survey_response_storyDescription: Get generated survey response
5.11 COUPON ENDPOINTS
Create Coupon
POST /create_couponDescription: Create a new coupon
Edit Coupon
POST /edit_couponDescription: Edit existing coupon
Delete Coupon
POST /delete_couponDescription: Delete a coupon
Get Coupon
POST /get_couponDescription: Get coupon list/details
Generate Coupon
POST /generate_couponDescription: Auto-generate coupon code
5.12 CHALLENGE ENDPOINTS
Create Challenge
POST /create_challengeDescription: Create new challenge
Update Challenge
POST /update_challengeDescription: Update challenge details
Update Challenge Blog
POST /update_challenge_blogDescription: Update challenge blog content
Delete Challenge
POST /delete_challengeDescription: Delete a challenge
Get Challenges
POST /get_challengesDescription: Get all challenges
Upload Image Challenge
POST /upload_image_challengeDescription: Upload challenge image
5.13 PDF GENERATION ENDPOINTS
Queue Generate PDF
POST /queue_generatepdfDescription: Queue PDF generation
Queue Public Generate PDF
POST /queue_public_generatepdfDescription: Queue public PDF generation
Queue Shared Generate PDF
POST /queue_shared_generatepdfDescription: Queue shared PDF generation
5.14 PAYMENT ENDPOINTS
Buy Report (Protected)
GET /buyreportDescription: Initiate PayPal transaction
Authentication: Cookie-based JWT required
Query Parameters:
?currency=USD&amount=99.00&version=3Continue Buy Report
GET /continuebuyreportDescription: Continue payment after PayPal redirect
Create Receipt
POST /create_receiptDescription: Create payment receipt
Get Bill
POST /get_billDescription: Get billing information
Get Receipt Count
POST /get_receipt_countDescription: Get number of receipts
Get Receipt By Report ID
POST /get_receipt_by_report_idDescription: Get receipt for specific report
5.15 SEARCH & ANALYSIS ENDPOINTS
Queue Basic Search (Protected)
POST /queue_basic_searchDescription: Queue basic search operation
Authentication: Cookie-based JWT required
Get Basic Search Status
GET /get_basic_search_statusDescription: Get basic search status
Queue KG Search (Protected)
POST /queue_kg_searchDescription: Queue Knowledge Graph search
Authentication: Cookie-based JWT required
Get KG Search Status
GET /get_kg_search_statusDescription: Get KG search status
KG Request
POST /kg_requestDescription: Send Knowledge Graph request
Queue Generate Analysis (Protected)
POST /queue_generate_analysisDescription: Queue analysis generation
Authentication: Cookie-based JWT required
Get Analysis Status
GET /get_analysis_statusDescription: Get analysis generation status
5.16 FEEDBACK ENDPOINTS
Save Feedback
POST /save_feedbackDescription: Save user feedback
Save Footer Feedback
POST /save_footer_feedbackDescription: Save footer feedback
Get Footer Feedback
POST /get_footer_feedbackDescription: Get footer feedback
Get All Footer Feedback
POST /get_all_footer_feedbackDescription: Get all footer feedback entries
Delete Footer Feedback
POST /delete_footer_feedbackDescription: Delete footer feedback
Update Footer Feedback
POST /update_footer_feedbackDescription: Update footer feedback
Get Homepage Feedback
POST /get_homepage_feedbackDescription: Get homepage reviews/feedback
Get Feedback Per User
GET /get_feedback_per_userDescription: Get feedback by user
5.17 ADMIN ENDPOINTS
Get Users And Total Reports
GET /get_users_and_total_reportsDescription: Get all users with report counts
Check Password
POST /check_passwordDescription: Validate password
Check Report Privacy
POST /check_report_privacyDescription: Check report privacy settings
Update Public ID Report
POST /update_public_id_reportDescription: Update report public ID
Restrict Email Spam
POST /restrict_email_spamDescription: Control email spam prevention
Add Subscription Client Monitoring
POST /add_subscription_client_monitoringDescription: Add client monitoring subscription
Get Subscriptions Client Monitoring
GET /get_subscriptions_client_monitoringDescription: Get all client monitoring subscriptions
5.18 UTILITY ENDPOINTS
Dropdown Content
POST /dropdown_contentDescription: Get dropdown menu content
Get Email Address By User ID
POST /get_email_address_by_user_idDescription: Get email by user ID
GPT Response
POST /gpt_responseDescription: Get GPT-generated questions
Global Response
POST /global_responseDescription: Get global GPT response
Prompts API
POST /promptsDescription: Handle prompt operations for clients
Get Webtext Content
POST /get_webtext_contentDescription: Get web text content
Get Personality
POST /get_personalityDescription: Get user personality data
6. CODE EXAMPLES
6.1 JAVASCRIPT (NODE.JS) EXAMPLE
const axios = require('axios');
const BASE_URL = 'https://api.preempt.life';
// Create axios instance with cookie handling
const client = axios.create({
baseURL: BASE_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
});
// Login
async function login(user, password) {
try {
const response = await client.post('/user_login', {
user,
password,
version: 1
});
if (response.data.status === 'success') {
console.log('Logged in:', response.data.data.userInfo);
return response.data.data.userInfo;
} else {
throw new Error(response.data.message);
}
} catch (error) {
console.error('Login failed:', error.message);
throw error;
}
}
// Get Reports
async function getReports(userid) {
try {
const response = await client.post('/get_report', {
userid,
version: 1
});
if (response.data.status === 'success') {
return response.data.data;
}
throw new Error(response.data.message);
} catch (error) {
console.error('Failed to get reports:', error.message);
throw error;
}
}
// Usage
(async () => {
try {
const user = await login('user@example.com', 'password123');
const reports = await getReports(user.userId);
console.log('Reports:', reports);
} catch (error) {
console.error('Error:', error);
}
})();6.2 PYTHON EXAMPLE
import requests
import json
BASE_URL = 'https://api.preempt.life'
class PreemptClient:
def __init__(self):
self.session = requests.Session()
self.session.headers.update({
'Content-Type': 'application/json'
})
def login(self, user: str, password: str) -> dict:
"""Login and store session cookie"""
response = self.session.post(
f'{BASE_URL}/user_login',
json={
'user': user,
'password': password,
'version': 1
}
)
data = response.json()
if data['status'] == 'success':
return data['data']['userInfo']
else:
raise Exception(data['message'])
def get_reports(self, userid: int) -> list:
"""Get all reports for a user"""
response = self.session.post(
f'{BASE_URL}/get_report',
json={'userid': userid, 'version': 1}
)
data = response.json()
if data['status'] == 'success':
return data['data']
else:
raise Exception(data['message'])
def create_question_category(self, name: str, description: str,
category_type: str) -> dict:
"""Create a new question category"""
response = self.session.post(
f'{BASE_URL}/create_question_category',
json={
'name': name,
'description': description,
'type': category_type
}
)
return response.json()
# Usage
if __name__ == '__main__':
client = PreemptClient()
try:
user = client.login('user@example.com', 'password123')
print(f"Logged in as: {user['name']}")
reports = client.get_reports(user['userId'])
print(f"Found {len(reports)} reports")
for report in reports:
print(f" - {report['title']}: {report['status']}")
except Exception as e:
print(f"Error: {e}")6.3 CURL EXAMPLES
Login:
curl -X POST https://api.preempt.life/user_login \
-H "Content-Type: application/json" \
-c cookies.txt \
-d '{
"user": "user@example.com",
"password": "password123",
"version": 1
}'Get Reports:
curl -X POST https://api.preempt.life/get_report \
-H "Content-Type: application/json" \
-b cookies.txt \
-d '{
"userid": 123,
"version": 1
}'Create Question:
curl -X POST https://api.preempt.life/create_question \
-H "Content-Type: application/json" \
-d '{
"questions": ["What are your goals?", "What challenges do you face?"],
"categoryid": 1
}'Get Question Categories:
curl https://api.preempt.life/get_question_categories7. ERROR HANDLING
7.1 ERROR RESPONSE FORMAT
All errors follow the standard response format:
{
"status": "error",
"messageid": "ERROR_CODE",
"message": "Human readable error message"
}7.2 COMMON ERROR CODES
| Error Code | Description | Resolution |
|---|---|---|
INVALID_PAYLOAD | Missing or invalid request parameters | Check required fields |
USER_NOT_FOUND | User does not exist | Verify user credentials |
FAILED_TO_LOGIN | Authentication failed | Check password |
UNVERIFIED_LOGIN | Email not verified | Complete verification |
UNAUTHORIZED | JWT token invalid/expired | Re-authenticate |
FORBIDDEN | Insufficient permissions | Check user role |
RESOURCE_NOT_FOUND | Requested resource doesn't exist | Verify resource ID |
INTERNAL_ERROR | Server-side error | Retry or contact support |
7.3 HTTP STATUS CODES
| Status Code | Meaning | Use Case |
|---|---|---|
| 200 | OK | Successful requests |
| 301 | Redirect | PayPal payment redirects |
| 400 | Bad Request | Invalid payload |
| 401 | Unauthorized | Missing/invalid auth |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 500 | Internal Server Error | Server error |
7.4 ERROR HANDLING BEST PRACTICES
async function makeApiCall(endpoint, data) {
try {
const response = await client.post(endpoint, data);
if (response.data.status === 'error') {
// Handle API-level errors
switch (response.data.messageid) {
case 'INVALID_PAYLOAD':
throw new ValidationError(response.data.message);
case 'UNAUTHORIZED':
// Re-authenticate
await refreshAuth();
return makeApiCall(endpoint, data);
default:
throw new ApiError(response.data.message);
}
}
return response.data;
} catch (error) {
if (error.response) {
// HTTP error
console.error('HTTP Error:', error.response.status);
}
throw error;
}
}8. RATE LIMITING
8.1 API THROTTLING LIMITS
The PreEmpt.Life API uses AWS API Gateway throttling to ensure fair usage and system stability.
Default Rate Limits:
| Limit Type | Value | Scope |
|---|---|---|
| Steady-State Rate | 10,000 requests/second | Per API |
| Burst Limit | 5,000 requests | Per API |
| Per-Client Rate | 100 requests/second | Per IP/Client |
| Timeout | 29 seconds | Per request |
Lambda Function Limits:
| Limit Type | Value | Notes |
|---|---|---|
| Standard Timeout | 300 seconds (5 min) | Most endpoints |
| Long-Running Timeout | 900 seconds (15 min) | AI generation, PDF creation |
| Concurrent Executions | 1,000 | Per account/region |
8.2 ENDPOINT-SPECIFIC LIMITS
Some endpoints have specific rate limits due to resource intensity:
| Endpoint Category | Rate Limit | Reason |
|---|---|---|
/queue_generatestory | 10 req/min | OpenAI API quota |
/queue_generate_analysis | 10 req/min | AI processing |
/queue_generatepdf | 20 req/min | PDF generation load |
/buyreport | 30 req/min | Payment processing |
/email_verification | 5 req/min | Email spam prevention |
/restrict_email_spam | 5 req/min | Anti-spam measures |
8.3 RATE LIMIT HEADERS
Responses include rate limit headers when approaching limits:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1705673400
Retry-After: 60| Header | Description |
|---|---|
X-RateLimit-Limit | Maximum requests allowed per window |
X-RateLimit-Remaining | Remaining requests in current window |
X-RateLimit-Reset | Unix timestamp when limit resets |
Retry-After | Seconds to wait before retrying (on 429) |
8.4 RATE LIMIT EXCEEDED RESPONSE
When rate limits are exceeded, the API returns:
{
"statusCode": 429,
"message": "Too Many Requests",
"retryAfter": 60
}8.5 HANDLING RATE LIMITS
JavaScript Example:
async function makeRequestWithRetry(endpoint, data, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await client.post(endpoint, data);
return response.data;
} catch (error) {
if (error.response?.status === 429) {
const retryAfter = error.response.headers['retry-after'] || 60;
console.log(`Rate limited. Retrying in ${retryAfter}s...`);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
} else {
throw error;
}
}
}
throw new Error('Max retries exceeded');
}Python Example:
import time
def make_request_with_retry(endpoint, data, max_retries=3):
for attempt in range(max_retries):
try:
response = session.post(f'{BASE_URL}{endpoint}', json=data)
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', 60))
print(f"Rate limited. Retrying in {retry_after}s...")
time.sleep(retry_after)
continue
return response.json()
except Exception as e:
raise e
raise Exception('Max retries exceeded')8.6 BEST PRACTICES
Implement Exponential Backoff
const delay = Math.min(1000 * Math.pow(2, attempt), 30000);Cache Responses
- Cache GET responses for static data
- Use ETags for conditional requests
Batch Requests
- Combine multiple operations where possible
- Use bulk endpoints when available
Monitor Usage
- Track
X-RateLimit-Remainingheader - Slow down before hitting limits
- Track
Queue Long Operations
- Use async endpoints (
/queue_*) for heavy operations - Poll status endpoints instead of waiting synchronously
- Use async endpoints (
Respect Retry-After
- Always wait the specified duration before retrying
- Don't hammer the API after receiving a 429
9. SUPPORT & RESOURCES
Technical Resources
- Postman Documentation: https://documenter.getpostman.com/view/22398403/2s93m4ZP56 (opens in a new tab)
- AWS Region: ap-southeast-2 (Sydney)
Environments
| Environment | Configuration File | Use Case |
|---|---|---|
| Development | samconfig.dev.toml | Development testing |
| Test | samconfig.test.toml | Integration testing |
| Staging | samconfig.staging.toml | Pre-production |
| Sandbox | samconfig.sandbox.toml | Feature testing |
| Production | samconfig.prod.toml | Live environment |
Database Schema
Core Tables:
users- User accounts (id, username, email, password, verified, role)savestory- Saved stories (id, userid, mystory)savesurvey- Survey dataquestioncategories- Question categories (id, name, description, type, priority)formquestions- Questions (id, question, category_id)reportanswers- User answers (userID, reportID, questionID, answer, date_answered)
PreEmpt.Life API Documentation
Version 1.0
Last Updated: January 19, 2026
Next Review: April 19, 2026
