OptimaAI Logo

API Integration

How the frontend communicates with the FastAPI backend

API Integration

The frontend communicates with the FastAPI backend via standard HTTP requests. All API calls use the base URL set in NEXT_PUBLIC_API_URL.

Base Configuration

// lib/api.js
const BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
 
export async function apiFetch(path, options = {}) {
  const res = await fetch(`${BASE}${path}`, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  })
  if (!res.ok) throw new Error(`API error ${res.status}`)
  return res.json()
}

Usage Examples

Fetch KPIs

const kpis = await apiFetch('/api/v1/kpis')
// kpis.revenue_model.MAPE_pct
// kpis.churn_model.ROC_AUC

Predict Revenue

const result = await apiFetch('/api/v1/predict/revenue', {
  method: 'POST',
  body: JSON.stringify({
    features: {
      quantity_sold: 3,
      price: 299.0,
      discount_percent: 10,
      seasonal_index: 1.0,
      gross_margin_pct: 0.45,
      month: 6,
      quarter: 2,
    }
  })
})
// result.prediction → 807.30

Get Recommendation

const rec = await apiFetch('/api/v1/recommend', {
  method: 'POST',
  body: JSON.stringify({ role: 'Sales Manager' })
})
// rec.recommendation → markdown string

Upload a Dataset

const form = new FormData()
form.append('file', fileInput.files[0])
form.append('category', 'sales')
 
const res = await fetch(`${BASE}/api/v1/datasets/upload`, {
  method: 'POST',
  body: form   // No Content-Type header — browser sets multipart boundary
})
const data = await res.json()

Query Knowledge Base

const answer = await apiFetch('/api/v1/kb/query', {
  method: 'POST',
  body: JSON.stringify({ query: 'What is our average order value?' })
})
// answer.answer → LLM-generated text
// answer.sources → array of relevant document chunks

Error Handling

All API calls should be wrapped in try/catch. The backend returns standard HTTP status codes:

CodeMeaning
200Success
400Bad request (e.g. unsupported file type)
404Resource not found (e.g. no models trained yet)
500Server error (e.g. model not loaded)
502LLM API error (e.g. OpenRouter unreachable)

On this page