Code examples.
These examples show how to use the ForecastAPI endpoints in your applications. Copy an example and adapt it for your own code.
YOUR_API_KEY with your actual API key. Get your key from the
Dashboard.Jump to Example
Basic Forecasting
Generate time series forecasts. Provide your historical data. ForecastAPI automatically selects the best method for your data patterns.
curl -X POST https://forecastapi.com/v2/forecast \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"identifier": "SKU-12345",
"frequency": "M",
"data_type": "sales",
"periods": 6,
"data": [
{"date": "2024-01-01", "value": 120},
{"date": "2024-02-01", "value": 135},
{"date": "2024-03-01", "value": 155},
{"date": "2024-04-01", "value": 142},
{"date": "2024-05-01", "value": 168},
{"date": "2024-06-01", "value": 175}
]
}'
$response = Http::withToken('YOUR_API_KEY')
->post('https://forecastapi.com/v2/forecast', [
'identifier' => 'SKU-12345',
'frequency' => 'M',
'data_type' => 'sales',
'periods' => 6,
'data' => [
['date' => '2024-01-01', 'value' => 120],
['date' => '2024-02-01', 'value' => 135],
['date' => '2024-03-01', 'value' => 155],
['date' => '2024-04-01', 'value' => 142],
['date' => '2024-05-01', 'value' => 168],
['date' => '2024-06-01', 'value' => 175],
],
]);
$forecast = $response->json();
foreach ($forecast['result']['forecasts'] as $period) {
echo "{$period['date']}: {$period['forecast']} "
. "(range {$period['lower']}–{$period['upper']})\n";
}
import requests
response = requests.post(
'https://forecastapi.com/v2/forecast',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={
'identifier': 'SKU-12345',
'frequency': 'M',
'data_type': 'sales',
'periods': 6,
'data': [
{'date': '2024-01-01', 'value': 120},
{'date': '2024-02-01', 'value': 135},
{'date': '2024-03-01', 'value': 155},
{'date': '2024-04-01', 'value': 142},
{'date': '2024-05-01', 'value': 168},
{'date': '2024-06-01', 'value': 175},
]
}
)
forecast = response.json()
for period in forecast['result']['forecasts']:
print(f"{period['date']}: {period['forecast']} "
f"(range {period['lower']}–{period['upper']})")
const response = await fetch('https://forecastapi.com/v2/forecast', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
identifier: 'SKU-12345',
frequency: 'M',
data_type: 'sales',
periods: 6,
data: [
{ date: '2024-01-01', value: 120 },
{ date: '2024-02-01', value: 135 },
{ date: '2024-03-01', value: 155 },
{ date: '2024-04-01', value: 142 },
{ date: '2024-05-01', value: 168 },
{ date: '2024-06-01', value: 175 },
]
})
});
const forecast = await response.json();
forecast.result.forecasts.forEach(period => {
console.log(`${period.date}: ${period.forecast} (range ${period.lower}–${period.upper})`);
});
Example Response
ForecastAPI returns the forecast as an array under result.forecasts.
The array holds one object per period. Each object carries its date,
a point forecast, and
lower/upper
prediction bounds.
{
"result": {
"identifier": "SKU-12345",
"tenant_context": null,
"forecasts": [
{ "period": 1, "date": "2024-07-01", "forecast": 182.5, "lower": 165.3, "upper": 199.7 },
{ "period": 2, "date": "2024-08-01", "forecast": 189.2, "lower": 170.1, "upper": 208.3 },
{ "period": 3, "date": "2024-09-01", "forecast": 195.8, "lower": 175.4, "upper": 216.2 },
{ "period": 4, "date": "2024-10-01", "forecast": 202.1, "lower": 179.6, "upper": 224.6 },
{ "period": 5, "date": "2024-11-01", "forecast": 208.4, "lower": 183.9, "upper": 232.9 },
{ "period": 6, "date": "2024-12-01", "forecast": 214.6, "lower": 188.1, "upper": 241.1 }
],
"model_info": {
"best_model": "AutoETS",
"models_evaluated": ["AutoETS", "AutoARIMA", "AutoTheta", "SeasonalNaive"],
"selection_metric": "smape",
"interval_source": "conformal"
}
},
"meta": {
"selection_metric": "smape",
"timing": {
"validation": 8.2,
"selection": 45.6,
"forecasting": 72.1,
"total": 125.9
}
}
}
Data Analysis
Analyze your time series data before you generate a forecast. The analysis shows patterns, trends, and the recommended forecasting methods.
curl -X POST https://forecastapi.com/v2/analyze \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"identifier": "product-sales",
"frequency": "M",
"data_type": "sales",
"periods": 6,
"data": [
{"date": "2024-01-01", "value": 120},
{"date": "2024-02-01", "value": 135},
{"date": "2024-03-01", "value": 155},
{"date": "2024-04-01", "value": 142},
{"date": "2024-05-01", "value": 168},
{"date": "2024-06-01", "value": 175}
]
}'
$response = Http::withToken('YOUR_API_KEY')
->post('https://forecastapi.com/v2/analyze', [
'identifier' => 'product-sales',
'frequency' => 'M',
'data_type' => 'sales',
'periods' => 6,
'data' => [
['date' => '2024-01-01', 'value' => 120],
['date' => '2024-02-01', 'value' => 135],
['date' => '2024-03-01', 'value' => 155],
['date' => '2024-04-01', 'value' => 142],
['date' => '2024-05-01', 'value' => 168],
['date' => '2024-06-01', 'value' => 175],
],
]);
$analysis = $response->json();
echo "Pattern: " . $analysis['result']['pattern_type'];
echo "Recommended: " . implode(', ', $analysis['result']['recommended_methods']);
import requests
response = requests.post(
'https://forecastapi.com/v2/analyze',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={
'identifier': 'product-sales',
'frequency': 'M',
'data_type': 'sales',
'periods': 6,
'data': [
{'date': '2024-01-01', 'value': 120},
{'date': '2024-02-01', 'value': 135},
{'date': '2024-03-01', 'value': 155},
{'date': '2024-04-01', 'value': 142},
{'date': '2024-05-01', 'value': 168},
{'date': '2024-06-01', 'value': 175},
]
}
)
analysis = response.json()
print(f"Pattern: {analysis['result']['pattern_type']}")
print(f"Recommended: {analysis['result']['recommended_methods']}")
const response = await fetch('https://forecastapi.com/v2/analyze', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
identifier: 'product-sales',
frequency: 'M',
data_type: 'sales',
periods: 6,
data: [
{ date: '2024-01-01', value: 120 },
{ date: '2024-02-01', value: 135 },
{ date: '2024-03-01', value: 155 },
{ date: '2024-04-01', value: 142 },
{ date: '2024-05-01', value: 168 },
{ date: '2024-06-01', value: 175 },
]
})
});
const analysis = await response.json();
console.log('Pattern:', analysis.result.pattern_type);
console.log('Recommended:', analysis.result.recommended_methods);
Example Response
{
"result": {
"pattern_type": "regular",
"characteristics": {
"total_periods": 6,
"non_zero_events": 6,
"mean_value": 149.2,
"std_deviation": 21.8,
"trend_strength": 0.82,
"seasonality_detected": false
},
"recommended_methods": ["exponential_smoothing", "linear_trend"],
"confidence": "high"
},
"meta": {
"timing": {
"validation": 5.1,
"analysing": 42.3,
"total": 47.4
}
}
}
Inventory Planning
Get inventory recommendations from demand forecasting. The recommendations include reorder points, safety stock, and supplier comparisons.
curl -X POST https://forecastapi.com/v2/inventory-planning \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"identifier": "SKU-12345",
"frequency": "M",
"periods": 6,
"data": [
{"date": "2024-01-01", "value": 100},
{"date": "2024-02-01", "value": 120},
{"date": "2024-03-01", "value": 95},
{"date": "2024-04-01", "value": 130},
{"date": "2024-05-01", "value": 110},
{"date": "2024-06-01", "value": 125}
],
"inventory_settings": {
"current_stock": 250,
"minimum_stock": 50,
"service_level": 0.95,
"suppliers": [
{
"identifier": "fast-supplier",
"lead_time_days": 7,
"minimum_order_quantity": 50,
"cost_per_unit": 15.00,
"reliability_score": 0.98
},
{
"identifier": "budget-supplier",
"lead_time_days": 21,
"minimum_order_quantity": 200,
"cost_per_unit": 11.50,
"reliability_score": 0.90
}
]
}
}'
$response = Http::withToken('YOUR_API_KEY')
->post('https://forecastapi.com/v2/inventory-planning', [
'identifier' => 'SKU-12345',
'frequency' => 'M',
'periods' => 6,
'data' => [
['date' => '2024-01-01', 'value' => 100],
['date' => '2024-02-01', 'value' => 120],
['date' => '2024-03-01', 'value' => 95],
['date' => '2024-04-01', 'value' => 130],
['date' => '2024-05-01', 'value' => 110],
['date' => '2024-06-01', 'value' => 125],
],
'inventory_settings' => [
'current_stock' => 250,
'minimum_stock' => 50,
'service_level' => 0.95,
'suppliers' => [
[
'identifier' => 'fast-supplier',
'lead_time_days' => 7,
'minimum_order_quantity' => 50,
'cost_per_unit' => 15.00,
'reliability_score' => 0.98,
],
[
'identifier' => 'budget-supplier',
'lead_time_days' => 21,
'minimum_order_quantity' => 200,
'cost_per_unit' => 11.50,
'reliability_score' => 0.90,
],
],
],
]);
$planning = $response->json();
echo "Reorder Point: " . $planning['result']['reorder_point'];
echo "Safety Stock: " . $planning['result']['safety_stock'];
import requests
response = requests.post(
'https://forecastapi.com/v2/inventory-planning',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={
'identifier': 'SKU-12345',
'frequency': 'M',
'periods': 6,
'data': [
{'date': '2024-01-01', 'value': 100},
{'date': '2024-02-01', 'value': 120},
{'date': '2024-03-01', 'value': 95},
{'date': '2024-04-01', 'value': 130},
{'date': '2024-05-01', 'value': 110},
{'date': '2024-06-01', 'value': 125},
],
'inventory_settings': {
'current_stock': 250,
'minimum_stock': 50,
'service_level': 0.95,
'suppliers': [
{
'identifier': 'fast-supplier',
'lead_time_days': 7,
'minimum_order_quantity': 50,
'cost_per_unit': 15.00,
'reliability_score': 0.98
},
{
'identifier': 'budget-supplier',
'lead_time_days': 21,
'minimum_order_quantity': 200,
'cost_per_unit': 11.50,
'reliability_score': 0.90
}
]
}
}
)
planning = response.json()
print(f"Reorder Point: {planning['result']['reorder_point']}")
print(f"Safety Stock: {planning['result']['safety_stock']}")
const response = await fetch('https://forecastapi.com/v2/inventory-planning', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
identifier: 'SKU-12345',
frequency: 'M',
periods: 6,
data: [
{ date: '2024-01-01', value: 100 },
{ date: '2024-02-01', value: 120 },
{ date: '2024-03-01', value: 95 },
{ date: '2024-04-01', value: 130 },
{ date: '2024-05-01', value: 110 },
{ date: '2024-06-01', value: 125 },
],
inventory_settings: {
current_stock: 250,
minimum_stock: 50,
service_level: 0.95,
suppliers: [
{
identifier: 'fast-supplier',
lead_time_days: 7,
minimum_order_quantity: 50,
cost_per_unit: 15.00,
reliability_score: 0.98
},
{
identifier: 'budget-supplier',
lead_time_days: 21,
minimum_order_quantity: 200,
cost_per_unit: 11.50,
reliability_score: 0.90
}
]
}
})
});
const planning = await response.json();
console.log('Reorder Point:', planning.result.reorder_point);
console.log('Safety Stock:', planning.result.safety_stock);
Example Response
{
"result": {
"identifier": "SKU-12345",
"current_stock": 250,
"minimum_stock": 50,
"reorder_point": 145,
"safety_stock": 62,
"suppliers": [
{
"supplier": "fast-supplier",
"order_quantity": 100,
"total_cost": 1500.00,
"cost_per_unit": 15.00,
"expected_delivery": "2024-07-08",
"lead_time_days": 7,
"lead_time_demand": 28.5,
"safety_stock": 45,
"reorder_point": 95,
"reason": "$15.00 per unit, fast delivery, high reliability (98%)"
},
{
"supplier": "budget-supplier",
"order_quantity": 200,
"total_cost": 2300.00,
"cost_per_unit": 11.50,
"expected_delivery": "2024-07-22",
"lead_time_days": 21,
"lead_time_demand": 85.5,
"safety_stock": 72,
"reorder_point": 185,
"reason": "$11.50 per unit, longer lead time, moderate reliability (90%)"
}
],
"stock_analysis": {
"days_of_coverage": 62,
"stockout_risk": 0.08,
"next_order_date": "2024-07-15",
"daily_demand_rate": 4.03,
"stock_status": "adequate"
}
},
"meta": {
"timing": {
"validation": 10.2,
"planning": 156.8,
"total": 167.0
}
}
}
Traffic Forecasting
Predict traffic patterns. ForecastAPI returns infrastructure scaling recommendations, capacity analysis, and cost optimization.
curl -X POST https://forecastapi.com/v2/traffic-forecasting \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"identifier": "api-endpoint-users",
"frequency": "H",
"periods": 24,
"data": [
{"date": "2024-06-01 00:00:00", "value": 1200},
{"date": "2024-06-01 01:00:00", "value": 850},
{"date": "2024-06-01 02:00:00", "value": 620},
{"date": "2024-06-01 03:00:00", "value": 480},
{"date": "2024-06-01 04:00:00", "value": 520},
{"date": "2024-06-01 05:00:00", "value": 780},
{"date": "2024-06-01 06:00:00", "value": 1150},
{"date": "2024-06-01 07:00:00", "value": 1680}
],
"traffic_settings": {
"current_capacity": 2000,
"baseline_traffic": 1000,
"scaling_buffer": 0.2,
"scale_up_threshold": 0.8,
"scale_down_threshold": 0.3,
"enable_auto_scaling": false,
"cost_per_unit": 0.01,
"fixed_cost_per_capacity": 0.10
}
}'
$response = Http::withToken('YOUR_API_KEY')
->post('https://forecastapi.com/v2/traffic-forecasting', [
'identifier' => 'api-endpoint-users',
'frequency' => 'H',
'periods' => 24,
'data' => [
['date' => '2024-06-01 00:00:00', 'value' => 1200],
['date' => '2024-06-01 01:00:00', 'value' => 850],
['date' => '2024-06-01 02:00:00', 'value' => 620],
['date' => '2024-06-01 03:00:00', 'value' => 480],
['date' => '2024-06-01 04:00:00', 'value' => 520],
['date' => '2024-06-01 05:00:00', 'value' => 780],
['date' => '2024-06-01 06:00:00', 'value' => 1150],
['date' => '2024-06-01 07:00:00', 'value' => 1680],
],
'traffic_settings' => [
'current_capacity' => 2000,
'baseline_traffic' => 1000,
'scaling_buffer' => 0.2,
'scale_up_threshold' => 0.8,
'scale_down_threshold' => 0.3,
'enable_auto_scaling' => false,
'cost_per_unit' => 0.01,
'fixed_cost_per_capacity' => 0.10,
],
]);
$traffic = $response->json();
$recommendations = $traffic['result']['scaling_recommendations']['recommendations'];
foreach ($recommendations as $rec) {
echo "{$rec['action']}: {$rec['reason']}\n";
}
import requests
response = requests.post(
'https://forecastapi.com/v2/traffic-forecasting',
headers={'Authorization': 'Bearer YOUR_API_KEY'},
json={
'identifier': 'api-endpoint-users',
'frequency': 'H',
'periods': 24,
'data': [
{'date': '2024-06-01 00:00:00', 'value': 1200},
{'date': '2024-06-01 01:00:00', 'value': 850},
{'date': '2024-06-01 02:00:00', 'value': 620},
{'date': '2024-06-01 03:00:00', 'value': 480},
{'date': '2024-06-01 04:00:00', 'value': 520},
{'date': '2024-06-01 05:00:00', 'value': 780},
{'date': '2024-06-01 06:00:00', 'value': 1150},
{'date': '2024-06-01 07:00:00', 'value': 1680},
],
'traffic_settings': {
'current_capacity': 2000,
'baseline_traffic': 1000,
'scaling_buffer': 0.2,
'scale_up_threshold': 0.8,
'scale_down_threshold': 0.3,
'enable_auto_scaling': False,
'cost_per_unit': 0.01,
'fixed_cost_per_capacity': 0.10
}
}
)
traffic = response.json()
for rec in traffic['result']['scaling_recommendations']['recommendations']:
print(f"{rec['action']}: {rec['reason']}")
const response = await fetch('https://forecastapi.com/v2/traffic-forecasting', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
identifier: 'api-endpoint-users',
frequency: 'H',
periods: 24,
data: [
{ date: '2024-06-01 00:00:00', value: 1200 },
{ date: '2024-06-01 01:00:00', value: 850 },
{ date: '2024-06-01 02:00:00', value: 620 },
{ date: '2024-06-01 03:00:00', value: 480 },
{ date: '2024-06-01 04:00:00', value: 520 },
{ date: '2024-06-01 05:00:00', value: 780 },
{ date: '2024-06-01 06:00:00', value: 1150 },
{ date: '2024-06-01 07:00:00', value: 1680 },
],
traffic_settings: {
current_capacity: 2000,
baseline_traffic: 1000,
scaling_buffer: 0.2,
scale_up_threshold: 0.8,
scale_down_threshold: 0.3,
enable_auto_scaling: false,
cost_per_unit: 0.01,
fixed_cost_per_capacity: 0.10
}
})
});
const traffic = await response.json();
traffic.result.scaling_recommendations.recommendations.forEach(rec => {
console.log(`${rec.action}: ${rec.reason}`);
});
Example Response
{
"result": {
"metric": "api-endpoint-users",
"current_capacity": 2000,
"baseline_traffic": 1000,
"scaling_recommendations": {
"peak_traffic": 1920,
"average_traffic": 1245,
"current_utilization": 96.0,
"recommendations": [
{
"action": "scale_up",
"current_capacity": 2000,
"recommended_capacity": 2500,
"scaling_factor": 1.25,
"reason": "Peak traffic (1920) will exceed 80% of current capacity (2000)",
"urgency": "high",
"estimated_time_to_scale": 10
}
]
},
"capacity_analysis": {
"current_capacity": 2000,
"over_capacity_periods": 0,
"critical_periods": 4,
"capacity_efficiency": 72.5
},
"traffic_alerts": {
"total_alerts": 1,
"high_severity": 0,
"medium_severity": 1,
"alerts": [
{
"type": "traffic_spike",
"severity": "medium",
"period": 8,
"predicted_traffic": 1920,
"increase_factor": 1.92,
"message": "Traffic spike predicted: 1920 (1.9x baseline) at 08:00"
}
]
},
"cost_optimization": {
"current_cost": 200.00,
"optimized_cost": 250.00,
"potential_savings": -50.00,
"savings_percentage": -25.0
}
},
"meta": {
"timing": {
"validation": 8.5,
"forecasting": 142.3,
"total": 150.8
}
}
}
Common Patterns
Always check for error responses and handle them.
if ($response->failed()) {
$error = $response->json();
Log::error('Forecast failed', [
'message' => $error['message'] ?? 'Unknown error',
'errors' => $error['errors'] ?? [],
]);
}
Use lower and upper bounds for risk-aware planning.
# Every period carries its own lower/upper bounds
for period in result['forecasts']:
conservative = period['lower'] # lower bound
optimistic = period['upper'] # upper bound
expected = period['forecast'] # most likely value
Process multiple items with batch requests.
// Send multiple forecasts in parallel
const results = await Promise.all(
items.map(item =>
fetch('/v2/forecast', {
method: 'POST',
body: JSON.stringify(item)
})
)
);
Match frequency to your data granularity.
H- Hourly dataD- Daily dataW- Weekly dataM- Monthly dataQ- Quarterly dataY- Yearly data