SARIF Object Model
The `sarif-om` library provides Python classes that implement the Static Analysis Results Interchange Format (SARIF) Version 2.1.0 object model, an OASIS Committee Specification. It allows programmatic creation and manipulation of SARIF log structures in Python. The current version is 1.0.4. Microsoft maintains the project, but an explicit release cadence is not published.
Warnings
- gotcha The `sarif-om` library provides only the object model classes. It does not include functionality to directly load existing SARIF files from disk or to serialize the in-memory object model to a file. Users must implement their own JSON parsing (e.g., using `json.load`/`json.loads`) and serialization (e.g., using `json.dump`/`json.dumps`) to work with actual SARIF files. Other libraries like `pysarif` or `sarif-tools` offer file I/O capabilities for SARIF.
- gotcha Documentation for programmatic usage of `sarif-om` can be sparse, particularly for constructing complex SARIF logs from scratch. Most public examples or tutorials tend to focus on the `sarif-tools` command-line utility or `pysarif` library for interacting with SARIF files.
- breaking The related `sarif-tools` library (a separate project that *uses* `sarif-om`) introduced breaking changes in its 2.0.0 release. Specifically, CSV output columns ('Code' and 'Description' are now separate) and the `--blame-filter` argument (replaced by `--filter` with a new YAML-based format) were changed. This directly impacts users interacting with `sarif-tools` for reporting or filtering.
Install
-
pip install sarif-om
Imports
- SarifLog
from sarif_om import SarifLog, Run, Tool, ToolComponent, Result, Location, PhysicalLocation, ArtifactLocation, Message, ReportingDescriptor
Quickstart
import json
from sarif_om import SarifLog, Run, Tool, ToolComponent, Result, Location, PhysicalLocation, ArtifactLocation, Message, ReportingDescriptor
# Create a SARIF log object
log = SarifLog(version='2.1.0', runs=[])
# Create a Tool component
tool_component = ToolComponent(name='Example Tool', version='1.0.0')
# Create a Tool
tool = Tool(driver=tool_component)
# Create a Run
run = Run(tool=tool, results=[])
# Create a ReportingDescriptor (rule definition)
rule = ReportingDescriptor(id='EX1001', name='Example Rule', short_description=Message(text='This is an example rule.'))
# Add the rule to the tool's driver rules
tool.driver.rules = [rule]
# Create a Result
result = Result(
rule_id='EX1001',
message=Message(text='Found a potential issue.'),
locations=[
Location(
physical_location=PhysicalLocation(
artifact_location=ArtifactLocation(uri='src/main.py'),
region={'startLine': 10, 'startColumn': 5}
)
)
]
)
# Add the result to the run
run.results.append(result)
# Add the run to the log
log.runs.append(run)
# Serialize the SARIF log to JSON (sarif-om does not provide a direct save method)
sarif_json = json.dumps(log.to_dict(), indent=2)
print(sarif_json)