Skip to content

LesterCerioli/FastBI-App-SDK-Go

Repository files navigation

FastBI App SDK for Go

A Go client SDK for the FastBI API — a Business Intelligence platform with KPI management, AI-powered analytics, MCP orchestration, real-time streaming, and multi-format report export.

Note on Authentication: The FastBI API currently uses short-lived JWT tokens (10-minute TTL) issued via client_id + secret. OAuth 2.0 support will be added in a future SDK release.

Requirements

  • Go 1.26 or later
  • A running FastBI API instance

Installation

go get github.com/fastbi/fastbi-app-sdk

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    fastbi "github.com/fastbi/fastbi-app-sdk"
)

func main() {
    client := fastbi.New(fastbi.Config{
        BaseURL:  "https://your-fastbi-instance.com/api/v1",
        ClientID: "your-client-id",
        Secret:   "your-secret",
    })

    ctx := context.Background()

    // The client automatically obtains and refreshes tokens.
    kpi, err := client.KPIs.Get(ctx, "REVENUE_GROWTH", "Acme Corp")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Current value: %.2f / Target: %.2f\n", kpi.CurrentValue, kpi.TargetValue)
}

Configuration

Field Type Default Description
BaseURL string http://localhost:3050/api/v1 FastBI API root URL
ClientID string API client identifier
Secret string API client secret
HTTPClient *http.Client default client (30s timeout) Override for custom TLS, proxy, or testing
Timeout time.Duration 30s Per-request timeout (does not apply to SSE streams)

Authentication

Tokens are obtained automatically before the first authenticated request and refreshed 30 seconds before expiry. You can also manage tokens explicitly:

// Explicit token generation
tok, err := client.Auth.GenerateToken(ctx, "my_client", "my_secret")
fmt.Println("Expires at:", tok.ExpiresAt)

// Token validation
result, err := client.Auth.ValidateToken(ctx, someToken)
fmt.Println("Status:", result.Status) // "AUTHORIZED"

Services

KPIs — client.KPIs

// Create
kpi, err := client.KPIs.Create(ctx, &fastbi.CreateKPIRequest{
    Code:             "NET_MARGIN",
    Name:             "Net Profit Margin",
    OrganizationName: "Acme Corp",
    Category:         "financial",
    CurrentValue:     18.5,
    TargetValue:      22.0,
    Unit:             "%",
    ReportingPeriod:  "quarterly",
})

// Read
kpi, err := client.KPIs.Get(ctx, "NET_MARGIN", "Acme Corp")

// Update
updated, err := client.KPIs.Update(ctx, "NET_MARGIN", &fastbi.UpdateKPIRequest{
    OrganizationName: "Acme Corp",
    CurrentValue:     floatPtr(19.1),
})

// Delete
err := client.KPIs.Delete(ctx, "NET_MARGIN", "Acme Corp")

// List with filters
list, err := client.KPIs.List(ctx, "Acme Corp", &fastbi.KPIListFilter{
    Category: "financial",
    Limit:    20,
    OrderBy:  "created_at",
    OrderDir: "DESC",
})

// History
history, err := client.KPIs.History(ctx, "NET_MARGIN", "Acme Corp", 50, 0)

Analytics — client.Analytics

// Revenue insights with optional date/category/region filters
insights, err := client.Analytics.RevenueInsights(ctx, &fastbi.RevenueInsightsFilter{
    StartDate: "2025-01-01",
    EndDate:   "2025-12-31",
    Region:    "southeast",
})

// Revenue forecast
forecast, err := client.Analytics.ForecastRevenue(ctx, &fastbi.ForecastRequest{
    OrganizationName:       "Acme Corp",
    MonthsAhead:            6,
    IncludeExternalFactors: true,
})

// Product mix optimization
mix, err := client.Analytics.OptimizeProductMix(ctx, &fastbi.ProductMixRequest{
    OrganizationName: "Acme Corp",
})

Dashboards — client.Dashboards

// Create a global template
tmpl, err := client.Dashboards.CreateTemplate(ctx, &fastbi.CreateDashboardTemplateRequest{
    Name:        "Executive Overview",
    Description: "C-level KPI dashboard",
})

// Create an organization dashboard from the template
dash, err := client.Dashboards.Create(ctx, &fastbi.CreateDashboardRequest{
    Name:             "Q4 Executive Dashboard",
    OrganizationName: "Acme Corp",
    TemplateID:       tmpl.ID,
})

// Add a widget
widget, err := client.Dashboards.AddWidget(ctx, dash.Slug, &fastbi.AddWidgetRequest{
    Title:  "Revenue Trend",
    Type:   "line_chart",
    Config: map[string]any{"metric": "REVENUE_GROWTH", "period": "12m"},
})

Database Connections — client.Connections

// Register a new database connection
_, err := client.Connections.Register(ctx, &fastbi.RegisterConnectionRequest{
    OrganizationName: "Acme Corp",
    ConnectionName:   "prod-db",
    Host:             "db.example.com",
    Port:             5432,
    DatabaseName:     "analytics",
    Username:         "reader",
    Password:         "s3cr3t",
    DBType:           fastbi.DBTypePostgres,
    SSLMode:          "require",
})

// Execute a query
rows, err := client.Connections.ExecuteQuery(ctx, "prod-db", &fastbi.ExecuteQueryRequest{
    OrganizationName: "Acme Corp",
    Query:            "SELECT product, SUM(revenue) FROM sales GROUP BY product LIMIT 10",
    UseCache:         true,
    CacheTTLSeconds:  300,
})

Reports — client.Reports

// Create and advance a report run through its lifecycle
run, err := client.Reports.CreateRun(ctx, &fastbi.CreateRunRequest{
    TemplateName:     "monthly-financial",
    OrganizationName: "Acme Corp",
})

_, err = client.Reports.TransitionRun(ctx, run.CreatedAt, &fastbi.TransitionRunRequest{
    TargetStage: "in_review",
})

_, err = client.Reports.ApproveReview(ctx, run.CreatedAt, &fastbi.ApproveReviewRequest{
    ApprovedBy: "cfo@acme.com",
})

// Schedule a recurring report
schedule, err := client.Reports.CreateSchedule(ctx, &fastbi.CreateScheduleRequest{
    Name:         "monthly-close",
    TemplateName: "monthly-financial",
    CronExpr:     "0 6 1 * *", // 06:00 on the 1st of every month
})

// Retrieve AI-generated narrative for a run
narrative, err := client.Reports.GenerateNarrative(ctx, &fastbi.GenerateNarrativeRequest{
    RunID:            run.ID,
    OrganizationName: "Acme Corp",
    Language:         "en",
})

Exports — client.Exports

// Export to Excel
_, err := client.Exports.ExportExcel(ctx, runID, &fastbi.ExcelExportRequest{
    OrganizationName: "Acme Corp",
})

// Download URLs (add Bearer token to request header yourself)
excelURL := client.Exports.DownloadExcelURL(runID)
csvURL   := client.Exports.DownloadCSVURL(createdAt)
pdfURL   := client.Exports.DownloadPDFURL(runID)

// Render a brand-aware PDF
_, err = client.Exports.RenderPDF(ctx, runID, &fastbi.PDFRenderRequest{
    OrganizationName: "Acme Corp",
    BrandName:        "acme-brand",
})

Revenue Reports — client.Revenue

exec,   err := client.Revenue.ExecutiveReport(ctx)
region, err := client.Revenue.RegionalReport(ctx, "southeast")
bu,     err := client.Revenue.BusinessUnitReport(ctx, "retail")
ts,     err := client.Revenue.TimeSeries(ctx, "Acme Corp", "2025-01-01", "2025-12-31")

Gross Margin — client.GrossMargin

overall,  err := client.GrossMargin.Overall(ctx)
byProd,   err := client.GrossMargin.ByProduct(ctx)
byTier,   err := client.GrossMargin.ByCustomerTier(ctx)
forecast, err := client.GrossMargin.Forecast(ctx)

Sales AI — client.Sales

// Natural language question
answer, err := client.Sales.Ask(ctx, &fastbi.AskQuestionRequest{
    Question:         "What are our top 3 revenue drivers this quarter?",
    OrganizationName: "Acme Corp",
})

// Trend prediction
trend, err := client.Sales.PredictTrend(ctx, &fastbi.PredictSalesTrendRequest{
    OrganizationName: "Acme Corp",
    MonthsAhead:      3,
    Region:           "southeast",
})

Machine Learning — client.ML

// Train a linear regression model
_, err := client.ML.TrainLinearRegression(ctx, &fastbi.TrainLinearRegressionRequest{
    Features: [][]float64{{1, 2}, {3, 4}, {5, 6}},
    Labels:   []float64{10, 20, 30},
})

// Single prediction
pred, err := client.ML.PredictLinearRegression(ctx, &fastbi.PredictLinearRegressionRequest{
    Features: []float64{7, 8},
})

Accounting — client.Accounting

// Create a tax workflow template
tmpl, err := client.Accounting.CreateTemplate(ctx, &fastbi.CreateAccountingTemplateRequest{
    Name:      "ICMS Monthly",
    Category:  "tax",
    Structure: map[string]any{"steps": []string{"collect", "calculate", "file"}},
})

// Instantiate a workflow for a fiscal year
wf, err := client.Accounting.CreateWorkflowFromTemplate(ctx, &fastbi.CreateWorkflowFromTemplateRequest{
    TemplateName:     "ICMS Monthly",
    TemplateCategory: "tax",
    FiscalYear:       2025,
})

// Get the compliance calendar
calendar, err := client.Accounting.GetComplianceCalendar(ctx, "2025")

AI Analysis — client.AI

Pure statistics and RAG — no external LLM calls.

// Customer intelligence
atRisk,   err := client.AI.IdentifyAtRiskCustomers(ctx)
segments, err := client.AI.GetCustomerSegments(ctx)

// Financial analysis
cogs,    err := client.AI.GetCOGSBreakdown(ctx)
leaks,   err := client.AI.GetMarginLeaks(ctx)

// KPI intelligence
devs,  err := client.AI.GetKPIDeviations(ctx)
corr,  err := client.AI.CorrelateKPIs(ctx)

// Product portfolio
bcg,   err := client.AI.GetBCGMatrix(ctx)
under, err := client.AI.GetUnderperformingProducts(ctx)

// Organization health
score, err := client.AI.GetOrganizationHealthScore(ctx)

// Automotive (fleet management)
fleet,  err := client.AI.GetFleetUtilization(ctx)
overdue, err := client.AI.GetOverdueRentals(ctx)

MCP Orchestration — client.MCP

// Full analysis across all dimensions
result, err := client.MCP.FullAnalysis(ctx, &fastbi.MCPAnalyticsRequest{
    OrganizationName: "Acme Corp",
    StartDate:        "2025-01-01",
    EndDate:          "2025-12-31",
    MaxSkills:        6,
})

// Route a natural language query to the best skill
route, err := client.MCP.RouteQuery(ctx, &fastbi.MCPRouteQueryRequest{
    Query: "which KPIs are below target this quarter?",
    TopK:  5,
})

// Execute a high-level goal
goal, err := client.MCP.ExecuteGoal(ctx, &fastbi.MCPExecuteGoalRequest{
    OrganizationName: "Acme Corp",
    Goal:             "analyze_kpis",
    StartDate:        "2025-01-01",
    EndDate:          "2025-12-31",
})

// Generate an AI narrative
narrative, err := client.MCP.GenerateNarrative(ctx, &fastbi.MCPNarrativeRequest{
    OrganizationName: "Acme Corp",
    ReportID:         "rpt-abc123",
    Language:         "en",
})

Real-time Streaming — client.Stream

Streaming methods return a <-chan SSEEvent that is closed when the context is cancelled or the server disconnects. Use context.WithTimeout or context.WithCancel to control lifetime.

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Live KPI feed
events, err := client.Stream.KPIs(ctx)
for ev := range events {
    fmt.Printf("[%s] %s\n", ev.Event, ev.Data)
}

// Anomaly monitoring for a specific organization
events, err = client.Stream.AnomaliesByOrg(ctx, "Acme Corp")

// Stream a specific KPI
events, err = client.Stream.KPIByCode(ctx, "REVENUE_GROWTH")

// Streaming pipeline
_, err = client.Stream.CreatePipeline(ctx, &fastbi.CreatePipelineRequest{
    Name:             "revenue-agg",
    OrganizationName: "Acme Corp",
})
pipelineEvents, err := client.Stream.StreamPipeline(ctx, "revenue-agg")

// Real-time report generation
reportEvents, err := client.Stream.GenerateReport(ctx, &fastbi.GenerateReportStreamRequest{
    TemplateName:     "monthly-financial",
    OrganizationName: "Acme Corp",
})

Organizations — client.Organizations

brand, err := client.Organizations.CreateBrandConfig(ctx, &fastbi.CreateBrandConfigRequest{
    OrganizationName: "Acme Corp",
    PrimaryColor:     "#0056b3",
    LogoURL:          "https://cdn.acme.com/logo.svg",
})

_, err = client.Organizations.UpdateBrandConfig(ctx, "Acme Corp", &fastbi.UpdateBrandConfigRequest{
    PrimaryColor: strPtr("#003d8c"),
})

Error Handling

Network errors are wrapped Go errors. HTTP errors from the API surface as *fastbi.APIError:

kpi, err := client.KPIs.Get(ctx, "UNKNOWN", "Acme Corp")
if err != nil {
    var apiErr *fastbi.APIError
    if errors.As(err, &apiErr) {
        fmt.Println("HTTP status:", apiErr.StatusCode)
        fmt.Println("Body:", apiErr.Body)
    }
    log.Fatal(err)
}

Examples

All examples read credentials from environment variables:

export FASTBI_BASE_URL=http://localhost:3050/api/v1
export FASTBI_CLIENT_ID=your_client
export FASTBI_SECRET=your_secret
Directory What it covers
examples/quickstart Auth, KPI CRUD, Sales AI, MCP full analysis, SSE streaming — good first stop
examples/kpi-lifecycle Full KPI lifecycle: create → read → update → list with filters → history → delete
examples/dashboard-builder Brand config → global template → org dashboard → add/update/delete widgets
examples/report-pipeline Report run lifecycle: create → stage transitions → review → narrative → approve → Excel/CSV/PDF export → schedule
examples/real-time-monitoring Concurrent SSE streams: KPI feed, anomaly alerts, aggregation pipeline, metrics — all in parallel goroutines
examples/mcp-analytics MCP orchestration: query routing, domain analytics, anomaly detection, decline diagnosis, narrative generation, goal execution
examples/database-connections Register DB connections, test, discover schema, execute/validate/estimate queries, batch execution, saved queries, cache management
examples/ai-intelligence All AI analysis endpoints: customers, financial, KPIs, products, intelligence, workflows, tasks, automotive, feedback, revenue, gross margin
examples/accounting-workflow Accounting templates by tax regime → fiscal year workflows → compliance calendar → AI workflow analytics
examples/ml-regression Generate synthetic training data → train linear regression → inspect model → single + 6-month batch forecast
examples/sales-nlp NLP Q&A, semantic RAG context, table discovery, trend predictions, AI insights, MCP-routed action queries

Run any example with:

go run ./examples/<name>/main.go

Roadmap

  • OAuth 2.0 support (client credentials flow)
  • Automatic retry with exponential back-off
  • Request/response logging middleware hook
  • Typed response structs for all endpoints (currently map[string]any where the schema is not yet stable)

License

Apache 2.0 — see LICENSE.

About

SDK from FastBI App API with Go 1.26

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages