Skip to content

api Module#

This module is used to interact with the PyMarkdown application through a programmatic Python interface, instead of through the command line. This API Listing assumes familiarity with the PyMarkdown linter and its command line interface. For a more descriptive and easy to follow guide to this API, please check out our API Support document.

Our current process is to add new functions to the API in response to requests from our users. If you have need of any other API members to expose functionality that already exists through the command line, please follow our feature request process.


Main API#

pymarkdown.api.PyMarkdownApi #

Module to provide for an API to directly communicate with PyMarkdown instead of using a command line.

Parameters:

  • inherit_logging (bool, default: False ) –

    If True, inherit the logging settings from the calling application. If False, will use the log_* functions to specify the logging properties.

scan_path(path_to_scan, recurse_if_directory=False, alternate_extensions=None, exclude_patterns=None, respect_gitignore=False) #

Scan any eligible Markdown files found on the provided path. For more information, check out our User's Guide sections on Basic Scanning and Command Line Arguments.

Parameters:

  • path_to_scan (str) –

    If path_to_scan is a directory, scan within that directory for eligible Markdown files. If path_to_scan is a file, determine if the file is an eligible Markdown file before proceeding with the scan.

  • recurse_if_directory (bool, default: False ) –

    If path_to_scan is a directory and recurse_if_directory if True, also scan any directories within the specified directory.

  • alternate_extensions (str, default: None ) –

    Optionally specify one or more comma-separated file extensions. Files with these file extensions are also considered to be eligible files to scan.

  • exclude_patterns (List[str], default: None ) –

    Optionally specify one or more glob-style patterns to exclude files or directories from being scanned.

  • respect_gitignore (bool, default: False ) –

    If True, respect any .gitignore files found when scanning according to standard Git rules.

Raises:

Returns:

  • PyMarkdownScanPathResult

    An instance of PyMarkdownScanPathResult containing any scan failures or pragma errors encountered when scanning the eligible files on the provided path.

Examples:

This example scans a specific Markdown file file.md for any issues. Both good results (printing of the two properties of scan_result) and bad results (printing the exception information) are properly handled.

from pymarkdown.api import PyMarkdownApi, PyMarkdownApiException

try:
    scan_result = PyMarkdownApi().scan_path("file.md")
    print(f"Scan Failures: {scan_result.scan_failures}")
    print(f"Pragma Errors: {scan_result.pragma_errors}")
except PyMarkdownApiException as this_exception:
    print(f"API Exception: {this_exception}", file=sys.stderr)

By replacing the line with scan_path with:

scan_result = PyMarkdownApi().scan_path("./docs", recurse_if_directory=True)

the code will now scan for any *.md files in the ./docs directory and in any directories under the ./docs directory.

scan_string(string_to_scan) #

Scan the specified string as a Markdown document.

Parameters:

  • string_to_scan (str) –

    String to interpret as a Markdown document.

Raises:

Returns:

  • PyMarkdownScanPathResult

    An instance of PyMarkdownScanPathResult containing any scan failures or pragma errors encountered when scanning the Markdown document.

Examples:

This example is a simplified form of the scan_path example that accepts a string to scan instead

from pymarkdown.api import PyMarkdownApi, PyMarkdownApiException

markdown_string = "# Markdown\n\nIs cool!\n"

try:
    scan_result = PyMarkdownApi().scan_string(markdown_string)
    print(f"Scan Failures: {scan_result.scan_failures}")
    print(f"Pragma Errors: {scan_result.pragma_errors}")
except PyMarkdownApiException as this_exception:
    print(f"API Exception: {this_exception}", file=sys.stderr)

fix_path(path_to_scan, recurse_if_directory=False, alternate_extensions=None, exclude_patterns=None, respect_gitignore=False) #

Fix any eligible Markdown files found on the provided path that have scan failures that can be automatically fixed.

Parameters:

  • path_to_scan (str) –

    If path_to_scan is a directory, scan within that directory for eligible Markdown files. If path_to_scan is a file, determine if the file is an eligible Markdown file before proceeding with the scan and fix.

  • recurse_if_directory (bool, default: False ) –

    If path_to_scan is a directory and recurse_if_directory if True, also scan any directories within the specified directory.

  • alternate_extensions (str, default: None ) –

    Optionally specify one or more comma-separated file extensions. Files with these file extensions are also considered to be eligible files to scan.

  • exclude_patterns (List[str], default: None ) –

    Optionally specify one or more glob-style patterns to exclude files or directories from being scanned.

  • respect_gitignore (bool, default: False ) –

    If True, respect any .gitignore files found when scanning according to standard Git rules.

Raises:

Returns:

Examples:

This function is syntactically equivalent to calling the scan_path function except for its return value.

from pymarkdown.api import PyMarkdownApi, PyMarkdownApiException

try:
    fix_result = PyMarkdownApi().fix_path("file.md")
    print(f"Fixed file paths: {fix_result.files_fixed}")
except PyMarkdownApiException as this_exception:
    print(f"API Exception: {this_exception}", file=sys.stderr)

fix_string(string_to_scan) #

Scan the specified string as a Markdown document and apply any eligible fixes.

Parameters:

  • string_to_scan (str) –

    String to interpret as a Markdown document.

Raises:

Returns:

Examples:

This function is syntactically equivalent to calling the scan_string function except for its return value.

from pymarkdown.api import PyMarkdownApi, PyMarkdownApiException

markdown_string = "# Markdown\n\nIs cool!\n"

try:
    fix_result = PyMarkdownApi().fix_string(markdown_string)
    print(f"Applied fixes?  {fix_result.was_fixed}")
    print(f"Fixed Markdown: {fix_result.fixed_file}")
except PyMarkdownApiException as this_exception:
    print(f"API Exception: {this_exception}", file=sys.stderr)

list_path(path_to_scan, recurse_if_directory=False, alternate_extensions='', exclude_patterns=None, respect_gitignore=False) #

List any eligible files found when scanning the specified path for eligible markdown files. This function is provided for debugging situations to provide confidence that one or more Markdown files are indeed being scanned by PyMarkdown.

Parameters:

  • path_to_scan (str) –

    If path_to_scan is a directory, scan within that directory for eligible Markdown files. If path_to_scan is a file, determine if the file is an eligible Markdown file.

  • recurse_if_directory (bool, default: False ) –

    If path_to_scan is a directory and recurse_if_directory if True, also scan any directories within the specified directory.

  • alternate_extensions (str, default: '' ) –

    Optionally specify one or more comma-separated file extensions. Files with these file extensions are also considered to be eligible files to scan.

  • exclude_patterns (List[str], default: None ) –

    Optionally specify one or more glob-style patterns to exclude files or directories from being scanned.

  • respect_gitignore (bool, default: False ) –

    If True, respect any .gitignore files found when scanning according to standard Git rules.

Raises:

Returns:

Examples:

This example generates a list of the files that PyMarkdown will scan if the scan_path function is invoked with the same parameters.

from pymarkdown.api import PyMarkdownApi, PyMarkdownApiException

try:
    scan_result = PyMarkdownApi().list_path("./docs", recurse_if_directory=True)
    print(scan_result.matching_files)
except PyMarkdownApiException as this_exception:
    print(f"API Exception: {this_exception}", file=sys.stderr)

application_version property #

Report on the application version.

Returns:

  • str

    The current application version.

Examples:

This function queries the current version of PyMarkdown.

from pymarkdown.api import PyMarkdownApi

print(f"PyMarkdown version = {PyMarkdownApi().application_version}")

interface_version property #

Report on the interface version.

Returns:

  • int

    The current plugin interface version.

Examples:

This function queries the current version of this API.

from pymarkdown.api import PyMarkdownApi

print(f"PyMarkdown API version = {PyMarkdownApi().interface_version}")

Modifiers#

All modifiers can be chained together without requiring separate statements.

For example, the following statement is a fluent example of how to use these modifiers in a function chain:

Python PyMarkdownApi().enable_stack_trace().log_debug_and_above().fix_string("something")

More in-depth information about each of these modifiers is available in our User's Guide section on General Command Line Arguments.

pymarkdown.api.PyMarkdownApi #

Module to provide for an API to directly communicate with PyMarkdown instead of using a command line.

Parameters:

  • inherit_logging (bool, default: False ) –

    If True, inherit the logging settings from the calling application. If False, will use the log_* functions to specify the logging properties.

disable_rule_by_identifier(rule_identifier) #

Disable a single rule by one of its identifiers.

Parameters:

  • rule_identifier (str) –

    Identifier for the rule to disable.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function disables a single rule by one of its identifiers.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().disable_rule_by_identifier("md031").scan_path("file.md")
enable_rule_by_identifier(rule_identifier) #

Enable a single rule by one of its identifiers.

Parameters:

  • rule_identifier (str) –

    Identifier for the rule to enable.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function enables a single rule by one of its identifiers.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().enable_rule_by_identifier("md031").scan_path("file.md")
enable_extension_by_identifier(extension_identifier) #

Enable a single extension by its identifier.

Parameters:

  • extension_identifier (str) –

    Identifier for the extension to enable.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function enables a single extension by its identifier.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().enable_extension_by_identifier("front-matter").scan_path("file.md")
configuration_file_path(path_to_config_file) #

Set the path to the configuration file to use.

Parameters:

  • path_to_config_file (str) –

    Path to the configuration file to use.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function specifies a file containing configuration information.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().path_to_config_file("pymarkdown.cfg").scan_path("file.md")
set_boolean_property(property_name, property_value) #

Set a named configuration property to a given boolean value.

Parameters:

  • property_name (str) –

    Full hierarchical name of the property to set.

  • property_value (bool) –

    True or False boolean value to set the property to.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets a boolean value for a specific configuration item.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().set_boolean_property("plugins.md007.enabled", True).scan_path("file.md")
set_integer_property(property_name, property_value) #

Set a named configuration property to a given integer value.

Parameters:

  • property_name (str) –

    Full hierarchical name of the property to set.

  • property_value (int) –

    Integer value to set the property to.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets a integer value for a specific configuration item.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().set_integer_property("plugins.md007.code_block_line_length", 160).scan_path("file.md")
set_string_property(property_name, property_value) #

Set a named configuration property to a given string value.

Parameters:

  • property_name (str) –

    Full hierarchical name of the property to set.

  • property_value (str) –

    String value to set the property to.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets a string value for a specific configuration item.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().set_string_property("plugins.heading-style-h1.style", "consistent").scan_path("file.md")
set_property(property_name, property_value) #

Set a named configuration property to a given value. Whatever is passed in as the property_value parameter is translated into a string.

If at all possible, the other three set_x_property functions should be used as they ensure that the correct type of value is set as the configuration item value. This function translated ANY value for the property_value argument into a str before setting it as the configuration item value.

Parameters:

  • property_name (str) –

    Full hierarchical name of the property to set.

  • property_value (Any) –

    Value to set the property to after applying a string transformation to the value.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets a value, translated into a string, for a specific configuration item.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().set_property("plugins.heading-style-h1.style", 1).scan_path("file.md")
enable_strict_configuration() #

Enable strict configuration for any requested properties, either through configuration files or manual setting.

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function enforces strict adherence to configuration requirements.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().enable_strict_configuration().scan_path("file.md")
log_debug_and_above() #

Enable logging for the DEBUG level and above.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets the logging level for PyMarkdown to anything that is at DEBUG logging level or above.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().log_debug_and_above().scan_path("file.md")
log_info_and_above() #

Enable logging for the INFO level and above.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets the logging level for PyMarkdown to anything that is at INFO logging level or above.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().log_info_and_above().scan_path("file.md")
log_warning_and_above() #

Enable logging for the WARN level and above.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets the logging level for PyMarkdown to anything that is at WARNING logging level or above.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().log_warning_and_above().scan_path("file.md")
log_error_and_above() #

Enable logging for the ERROR level and above.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets the logging level for PyMarkdown to anything that is at ERROR logging level or above.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().log_error_and_above().scan_path("file.md")
log_critical_and_above() #

Enable logging for the CRITICAL level and above.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets the logging level for PyMarkdown to anything that is at CRITICAL logging level or above.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().log_critical_and_above().scan_path("file.md")
log(log_level) #

Set the logging level using a string value.

Parameters:

  • log_level (str) –

    One of "CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG".

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function sets the logging level for PyMarkdown to anything that is at INFO logging level or above.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().log("INFO").scan_path("file.md")
log_to_file(log_file_path) #

Set a file to log any results to.

Parameters:

  • log_file_path (str) –

    Path to the file to write the logs to.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function writes any logging messages to the specified file.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().log_to_file("file.log").scan_path("file.md")
add_plugin_path(path_to_plugin) #

Add a plugin path that points to a directory with plugins or a single plugin.

Parameters:

  • path_to_plugin (str) –

    Path to an additional plugin to load.

Raises:

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function informs PyMarkdown to use a new plugin.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().add_plugin_path("my_plugin.py").scan_path("file.md")
enable_stack_trace() #

Enable the reporting of stack traces for any exceptions caught by the API. If this modifier is present, additional information will be recorded as to the exact nature of any reported exception.

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function enable stack trace support in case of a raised exception.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().enable_stack_trace().scan_path("file.md")
disable_json5_configuration() #

Disable the use of the JSON5 parser for configuration files, instead using the base json parser from the Python standard library.

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function disables the use of the JSON5 parser for configuration files.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().disable_json5_configuration().scan_path("file.md")
enable_continue_on_error() #

Enable the scanning of multiple files to continue, even if some of the files have critical errors.

Returns:

  • PyMarkdownApi

    An instance of PyMarkdownApi to allow for function chaining.

Examples:

This function disables the use of the JSON5 parser for configuration files.

from pymarkdown.api import PyMarkdownApi

PyMarkdownApi().disable_json5_configuration().scan_path("file.md")

Scan Results#

pymarkdown.api.PyMarkdownScanPathResult dataclass #

Result for the scan_path and scan_string functions.

As both PyMarkdownScanFailure objects and PyMarkdownPragmaError objects contain location and additional failure/error information, this result object is a simple pair of lists containing failure information.

Attributes:


pymarkdown.api.PyMarkdownScanFailure dataclass #

Class to contain information about a failure reported by one of the rule plugins.

Each instance of this class specifies a single scan failure that was encountered within the specified Markdown document. Using the encapsulated fields, the following pieces of information about that scan failure can be determined:

  • the location where the scan failure occurred
  • the specific location within that location that triggered the scan failure
  • the exact rule that was triggered

Optionally, depending on the rule, extra information may be present in the extra_error_information field. This information is rule-dependent and is intended to provide extra clarity on why the rule was triggered.

For more information consult the Rule Failure Format section of our User's Guide.

Attributes:

  • scan_file (str) –

    Path to the file containing the failure.

  • line_number (int) –

    Line number of the triggered rule failure.

  • column_number (int) –

    Column number of the triggered rule failure.

  • rule_id (str) –

    ID of the rule that was triggered.

  • rule_name (str) –

    Name(s) of the rule that was triggered.

  • rule_description (str) –

    Longer description of the rule that was triggered.

  • extra_error_information (Optional[str]) –

    String providing more information on why the rule was triggered.


pymarkdown.api.PyMarkdownPragmaError dataclass #

Class to encapsulate the information for a pragma error.

Each instance of this class specifies a single pragma failure that was encountered within the specified Markdown document. Using the encapsulated fields, the following pieces of information about that pragma error can be determined:

  • the location where the pragma error occurred
  • the specific location within that location that triggered the pragma error
  • specific information on why PyMarkdown generated the pragma error

More information on Pragmas and their use are available here.

Attributes:

  • file_path (str) –

    Path to the file that contains the improperly constructed pragma.

  • line_number (int) –

    Line number where the pragma is contained.

  • pragma_error (str) –

    Specific information about the error.


Fix Results#

pymarkdown.api.PyMarkdownFixResult dataclass #

Result for the fix_path function.

The only information that PyMarkdown provides about scanned and fixed documents are the names of the documents that were fixed. As such, this result simply provides those same Markdown file names.

Attributes:

  • files_fixed (List[str]) –

    List of zero or more files that were fixed.


pymarkdown.api.PyMarkdownFixStringResult dataclass #

Result for the fix_string function.

Focusing on a singular Markdown document, this object returns an indication of whether fixes were applied along with the fixed document.

Attributes:

  • was_fixed (bool) –

    Whether the string, interpretted as a Markdown document, was fixed.

  • fixed_file (str) –

    String that was passed into the fix_string function, with any fixes applied to it.


List Results#

pymarkdown.api.PyMarkdownListPathResult dataclass #

Result for the list_path function.

This object returns a list of files that PyMarkdown understands to be eligible for scanning, without having scanned those files.

Attributes:

  • matching_files (List[str]) –

    List of filenames that match the specifications of the requested path.


Exceptions#

pymarkdown.api.PyMarkdownApiException #

Bases: Exception

Class to provide for an exception that is thrown by the API layer.

This base PyMarkdown application exception is explicitly thrown when a unexpected error occurs that is not categorized as one of the other application exceptions. Where possible, child classes of this class should be used to provide more specific information regarding the nature of the exception.

Attributes:

  • reason (str) –

    Reported reason why the action failed.


pymarkdown.api.PyMarkdownApiArgumentException #

Bases: PyMarkdownApiException

Class to provide for an argument that an exception is not valid.

This exception is raised when an argument to a function falls outside of the expected behavior for that function. This can mean that a str parameter is unexpectedly empty or that the parameter is not one of the allowed values for that parameter.

Attributes:

  • reason (str) –

    Reported reason why the action failed.

  • argument_name(str) (str) –

    Name of the argument that caused this exception to be raised.


pymarkdown.api.PyMarkdownApiNoFilesFoundException #

Bases: PyMarkdownApiException

Class to provide for an exception that the invoked API was not able to find at least one file to process.

This is raised as an exception if at least one file to scan or fix is not encountered. As the PyMarkdown application is a scanning application, not finding a single Markdown document to scan is typically an exceptional case.

Attributes:

  • reason (str) –

    Reported reason why the action failed.


pymarkdown.api.PyMarkdownApiNotSupportedException #

Bases: PyMarkdownApiException

Class to provide for an exception that a given situation is not supported.

The most frequent raising of this exception is when the PyMarkdownApi instance is created with the inherit_logging set to True, followed by a call to one of the functions that alters the logging behavior of the application.

Attributes:

  • reason (str) –

    Reported reason why the action failed.