Skip to content

Calculations API

The Calculations API provides endpoints for evaluating Excel formulas, batch processing, formula validation, and translating formulas to Python code.


Overview

CalcBridge's calculation engine supports:

  • Formula Evaluation: Execute Excel formulas with cell references
  • Batch Processing: Evaluate multiple formulas in a single request
  • Validation: Check formula syntax before evaluation
  • Translation: Convert Excel formulas to Python/pandas code
  • Function Library: Access 100+ supported Excel functions

Endpoints

Evaluate Formula

Evaluate a single Excel formula with optional context.

POST /api/v1/calculations/evaluate

Request Body

Field Type Required Description
formula string Yes Excel formula (must start with =)
context object No Cell references and their values
workbook_id string (UUID) No Workbook for cell reference resolution
sheet_name string No Sheet for cell reference resolution
options object No Evaluation options

Options Object

Field Type Default Description
precision integer 15 Decimal precision for results
error_handling string excel Error behavior: excel, null, throw
date_format string ISO8601 Date output format

Example Request

curl -X POST https://api.calcbridge.io/api/v1/calculations/evaluate \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "formula": "=SUM(A1:A3) + IF(B1>100, C1*0.1, C1*0.05)",
    "context": {
      "A1": 100,
      "A2": 200,
      "A3": 300,
      "B1": 150,
      "C1": 1000
    },
    "options": {
      "precision": 2
    }
  }'
import requests

response = requests.post(
    "https://api.calcbridge.io/api/v1/calculations/evaluate",
    headers={"Authorization": f"Bearer {token}"},
    json={
        "formula": "=SUM(A1:A3) + IF(B1>100, C1*0.1, C1*0.05)",
        "context": {
            "A1": 100,
            "A2": 200,
            "A3": 300,
            "B1": 150,
            "C1": 1000
        },
        "options": {"precision": 2}
    }
)
result = response.json()
print(f"Result: {result['value']}")  # Result: 700.00
const response = await fetch('https://api.calcbridge.io/api/v1/calculations/evaluate', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    formula: '=SUM(A1:A3) + IF(B1>100, C1*0.1, C1*0.05)',
    context: {
      A1: 100,
      A2: 200,
      A3: 300,
      B1: 150,
      C1: 1000
    },
    options: { precision: 2 }
  })
});
const result = await response.json();
console.log('Result:', result.value);  // Result: 700.00

Response

{
  "value": 700.00,
  "type": "number",
  "formula": "=SUM(A1:A3) + IF(B1>100, C1*0.1, C1*0.05)",
  "evaluated_at": "2026-01-25T10:30:00Z",
  "execution_time_ms": 12,
  "cell_references": ["A1", "A2", "A3", "B1", "C1"],
  "functions_used": ["SUM", "IF"]
}

Error Responses

Status Error Description
400 Invalid formula Formula syntax is incorrect
400 Unsupported function Formula contains unknown function
400 Missing context Required cell reference not provided
422 Evaluation error Formula could not be evaluated

Batch Evaluate

Evaluate multiple formulas in a single request.

POST /api/v1/calculations/batch

Request Body

Field Type Required Description
formulas array[FormulaRequest] Yes Array of formula requests
shared_context object No Context shared across all formulas
options object No Evaluation options

FormulaRequest Object

Field Type Required Description
id string No Custom identifier for result matching
formula string Yes Excel formula
context object No Formula-specific context (merged with shared)

Example Request

curl -X POST https://api.calcbridge.io/api/v1/calculations/batch \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "formulas": [
      {"id": "total", "formula": "=SUM(A1:A3)"},
      {"id": "average", "formula": "=AVERAGE(A1:A3)"},
      {"id": "max", "formula": "=MAX(A1:A3)"},
      {"id": "weighted", "formula": "=SUMPRODUCT(A1:A3, B1:B3)/SUM(B1:B3)"}
    ],
    "shared_context": {
      "A1": 100, "A2": 200, "A3": 300,
      "B1": 0.2, "B2": 0.3, "B3": 0.5
    }
  }'
import requests

response = requests.post(
    "https://api.calcbridge.io/api/v1/calculations/batch",
    headers={"Authorization": f"Bearer {token}"},
    json={
        "formulas": [
            {"id": "total", "formula": "=SUM(A1:A3)"},
            {"id": "average", "formula": "=AVERAGE(A1:A3)"},
            {"id": "max", "formula": "=MAX(A1:A3)"},
            {"id": "weighted", "formula": "=SUMPRODUCT(A1:A3, B1:B3)/SUM(B1:B3)"}
        ],
        "shared_context": {
            "A1": 100, "A2": 200, "A3": 300,
            "B1": 0.2, "B2": 0.3, "B3": 0.5
        }
    }
)
results = response.json()
for r in results["results"]:
    print(f"{r['id']}: {r['value']}")
const response = await fetch('https://api.calcbridge.io/api/v1/calculations/batch', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    formulas: [
      { id: 'total', formula: '=SUM(A1:A3)' },
      { id: 'average', formula: '=AVERAGE(A1:A3)' },
      { id: 'max', formula: '=MAX(A1:A3)' },
      { id: 'weighted', formula: '=SUMPRODUCT(A1:A3, B1:B3)/SUM(B1:B3)' }
    ],
    shared_context: {
      A1: 100, A2: 200, A3: 300,
      B1: 0.2, B2: 0.3, B3: 0.5
    }
  })
});
const results = await response.json();
results.results.forEach(r => console.log(`${r.id}: ${r.value}`));

Response

{
  "results": [
    {
      "id": "total",
      "formula": "=SUM(A1:A3)",
      "value": 600,
      "type": "number",
      "status": "success"
    },
    {
      "id": "average",
      "formula": "=AVERAGE(A1:A3)",
      "value": 200,
      "type": "number",
      "status": "success"
    },
    {
      "id": "max",
      "formula": "=MAX(A1:A3)",
      "value": 300,
      "type": "number",
      "status": "success"
    },
    {
      "id": "weighted",
      "formula": "=SUMPRODUCT(A1:A3, B1:B3)/SUM(B1:B3)",
      "value": 230,
      "type": "number",
      "status": "success"
    }
  ],
  "summary": {
    "total": 4,
    "succeeded": 4,
    "failed": 0
  },
  "execution_time_ms": 45
}

Validate Formula

Check formula syntax without evaluation.

POST /api/v1/calculations/validate

Request Body

Field Type Required Description
formula string Yes Formula to validate
strict boolean No Enable strict validation mode

Example Request

curl -X POST https://api.calcbridge.io/api/v1/calculations/validate \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "formula": "=VLOOKUP(A1, B:D, 3, FALSE)",
    "strict": true
  }'
import requests

response = requests.post(
    "https://api.calcbridge.io/api/v1/calculations/validate",
    headers={"Authorization": f"Bearer {token}"},
    json={
        "formula": "=VLOOKUP(A1, B:D, 3, FALSE)",
        "strict": True
    }
)
result = response.json()
if result["valid"]:
    print("Formula is valid")
else:
    print(f"Error: {result['error']}")
const response = await fetch('https://api.calcbridge.io/api/v1/calculations/validate', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    formula: '=VLOOKUP(A1, B:D, 3, FALSE)',
    strict: true
  })
});
const result = await response.json();
if (result.valid) {
  console.log('Formula is valid');
} else {
  console.log('Error:', result.error);
}

Response (Valid)

{
  "valid": true,
  "formula": "=VLOOKUP(A1, B:D, 3, FALSE)",
  "functions_used": ["VLOOKUP"],
  "cell_references": ["A1", "B:D"],
  "complexity_score": 2,
  "warnings": []
}

Response (Invalid)

{
  "valid": false,
  "formula": "=VLOOKUP(A1, B:D, 3",
  "error": "Unmatched parenthesis",
  "error_position": 20,
  "suggestions": [
    "Add closing parenthesis: =VLOOKUP(A1, B:D, 3)"
  ]
}

List Functions

Get all supported Excel functions.

GET /api/v1/calculations/functions

Query Parameters

Parameter Type Description
category string Filter by category (math, logical, lookup, etc.)
search string Search function names

Example Request

curl -X GET "https://api.calcbridge.io/api/v1/calculations/functions?category=lookup" \
  -H "Authorization: Bearer $TOKEN"
import requests

response = requests.get(
    "https://api.calcbridge.io/api/v1/calculations/functions",
    headers={"Authorization": f"Bearer {token}"},
    params={"category": "lookup"}
)
functions = response.json()
for func in functions["functions"]:
    print(f"{func['name']}: {func['description']}")
const response = await fetch(
  'https://api.calcbridge.io/api/v1/calculations/functions?category=lookup',
  { headers: { 'Authorization': `Bearer ${token}` } }
);
const functions = await response.json();
functions.functions.forEach(f => {
  console.log(`${f.name}: ${f.description}`);
});

Response

{
  "functions": [
    {
      "name": "VLOOKUP",
      "category": "lookup",
      "description": "Looks up a value in the first column of a range and returns a value in the same row from another column",
      "syntax": "VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])",
      "arguments": [
        {"name": "lookup_value", "type": "any", "required": true, "description": "The value to search for"},
        {"name": "table_array", "type": "range", "required": true, "description": "The range to search in"},
        {"name": "col_index_num", "type": "number", "required": true, "description": "Column number to return"},
        {"name": "range_lookup", "type": "boolean", "required": false, "description": "TRUE for approximate, FALSE for exact match"}
      ],
      "examples": [
        "=VLOOKUP(A1, B:D, 3, FALSE)",
        "=VLOOKUP(\"John\", A1:C100, 2, FALSE)"
      ]
    },
    {
      "name": "XLOOKUP",
      "category": "lookup",
      "description": "Searches a range or array for a match and returns the corresponding item from a second range or array",
      "syntax": "XLOOKUP(lookup_value, lookup_array, return_array, [if_not_found], [match_mode], [search_mode])",
      "arguments": [
        {"name": "lookup_value", "type": "any", "required": true, "description": "The value to search for"},
        {"name": "lookup_array", "type": "range", "required": true, "description": "The array to search"},
        {"name": "return_array", "type": "range", "required": true, "description": "The array to return from"},
        {"name": "if_not_found", "type": "any", "required": false, "description": "Value to return if not found"},
        {"name": "match_mode", "type": "number", "required": false, "description": "Match type: 0=exact, -1=exact or smaller, 1=exact or larger, 2=wildcard"},
        {"name": "search_mode", "type": "number", "required": false, "description": "Search direction"}
      ],
      "examples": [
        "=XLOOKUP(A1, B:B, C:C)",
        "=XLOOKUP(A1, B:B, C:C, \"Not Found\")"
      ]
    }
  ],
  "categories": ["math", "logical", "lookup", "text", "date", "statistical", "information"],
  "total": 15
}

Translate Formula

Convert an Excel formula to Python/pandas code.

GET /api/v1/calculations/translate

Query Parameters

Parameter Type Required Description
formula string Yes Excel formula to translate
target string No Target: python, pandas, numpy (default: pandas)
include_imports boolean No Include required import statements

Example Request

curl -X GET "https://api.calcbridge.io/api/v1/calculations/translate?formula==SUMIF(A:A,\">100\",B:B)&target=pandas&include_imports=true" \
  -H "Authorization: Bearer $TOKEN"
import requests
from urllib.parse import quote

formula = '=SUMIF(A:A,">100",B:B)'
response = requests.get(
    "https://api.calcbridge.io/api/v1/calculations/translate",
    headers={"Authorization": f"Bearer {token}"},
    params={
        "formula": formula,
        "target": "pandas",
        "include_imports": True
    }
)
result = response.json()
print(result["code"])
const formula = '=SUMIF(A:A,">100",B:B)';
const response = await fetch(
  `https://api.calcbridge.io/api/v1/calculations/translate?formula=${encodeURIComponent(formula)}&target=pandas&include_imports=true`,
  { headers: { 'Authorization': `Bearer ${token}` } }
);
const result = await response.json();
console.log(result.code);

Response

{
  "formula": "=SUMIF(A:A,\">100\",B:B)",
  "target": "pandas",
  "code": "df.loc[df['A'] > 100, 'B'].sum()",
  "imports": [
    "import pandas as pd",
    "import numpy as np"
  ],
  "full_code": "import pandas as pd\nimport numpy as np\n\nresult = df.loc[df['A'] > 100, 'B'].sum()",
  "notes": [
    "Assumes DataFrame 'df' with columns 'A' and 'B'",
    "Column references A:A and B:B mapped to column names"
  ]
}

Function Categories

Mathematical Functions

Function Description
SUM Sum of values
SUMIF Conditional sum
SUMIFS Multi-condition sum
SUMPRODUCT Sum of products
ABS Absolute value
ROUND Round to digits
ROUNDUP Round up
ROUNDDOWN Round down
INT Integer portion
MOD Modulo
POWER Exponentiation
SQRT Square root

Logical Functions

Function Description
IF Conditional logic
IFS Multiple conditions
IFERROR Error handling
AND Logical AND
OR Logical OR
NOT Logical NOT
SWITCH Switch/case
CHOOSE Index selection

Lookup Functions

Function Description
VLOOKUP Vertical lookup
HLOOKUP Horizontal lookup
XLOOKUP Modern lookup
INDEX Array index
MATCH Position match
XMATCH Modern match
OFFSET Range offset

Statistical Functions

Function Description
AVERAGE Arithmetic mean
AVERAGEIF Conditional average
AVERAGEIFS Multi-condition average
COUNT Count numbers
COUNTA Count non-empty
COUNTIF Conditional count
COUNTIFS Multi-condition count
MIN Minimum value
MAX Maximum value
MEDIAN Median value

Text Functions

Function Description
CONCATENATE Join text
CONCAT Modern concatenate
TEXTJOIN Join with delimiter
LEFT Left characters
RIGHT Right characters
MID Middle characters
LEN Text length
TRIM Remove whitespace
UPPER Uppercase
LOWER Lowercase

Date Functions

Function Description
DATE Create date
TODAY Current date
NOW Current datetime
YEAR Extract year
MONTH Extract month
DAY Extract day
DATEDIF Date difference
EDATE Add months
EOMONTH End of month

Error Handling

Excel Error Values

Error Description Python Equivalent
#DIV/0! Division by zero float('inf') or None
#VALUE! Wrong value type None
#REF! Invalid reference None
#NAME? Unknown function Exception
#N/A Value not found None
#NUM! Invalid number None
#NULL! Intersection error None

Error Handling Modes

{
  "options": {
    "error_handling": "excel"  // Default: Return Excel error strings
  }
}
Mode Behavior
excel Return Excel error strings (#DIV/0!, etc.)
null Return null for errors
throw Raise exception on error

Performance Tips

  1. Use batch evaluation: Combine multiple formulas into one request
  2. Provide context efficiently: Only include referenced cells
  3. Cache workbook references: Reuse workbook_id for repeated calculations
  4. Use appropriate precision: Lower precision for faster evaluation
  5. Prefer vectorized functions: SUMIFS over multiple SUMIFs