Skip to main content

Extending the API

How a method is added to the konsol Frappe app today, and what is checked before it ships. Read with the API Reference.

Where methods live​

A method is a Python function with the @frappe.whitelist() decorator. Frappe serves it at /api/method/<module path>.<function>. In konsol they live in:

ModuleHolds
konsol/api.pyValues (epm_value, epm_batch), budget writes, hierarchies, the Excel add-in's auth and report builders, the Airbyte webhook
konsol/close/<screen>_api.pyOne module per Close app screen; pure logic in the matching <screen>_model.py
konsol/cli_api.py, konsol/schema_apply.pyConfiguration bundles and Apply Schema
konsol/chart_upload.py, konsol/tb_bulk.py, konsol/group_rates.py, konsol/fiscal_calendar.pyAdmin tools
konsol/orchestrator/api.pyPipeline runs
doctype controllersDocument methods (publish, unpublish, generate_periods, ...) called from the form
Excel add-in / Close app / Desk / CLI → HTTP → Frappe (konsol) → MariaDB (documents) and ClickHouse (warehouse) → JSON

Rules a new method must follow​

1. Declare the verb; writes are POST​

Frappe rolls the database back at the end of a GET request. Any method that inserts, saves, submits, cancels, enqueues or commits must be:

@frappe.whitelist(methods=["POST"])
def save_thing(...):

A GET-only method is @frappe.whitelist(methods=["GET"]). A GET-only method answers 403 to a POST, and frappe.xcall defaults to POST, so a Desk caller passes "GET" explicitly. A decorator with no methods= accepts both; in konsol/close/ that is not allowed (see the contract test below).

2. Gate the role first​

In konsol/close/, the first real statement of every method is frappe.only_for with a literal tuple of roles:

@frappe.whitelist(methods=["GET"])
def get_thing(fiscal_year, fiscal_period):
"""One sentence on what it returns and what it refuses."""
frappe.only_for(("EPM Admin", "EPM Analyst", "EPM User", "System Manager"))
...

Elsewhere, admin tools call konsol.schema_lifecycle.check_epm_admin (EPM Admin, System Manager or Administrator), and document methods rely on the caller's permission on the document (doc.check_permission("write")).

3. Scope by entity​

A read that goes straight to ClickHouse never passes Frappe's permission layer. Call konsol.entity_permissions.assert_entity_access for one entity, or resolve allowed_entity_codes() once and ask entity_read_scope per row in a batch. None means unrestricted; an empty set means the caller may see nothing. Rows for other entities are dropped and counted in a hidden field, not silently omitted.

4. Refuse before you write​

Every refusal (frappe.throw with a sentence written for the user) comes before the first insert or save, so a refused request leaves nothing behind. Name the thing refused and what to do: "%s is %s: a journal is drafted in an open period."

5. Pin the contract with a test​

konsol/tests/test_close_api_contract.py parses every konsol/close/*_api.py with ast and fails if a method does not declare exactly methods=["GET"] or methods=["POST"], if a GET-capable method contains a write call (.insert(, .save(, .submit(, .cancel(, db.set_value, db.commit, frappe.enqueue, delete_doc), or if its first statement is not frappe.only_for(...). It runs on the host without a bench.

Other tests that pin API contracts, all under konsol/tests/: test_api_generalisation.py (the fact / dimensions / default-measure read path in api.py), test_budget_api.py, test_close_tb_api.py, test_tb_bulk.py, test_orchestrator_api.py, test_cli_api_slim.py (exactly five methods in cli_api.py), test_reporting_hierarchy_tree_api.py, test_assertion_run_access.py, test_role_access.py, and one test_close_<screen>_api.py per close screen. Add to these when you add a method; a new close screen gets its own.

Reading a POST body​

Methods in konsol/api.py that take a JSON document read it raw:

@frappe.whitelist(methods=["POST"])
def save_thing():
data = json.loads(frappe.request.get_data(as_text=True)) # _get_json_body()

Close methods instead declare named parameters; Frappe fills them from form fields or a JSON body. Lists arrive as JSON strings and are parsed in the function (lines, kinds, names).

Querying ClickHouse​

konsol/api.py talks to ClickHouse over HTTP with ClickHouse's own parameter binding. Never interpolate a value into SQL.

from konsol.clickhouse import connection_url as _ch_url
from konsol.clickhouse import get_connection as _get_ch_connection

sql = """
SELECT data_area_id, sum(period_net_amount) AS total
FROM epm_gold.gold_trial_balance
WHERE data_area_id = {entity:String}
AND fiscal_year = {year:Int32}
GROUP BY data_area_id
"""
params = {"param_entity": "USMF", "param_year": "2024"}
rows = _clickhouse_query(sql, params, _get_ch_connection())
  • {name:Type} in the SQL, param_name=value on the wire. A bare name is read by ClickHouse as a setting and fails with UNKNOWN_SETTING.
  • _clickhouse_query(sql, params, ch_settings) GETs with the credentials as an HTTP auth tuple, a 30 s timeout and the connection's verify flag. konsol.clickhouse.execute(sql, params) POSTs the same way for statements and FORMAT JSON reads.
  • Identifiers that come from a record (a measure name, a table) are checked with _SAFE_IDENTIFIER (^[a-z][a-z0-9_]*$) and _SAFE_TABLE_NAME (schema.table, lowercase) before they reach the SQL.

Making a new Gold model readable through =K.EPM()​

No code change. The read path validates against the registry doctypes at request time:

  • _get_fact(fact=..., scenario=...) loads a Dataset by fact_name (wins) or scenario_key.
  • _measure_for fills a blank measure with the Dataset's default_measure.
  • _get_allowed_measures reads the Dataset's measures; the measure must also be a Published Measure.
  • _get_fact_dimensions reads the Dataset's dimensions; every requested dimension must be in it.
  • _resolve_and_validate(fact_name, scenario, measure, dim_names) runs all of this and returns (dataset, error_or_None), with the "Allowed: ..." list built from the records.

1. Create the Measure records​

Doctype Measure (module EPM), one per measure the model exposes:

  • measure_name, e.g. forecast_amount (what clients pass as measure=)
  • expression, e.g. sum(forecast_amount)
  • label; cube_type one of sum, count, avg, last
  • status: Published for the measure to validate (Draft and Inactive do not)

2. Create the Dataset record​

Doctype Dataset (module EPM; name = fact_name):

  • fact_name, e.g. forecast (clients pass fact=forecast)
  • scenario_key, e.g. forecast (clients pass scenario=forecast)
  • clickhouse_table, e.g. epm_gold.gold_forecast_model (validated as lowercase schema.table); dbt_model
  • has_scenario_id if the table keeps rows per budget scenario; has_layer if it keeps budget layers
  • fact_measures (child table Dataset Measure): one row per allowed Measure, each Published; mirrored into the measures JSON the read path uses
  • default_measure: the measure a read takes when none is named
  • fact_dimensions (child table Dataset Dimension): mirrored into dimensions
  • reroute_measure / reroute_table / reroute_column: let one measure read a different table or column
  • status: use the Publish action (the whitelisted document method publish, EPM Admin) to apply the schema and request a rebuild

3. Test​

curl "http://localhost:8069/api/method/konsol.api.epm_value?\
entity=USMF&year=2025&period=5&account=401100&\
measure=forecast_amount&fact=forecast" \
-b cookies.txt

A standalone endpoint​

import frappe
from konsol.clickhouse import get_connection as _get_ch_connection
from konsol.entity_permissions import assert_entity_access

@frappe.whitelist(methods=["GET"])
def get_entity_total(entity, year):
"""Net amount of one entity for one year; refuses an entity outside the caller's scope."""
frappe.only_for(("EPM Admin", "EPM Analyst", "EPM User", "System Manager"))
assert_entity_access(entity)
sql = (
"SELECT sum(period_net_amount) FROM epm_gold.gold_trial_balance "
"WHERE data_area_id = {entity:String} AND fiscal_year = {year:Int32}"
)
raw = _clickhouse_query(sql, {"param_entity": entity, "param_year": str(int(year))},
_get_ch_connection())
return {"total": float(raw or 0)}

Validate registry input with _resolve_and_validate and raise its error with frappe.throw(err, frappe.ValidationError) rather than keeping a list of allowed values in code.

Response format​

Frappe wraps the return value: return {"value": 123.45} reaches the client as {"message": {"value": 123.45}}. A frappe.throw is HTTP 417 with exc_type and _server_messages; a PermissionError is 403. To set another status, assign frappe.local.response.http_status_code before returning (budget_cell_save does this for 409 and 423).

Next steps​