Reports API

The Reports module exposes a comprehensive REST API under the /api/reports/ prefix, allowing you to automate all operations available through the graphical interface: creating and managing templates, generating PDFs, viewing history, customizing branding, creating custom Python blocks, and configuring matrix rules. This page documents the twenty-three available endpoints along with their input and output schemas.

Endpoints Overview

Endpoints are grouped into seven functional families. Each family corresponds to a specific area of the interface and can be used independently.

Family Number of Endpoints Usage
Templates 5 Manage reusable report skeletons
Generation 2 Produce a final PDF or a preview
Consultation 4 List, retrieve, download, or delete reports
Nexus Sessions 1 List available sessions for generation
Branding 3 Customize organization name and logo
Custom Blocks 5 CRUD for user-created Python blocks
Matrices 3 Configure relevance rules between matrices

Templates

The five template endpoints form a complete CRUD suite. Default (embedded) templates are read-only; modifications only apply to user-created templates.

Method Path Description
GET /api/reports/templates Lists all available templates
POST /api/reports/templates Creates a user template (returns 201)
GET /api/reports/templates/{id} Retrieves a template by ID
PUT /api/reports/templates/{id} Updates a user template
DELETE /api/reports/templates/{id} Deletes a user template

Creation Schema (TemplateCreate): name, blocks (list of keys), description, language (default 'fr'), mode ('concis' or 'expert'). Update (TemplateUpdate) only accepts blocks, name, and description.

Generation

Two endpoints share the same internal logic. The only difference is that /preview forces the is_preview=True flag, producing a temporary, non-persisted PDF intended for viewing in a new tab.

Method Path Usage
POST /api/reports/generate Persisted final PDF added to history
POST /api/reports/preview Temporary preview PDF

ReportGenerateRequest Schema

The generation input schema is the most detailed in the API. It includes sixteen optional fields covering report structure, data inclusion, and environmental context.

Field Type Description
template_id optional int ID of an existing template
blocks optional list of str Ad hoc template (if template_id is absent)
title str Report title, default "IsoFind Report"
sample_ids optional list of int Filters the included samples
project optional str Project name (simple usage)
project_data optional dict Full project object (name, objective, constraints), takes priority over project
nexus_session_id optional int Loads a Nexus session by its ID
nexus_result optional dict Nexus result passed directly (alternative to nexus_session_id)
auto_context_result optional dict Automatic geochemical context result
scoring_result optional dict Matching or scoring result
licence_data optional dict Associated license and branding information
language str 'fr' or 'en', default 'fr'
is_preview bool Preview mode (forced to True by /preview)
mbtiles_path optional str Path to an offline map tile
snapshots optional dict Map snapshots and vertical sections: {map: [...], section: [...]}
simulation_result optional dict CSIA or redox simulation result, required for sim_* blocks, Pro license
scenarios optional list of dict Saved scenarios for scenario_comparison: {id, label, ts, meta}
At least one of the two fields template_id or blocks must be present, otherwise the request returns a 422. Other fields are optional, and the engine adapts to the provided set.

Retrieval and Download

Generated reports are persisted on the server with an ID and a PDF file path. The API allows listing, retrieving metadata, downloading the file, and deletion.

Method Path Description
GET /api/reports/list Lists all generated reports
GET /api/reports/{id} Report metadata (title, date, blocks, path)
GET /api/reports/download/{id} Downloads the PDF as application/pdf
DELETE /api/reports/{id} Deletes the report record and its file
Deletion removes both the database record and the PDF file from the disk. This action is irreversible. A signed PDF already transmitted to a third party remains valid and verifiable on their end, but it will no longer be downloadable via the API.

Nexus Sessions

A dedicated endpoint lists available Nexus sessions to populate the report creation form. It reads directly from the SQLite sessions database and returns the fifty most recent entries.

Method Path Response
GET /api/reports/nexus-sessions {success: true, sessions: [...], count: n}

Each returned session contains its ID, name, associated sample_id and sample_name, the processed element, and the creation date. This information is used to provide a dropdown menu for the user in the interface.

Branding

Branding includes the organization name and the path to a local logo that will be injected into report headers and footers. It is stored on the server and applied automatically during each generation.

Method Path Description
GET /api/reports/branding Returns the configured branding
PUT /api/reports/branding Updates name and logo, Pro license required
DELETE /api/reports/branding Restores default IsoFind branding

The update validates that the provided logo path points to an existing file and that its extension is recognized (PNG, JPG, JPEG, or SVG). A missing file or unsupported format returns a 400 error with an explicit message.

Custom Blocks

The five custom block endpoints form a full CRUD suite with one key feature: backend Python syntax validation before acceptance.

Method Path Description
GET /api/reports/custom-blocks Lists active custom blocks
GET /api/reports/custom-blocks/{id} Retrieves a block by ID
POST /api/reports/custom-blocks Creates a block, pre-compiling the Python code
PUT /api/reports/custom-blocks/{id} Updates a block, re-compiling if code is modified
DELETE /api/reports/custom-blocks/{id} Deletes the block

The CustomBlockCreate schema requires: key, name, and code_python. Other fields have default values: description='', category='custom', nature='I', icon='CB', licence='pro', expert=False, language='fr', api_calls=None.

The backend calls compile(code_python, '<custom_block>', 'exec') on the provided code before saving. A SyntaxError triggers an HTTP 422 with a detailed error message. This early validation prevents saving a syntactically invalid block that would fail during generation.

Groups and Matrix Rules

Sampling matrices (water, soil, sediment, etc.) can be grouped by affinity, and relevance rules can be defined between these groups. This configuration supports validations performed when comparing different matrices within the same report.

Method Path Description
GET /api/reports/matrix-groups Returns configured groups and rules
PUT /api/reports/matrix-groups Saves the set of groups and rules
GET /api/reports/matrix-groups/check Verifies relevance between matrix_a and matrix_b

A matrix group includes an ID, name, color, a list of concrete matrices, and an optional note. A rule links two groups (from_group, to_group), carries a relevant flag (boolean), and a note. The check endpoint returns relevant (bool or null) and defined (bool indicating if the rule exists).

Standard Error Codes

All endpoints follow the same HTTP error code conventions.

Code Meaning Occurrence Case
200 OK Request processed successfully
201 Created Template created (POST templates)
400 Bad Request Missing logo file or unsupported format
404 Not Found Template, report, or block not found
422 Unprocessable Entity Missing parameters, Python syntax error, invalid key
500 Internal Server Error Unexpected error during generation
503 Service Unavailable Reports module not loaded at startup

Programmatic Usage Example

The following example illustrates a complete workflow in Python using the requests library: selecting a Nexus session, generating the report, and downloading the PDF.

import requests

base = 'http://localhost:8000'

# Select a Nexus session
sessions = requests.get(f'{base}/api/reports/nexus-sessions').json()
session_id = sessions['sessions'][0]['id']

# Generate report with the expert preset
payload = {
    'blocks': ['cover_page', 'executive_summary', 'sample_inventory',
               'nexus_processes', 'nexus_chain', 'limitations',
               'certification'],
    'title': 'Automated Audit -- Nexus session',
    'nexus_session_id': session_id,
    'language': 'en',
}
resp = requests.post(f'{base}/api/reports/generate', json=payload)
report = resp.json()

# Download the PDF
pdf = requests.get(f'{base}/api/reports/download/{report["id"]}')
with open('report.pdf', 'wb') as f:
    f.write(pdf.content)

This automation is the recommended path for integrating IsoFind into larger pipelines: continuous monitoring, periodic follow-up reports, or batch production of certifications for a portfolio of sites.

Authentication

The API is protected by the same authentication system as the graphical interface. A token is required in the HTTP header for endpoints that modify state or access sensitive data. Read-only endpoints for default templates are accessible without a token.

Details on obtaining and using the token are described in the general IsoFind API documentation. For third-party integrations, a service token can be generated in the administration panel and revoked independently of the user account.

Branding and custom block endpoints operate at the workstation level and are more sensitive than report retrieval endpoints. Strict access control for these endpoints is recommended in enterprise deployments.

Going Further