MyBusiness Logousiness - BI API Documentation

Access your data warehouse with powerful REST APIs

Version 1.0 REST API JWT Auth

Overview

The Business Intelligence API provides secure, RESTful access to your data warehouse views. All endpoints require authentication with SuperAdmin or CompanyAdmin role.

Base URL: /api/BusinessIntelligence
Authentication: Bearer Token (JWT)
Content Type: application/json

API Categories

Key Features

Quick Links

Getting Started

Step 1: Obtain Authentication Token

Before making any API calls, you need to obtain a JWT token:

POST /api/Account/GetToken
Content-Type: application/json

{
  "username": "your-username",
  "password": "your-password"
}
Success Response: You'll receive an access_token that you'll use in subsequent requests.

Step 2: Make Your First API Call

Use the token in the Authorization header:

GET /api/BusinessIntelligence/Categories
Authorization: Bearer {your-access-token}
Content-Type: application/json

Step 3: Filter Transaction Data

For transaction endpoints, use POST with filters:

POST /api/BusinessIntelligence/Sellings
Authorization: Bearer {your-access-token}
Content-Type: application/json

{
  "dateFilter": {
    "start": "2024-01-01T00:00:00Z",
    "end": "2024-01-31T23:59:59Z"
  },
  "stores": ["STORE001", "STORE002"]
}

Authentication Flow

  1. Get Token: Call /api/Account/GetToken with credentials
  2. Store Token: Save the access_token and refresh_token
  3. Use Token: Include as Bearer token in Authorization header
  4. Refresh: When token expires, use refresh_token to get new token

Common Use Cases

1. Get All Master Data

// Get categories, products, stores, units
GET /api/BusinessIntelligence/Categories
GET /api/BusinessIntelligence/Products
GET /api/BusinessIntelligence/Stores
GET /api/BusinessIntelligence/Units

2. Query Sales for a Period

POST /api/BusinessIntelligence/Sellings
{
  "dateFilter": {
    "start": "2024-01-01T00:00:00Z",
    "end": "2024-01-31T23:59:59Z"
  }
}

3. Analyze Consumption Variance

POST /api/BusinessIntelligence/Consumptions
{
  "dateFilter": {
    "start": "2024-01-01T00:00:00Z",
    "end": "2024-01-31T23:59:59Z"
  },
  "stores": ["STORE001"]
}

Best Practices

Important: Never expose your authentication credentials in client-side code. Always use secure backend services for API authentication.

Code Examples

JavaScript / Fetch API

// 1. Get authentication token
async function getToken(username, password) {
  const response = await fetch('/api/Account/GetToken', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  });

  if (!response.ok) {
    throw new Error('Authentication failed');
  }

  const data = await response.json();
  return data.access_token;
}

// 2. Get categories
async function getCategories(token) {
  const response = await fetch('/api/BusinessIntelligence/Categories', {
    headers: { 
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  });

  return await response.json();
}

// 3. Get sellings for a date range
async function getSellings(token, startDate, endDate, stores) {
  const response = await fetch('/api/BusinessIntelligence/Sellings', {
    method: 'POST',
    headers: { 
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      dateFilter: {
        start: startDate,
        end: endDate
      },
      stores: stores
    })
  });

  return await response.json();
}

// Usage
const token = await getToken('user@example.com', 'password123');
const categories = await getCategories(token);
const sellings = await getSellings(
  token, 
  '2024-01-01T00:00:00Z', 
  '2024-01-31T23:59:59Z',
  ['STORE001']
);

console.log('Categories:', categories);
console.log('Sellings:', sellings);

C# / HttpClient

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class BiApiClient
{
    private readonly HttpClient _client;
    private string _token;

    public BiApiClient(string baseUrl)
    {
        _client = new HttpClient { BaseAddress = new Uri(baseUrl) };
    }

    // 1. Authenticate
    public async Task<bool> AuthenticateAsync(string username, string password)
    {
        var request = new { username, password };
        var response = await _client.PostAsJsonAsync("/api/Account/GetToken", request);

        if (!response.IsSuccessStatusCode)
            return false;

        var result = await response.Content.ReadAsAsync<TokenResponse>();
        _token = result.access_token;

        _client.DefaultRequestHeaders.Authorization = 
            new AuthenticationHeaderValue("Bearer", _token);

        return true;
    }

    // 2. Get categories
    public async Task<List<BICategoryDTO>> GetCategoriesAsync()
    {
        var response = await _client.GetAsync("/api/BusinessIntelligence/Categories");
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsAsync<List<BICategoryDTO>>();
    }

    // 3. Get purchases
    public async Task<List<BIPurchaseDTO>> GetPurchasesAsync(
        DateTime startDate, 
        DateTime endDate, 
        List<string> stores = null)
    {
        var filter = new DateAndStoreFilter
        {
            DateFilter = new DateFilter
            {
                Start = startDate,
                End = endDate
            },
            Stores = stores
        };

        var response = await _client.PostAsJsonAsync(
            "/api/BusinessIntelligence/Purchases", 
            filter
        );
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsAsync<List<BIPurchaseDTO>>();
    }
}

// Usage
var client = new BiApiClient("https://your-api-host.com");

if (await client.AuthenticateAsync("user@example.com", "password123"))
{
    var categories = await client.GetCategoriesAsync();
    var purchases = await client.GetPurchasesAsync(
        new DateTime(2024, 1, 1),
        new DateTime(2024, 1, 31),
        new List<string> { "STORE001" }
    );

    Console.WriteLine($"Found {categories.Count} categories");
    Console.WriteLine($"Found {purchases.Count} purchases");
}

Python / Requests

import requests
from datetime import datetime
from typing import List, Dict, Optional

class BiApiClient:
    def __init__(self, base_url: str):
        self.base_url = base_url
        self.token = None
        self.session = requests.Session()

    # 1. Authenticate
    def authenticate(self, username: str, password: str) -> bool:
        url = f"{self.base_url}/api/Account/GetToken"
        response = self.session.post(url, json={
            "username": username,
            "password": password
        })

        if response.status_code != 200:
            return False

        data = response.json()
        self.token = data['access_token']
        self.session.headers.update({
            'Authorization': f'Bearer {self.token}'
        })

        return True

    # 2. Get categories
    def get_categories(self) -> List[Dict]:
        url = f"{self.base_url}/api/BusinessIntelligence/Categories"
        response = self.session.get(url)
        response.raise_for_status()
        return response.json()

    # 3. Get sellings
    def get_sellings(
        self, 
        start_date: str, 
        end_date: str, 
        stores: Optional[List[str]] = None
    ) -> List[Dict]:
        url = f"{self.base_url}/api/BusinessIntelligence/Sellings"

        payload = {
            "dateFilter": {
                "start": start_date,
                "end": end_date
            }
        }

        if stores:
            payload["stores"] = stores

        response = self.session.post(url, json=payload)
        response.raise_for_status()
        return response.json()

# Usage
client = BiApiClient("https://your-api-host.com")

if client.authenticate("user@example.com", "password123"):
    categories = client.get_categories()
    sellings = client.get_sellings(
        "2024-01-01T00:00:00Z",
        "2024-01-31T23:59:59Z",
        ["STORE001"]
    )

    print(f"Found {len(categories)} categories")
    print(f"Found {len(sellings)} sellings")

cURL

# 1. Get token
curl -X POST https://your-api-host.com/api/Account/GetToken \
  -H "Content-Type: application/json" \
  -d '{
    "username": "user@example.com",
    "password": "password123"
  }'

# Response will contain access_token

# 2. Get categories
curl -X GET https://your-api-host.com/api/BusinessIntelligence/Categories \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json"

# 3. Get purchases
curl -X POST https://your-api-host.com/api/BusinessIntelligence/Purchases \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "dateFilter": {
      "start": "2024-01-01T00:00:00Z",
      "end": "2024-01-31T23:59:59Z"
    },
    "stores": ["STORE001"]
  }'

Error Handling Example (JavaScript)

async function makeApiCall(url, options = {}) {
  try {
    const response = await fetch(url, options);

    if (response.status === 401) {
      // Token expired or invalid - re-authenticate
      console.log('Authentication required');
      // Trigger re-authentication flow
      return null;
    }

    if (response.status === 500) {
      // Server error - implement retry logic
      console.error('Server error - retrying...');
      await new Promise(resolve => setTimeout(resolve, 2000));
      return makeApiCall(url, options); // Retry
    }

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || 'API call failed');
    }

    return await response.json();

  } catch (error) {
    console.error('API Error:', error);
    throw error;
  }
}