Quick integration examples
Node.js / JavaScript
const API_KEY = process.env.MPJ_API_KEY;
const BASE_URL = 'https://app.mypropjournal.com/api/v1';
// Helper function for API requests
async function apiRequest(endpoint, options = {}) {
const url = `${BASE_URL}${endpoint}`;
const config = {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
...options.headers
},
...options
};
const response = await fetch(url, config);
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error: ${error.error}`);
}
return response.json();
}
// Fetch trades
async function getTrades(startDate, endDate) {
const params = new URLSearchParams();
if (startDate) params.append('start_date', startDate);
if (endDate) params.append('end_date', endDate);
return apiRequest(`/trades?${params}`);
}
// Create trade
async function createTrade(tradeData) {
return apiRequest('/trades', {
method: 'POST',
body: JSON.stringify(tradeData)
});
}
// Usage
const trades = await getTrades('2024-01-01', '2024-12-31');
console.log(`Found ${trades.pagination.total} trades`);
Python
import os
import requests
from typing import Dict, Any, Optional
API_KEY = os.environ['MPJ_API_KEY']
BASE_URL = 'https://app.mypropjournal.com/api/v1'
class MyPropJournalAPI:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = BASE_URL
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
})
def _request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
"""Make API request with error handling"""
url = f'{self.base_url}{endpoint}'
response = self.session.request(method, url, **kwargs)
response.raise_for_status()
return response.json()
def get_trades(self, start_date: Optional[str] = None,
end_date: Optional[str] = None,
page: int = 1,
limit: int = 50) -> Dict[str, Any]:
"""Fetch trades with optional date filtering"""
params = {'page': page, 'limit': limit}
if start_date:
params['start_date'] = start_date
if end_date:
params['end_date'] = end_date
return self._request('GET', '/trades', params=params)
def create_trade(self, trade_data: Dict[str, Any]) -> Dict[str, Any]:
"""Create a new trade"""
return self._request('POST', '/trades', json=trade_data)
def get_performance(self, start_date: Optional[str] = None,
end_date: Optional[str] = None) -> Dict[str, Any]:
"""Get performance overview"""
params = {}
if start_date:
params['start_date'] = start_date
if end_date:
params['end_date'] = end_date
return self._request('GET', '/performance/overview', params=params)
# Usage
api = MyPropJournalAPI(API_KEY)
# Get recent trades
trades = api.get_trades(limit=10)
print(f"Total trades: {trades['pagination']['total']}")
# Get performance
performance = api.get_performance(start_date='2024-01-01')
print(f"Win rate: {performance['data']['win_rate']:.2f}%")
Ruby
require 'net/http'
require 'json'
require 'uri'
class MyPropJournalAPI
API_KEY = ENV['MPJ_API_KEY']
BASE_URL = 'https://app.mypropjournal.com/api/v1'
def initialize
@headers = {
'Authorization' => "Bearer #{API_KEY}",
'Content-Type' => 'application/json'
}
end
def get_trades(start_date: nil, end_date: nil, page: 1, limit: 50)
params = { page: page, limit: limit }
params[:start_date] = start_date if start_date
params[:end_date] = end_date if end_date
get('/trades', params)
end
def create_trade(trade_data)
post('/trades', trade_data)
end
private
def get(endpoint, params = {})
uri = URI("#{BASE_URL}#{endpoint}")
uri.query = URI.encode_www_form(params) unless params.empty?
request = Net::HTTP::Get.new(uri)
@headers.each { |key, value| request[key] = value }
make_request(uri, request)
end
def post(endpoint, data)
uri = URI("#{BASE_URL}#{endpoint}")
request = Net::HTTP::Post.new(uri)
@headers.each { |key, value| request[key] = value }
request.body = data.to_json
make_request(uri, request)
end
def make_request(uri, request)
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
raise "API Error: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
JSON.parse(response.body)
end
end
# Usage
api = MyPropJournalAPI.new
trades = api.get_trades(limit: 10)
puts "Total trades: #{trades['pagination']['total']}"
Rate limiting
Current status
Rate limits are not currently enforced. The API will accept unlimited requests.
Future implementation
When rate limiting is added:
- Standard tier: 1,000 requests per hour
- Response code:
429 Too Many Requests - Headers:
X-RateLimit-Limit,X-RateLimit-Remaining,Retry-After
Example rate limit response:
{
"error": "Rate limit exceeded",
"code": "RATE_LIMIT_EXCEEDED",
"retry_after": 3600
}
Handling rate limits:
async function fetchWithRateLimit(url, options) {
const response = await fetch(url, options);
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
const waitTime = parseInt(retryAfter) * 1000;
console.log(`Rate limited. Waiting ${retryAfter}s...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
// Retry the request
return fetchWithRateLimit(url, options);
}
return response;
}
API versioning
Current version
- Version:
v1(stable) - Prefix:
/api/v1
Versioning policy
- Backward compatibility: Version 1 endpoints will remain stable and backward-compatible
- Breaking changes: Major changes will be released as
v2,v3, etc. - Deprecation notice: At least 6 months advance notice before deprecating endpoints
- Parallel versions: Old and new versions will run simultaneously during the deprecation period
Deprecation notifications
When an endpoint is deprecated, you'll receive:
- Email notification and in-app message with migration guidance
- Response headers indicating deprecation:
X-API-Deprecated: trueSunsetheader with removal date (RFC 8594)X-API-Deprecation-InfoURL to migration guide
- Grace period: Minimum 6 months before endpoint removal
Example deprecated response:
HTTP/1.1 200 OK
X-API-Deprecated: true
Sunset: Sat, 1 Jan 2025 00:00:00 GMT
X-API-Deprecation-Info: https://docs.mypropjournal.com/api/migration-v2
{
"data": [...],
"deprecation_notice": "This endpoint will be removed on 2025-01-01. Please migrate to /api/v2/trades"
}
Best practices
- Always use HTTPS in production
- Store API keys securely (environment variables, secret managers)
- Implement retry logic with exponential backoff
- Handle pagination properly for large datasets
- Validate data before sending to API
- Log errors for debugging
- Monitor API usage and set up alerts
- Keep API client libraries up to date
- Test thoroughly before production deployment
- Read response headers for rate limit info (when implemented)