Code Examples

Practical examples showing how to use the ForecastAPI endpoints in your applications. Copy and adapt these examples to get started quickly.

Before You Start

Replace YOUR_API_KEY with your actual API key. Get your key from the Dashboard.

Basic Forecasting

Generate time series forecasts with automatic method selection. Provide your historical data and ForecastAPI will choose the best forecasting algorithm 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}
    ]
  }'

Example Response

{
  "result": {
    "forecast_value": 182.5,
    "confidence_lower": 165.3,
    "confidence_upper": 199.7,
    "method_used": "exponential_smoothing",
    "forecast_dates": ["2024-07-01", "2024-08-01", "2024-09-01", "2024-10-01", "2024-11-01", "2024-12-01"],
    "forecast_values": [182.5, 189.2, 195.8, 202.1, 208.4, 214.6]
  },
  "meta": {
    "timing": {
      "validation": 8.2,
      "selection": 45.6,
      "forecasting": 72.1,
      "total": 125.9
    }
  }
}

Data Analysis

Analyze your time series data to understand patterns, trends, and recommended forecasting methods before generating a forecast.

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}
    ]
  }'

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 comprehensive inventory recommendations including reorder points, safety stock calculations, and supplier comparisons based on demand forecasting.

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
        }
      ]
    }
  }'

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 and get infrastructure scaling recommendations, capacity analysis, and cost optimization insights.

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
    }
  }'

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

Error Handling

Always check for error responses and handle them gracefully.

if ($response->failed()) {
    $error = $response->json();
    Log::error('Forecast failed', [
        'message' => $error['message'] ?? 'Unknown error',
        'errors' => $error['errors'] ?? [],
    ]);
}

Using Confidence Intervals

Use lower and upper bounds for risk-aware planning.

# Conservative estimate (lower bound)
safe_forecast = result['confidence_lower']

# Optimistic estimate (upper bound)
optimistic = result['confidence_upper']

# Most likely value
expected = result['forecast_value']

Batch Processing

Process multiple items efficiently 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)
    })
  )
);

Frequency Options

Match frequency to your data granularity.

  • H - Hourly data
  • D - Daily data
  • W - Weekly data
  • M - Monthly data
  • Q - Quarterly data
  • Y - Yearly data

Next Steps