Skip to content
Back to top
View this page
Edit this page

# Python API

Sphinx-Needs provides an open API for other Sphinx-extensions to provide specific need-types, create needs or make usage of the filter possibilities.

The API allows the injection of extra configuration, but does not support manipulation of it (e.g remove need types), to keep the final configuration transparent for the Sphinx project authors.

## Configuration

API to get or add specific sphinx needs configuration parameters.

All functions here are available under `sphinx_needs.api`.

add_dynamic_function(app: Sphinx, function: DynamicFunction, name: str | None = None) → None

  Registers a new dynamic function for sphinx-needs.

  If `name` is not given, the name to call the function is automatically taken from the provided function. The used name must be unique.

  Usage:

      from sphinx_needs.api import add_dynamic_function

      def my_function(app, need, needs, *args, **kwargs):
          # Do magic here
          return "some data"

      add_dynamic_function(app, my_function)

  Read Dynamic functions for details about how to use dynamic functions.

  Parameters:

    - app – Sphinx application object

    - function – Function to register

    - name – Name of the dynamic function as string

  Returns:

    None

add_extra_option(app: Sphinx, name: str, *, description: str = 'Added by add_extra_option API') → None

  Adds an extra option to the configuration. This option can then later be used inside needs or `add_need`.

  Same impact as using needs_extra_options manually.

  Usage:

      from sphinx_needs.api import add_extra_option

      add_extra_option(app, 'my_extra_option')

  Parameters:

    - app – Sphinx application object

    - name – Name as string of the extra option

  Returns:

    None

add_need_type(app: Sphinx, directive: str, title: str, prefix: str, color: str = '#ffffff', style: str = 'node') → None

  Adds a new need_type to the configuration.

  The given directive must no exist, otherwise NeedsApiConfigException gets raised.

  Same impact as using needs_types manually.

  Usage:

      from sphinx_needs.api import add_need_type

      add_need_type(app, 'awesome', 'Awesome', 'AW_', '#000000', 'cloud')

  Parameters:

    - app – Sphinx application object

    - directive – Name of the directive, e.g. ‘story’

    - title – Long, human-readable title, e.g. ‘User-Story’

    - prefix – Prefix, if IDs get automatically generated. E.g.: `'US_'`

    - color – Hex-color code used in needflow representation. Default: `'#ffffff'`

    - style – Plantuml-style for needflow representation. Default: ‘node’

  Returns:

    None

add_warning(app: Sphinx, name: str, function: Callable[[NeedsInfoType, SphinxLoggerAdapter], bool] | None = None, filter_string: str | None = None) → None

  Registers a warning.

  A warning can be based on the result of a given filter_string or an own defined function.

  Parameters:

    - app – Sphinx app object

    - name – Name as string for the warning

    - function – function to execute to check the warning

    - filter_string – filter_string to use for the warning

  Returns:

    None

get_need_types(app: Sphinx) → list[str]

  Returns a list of directive-names from all configured need_types.

  Usage:

      from sphinx_needs.api import get_need_types

      all_types = get_need_types(app)

  Parameters:

    app – Sphinx application object

  Returns:

    list of strings

class DynamicFunction(*args, **kwargs)

  A protocol for a sphinx-needs dynamic function.

  __call__(app: Sphinx, need: NeedsInfoType | None, needs: NeedsView | NeedsMutable, *args: Any, **kwargs: Any) → str | int | float | list[str] | list[int] | list[float] | None

    Call self as a function.

## Need

add_external_need(app: Sphinx, need_type: str, title: str | None = None, id: str | None = None, external_url: str | None = None, external_css: str = 'external_link', content: str = '', status: str | None = None, tags: str | list[str] | None = None, constraints: str | None = None, **kwargs: Any) → list[Node]

  Adds an external need from an external source. This need does not have any representation in the current documentation project. However, it can be linked and filtered. It’s reference will open a link to another, external sphinx documentation project.

  It returns an empty list (without any nodes), so no nodes will be added to the document.

  Parameters:

    - app – Sphinx application object.

    - need_type – Name of the need type to create.

    - title – String as title.

    - id – ID as string. If not given, a id will get generated.

    - external_url – URL as string, which shall be used as link to the original need source

    - content – Content as single string.

    - status – Status as string.

    - tags – A list of tags, or a comma separated string.

    - constraints – constraints as single, comma separated string.

    - external_css – CSS class name as string, which is set for the <a> tag.

  Raises:

    InvalidNeedException – If the need could not be added due to a validation issue.

add_need(app: Sphinx, state: None | RSTState, docname: None | str, lineno: None | int, need_type: str, title: str, *, id: str | None = None, content: str | StringList = '', lineno_content: None | int = None, doctype: None | str = None, status: str | None = None, tags: None | str | list[str] = None, constraints: None | str | list[str] = None, parts: dict[str, NeedsPartType] | None = None, arch: dict[str, str] | None = None, signature: str = '', sections: list[str] | None = None, jinja_content: None | bool = False, hide: bool = False, collapse: None | bool = None, style: None | str = None, layout: None | str = None, template: None | str = None, pre_template: str | None = None, post_template: str | None = None, is_external: bool = False, external_url: str | None = None, external_css: str = 'external_link', full_title: str | None = None, **kwargs: Any) → list[Node]

  Creates a new need and returns its node.

  `add_need` allows to create needs programmatically and use its returned node to be integrated in any docutils based structure.

  `kwargs` can contain options defined in `needs_extra_options` and `needs_extra_links`. If an entry is found in `kwargs`, which is not specified in the configuration or registered e.g. via `add_extra_option`, an exception is raised.

  If `is_external` is set to `True`, no node will be created. Instead, the need is referencing an external url. Used mostly for needs_external_needs to integrate and reference needs from external documentation.

  Raises:

    InvalidNeedException – If the need could not be added due to a validation issue.

  If the need is within the current project, i.e. not an external need, the following parameters are used to help provide source mapped warnings and errors:

  Parameters:

    - docname – documentation identifier, for the referencing document.

    - lineno – line number of the top of the directive (1-indexed).

    - lineno_content – line number of the content start of the directive (1-indexed).

  Otherwise, the following parameters are used:

  Parameters:

    - is_external – Is true, no node is created and need is referencing external url

    - external_url – URL as string, which is used as target if `is_external` is `True`

    - external_css – CSS class name as string, which is set for the <a> tag.

  Additional parameters:

  Parameters:

    - app – Sphinx application object.

    - state – Current state object.

    - need_type – Name of the need type to create.

    - title – String as title.

    - full_title – This is given, if an auto-generated title was trimmed. It is used to auto-generate the ID, if required.

    - id – ID as string. If not given, an id will get generated.

    - content – Content of the need, either as a `str` or a `StringList` (a string with mapping to the source text).

    - status – Status as string.

    - tags – A list of tags, or a comma separated string.

    - constraints – Constraints as single, comma separated, string.

    - constraints_passed – Contains bool describing if all constraints have passed

    - hide – boolean value.

    - collapse – boolean value.

    - style – String value of class attribute of node.

    - layout – String value of layout definition to use

    - template – Template name to use for the content of this need

    - pre_template – Template name to use for content added before need

    - post_template – Template name to use for the content added after need

  Returns:

    list of nodes

del_need(app: Sphinx, need_id: str) → None

  Deletes an existing need.

  Parameters:

    - app – Sphinx application object.

    - need_id – Sphinx need id.

generate_need(needs_config: NeedsSphinxConfig, need_type: str, title: str, *, docname: None | str = None, lineno: None | int = None, id: str | None = None, doctype: str = '.rst', content: str = '', lineno_content: None | int = None, status: str | None = None, tags: None | str | list[str] = None, constraints: None | str | list[str] = None, parts: dict[str, NeedsPartType] | None = None, arch: dict[str, str] | None = None, signature: str = '', sections: list[str] | None = None, jinja_content: None | bool = False, hide: bool = False, collapse: None | bool = None, style: None | str = None, layout: None | str = None, template_root: Path | None = None, template: None | str = None, pre_template: str | None = None, post_template: str | None = None, is_external: bool = False, external_url: str | None = None, external_css: str = 'external_link', full_title: str | None = None, **kwargs: str) → NeedsInfoType

  Creates a validated need data entry, without adding it to the project.

  Important

  This function does not parse or analyse the content, and so will not auto-populate the `parts` or `arch` fields of the need from the content.

  It will also not validate that the ID is not already in use within the project.

  Raises:

    InvalidNeedException – If the data fails any validation issue.

  `kwargs` can contain options defined in `needs_extra_options` and `needs_extra_links`. If an entry is found in `kwargs`, which is not specified in the configuration or registered e.g. via `add_extra_option`, an exception is raised.

  If the need is within the current project, i.e. not an external need, the following parameters are used to help provide source mapped warnings and errors:

  Parameters:

    - docname – documentation identifier, for the referencing document.

    - lineno – line number of the top of the directive (1-indexed).

    - lineno_content – line number of the content start of the directive (1-indexed).

  Otherwise, the following parameters are used:

  Parameters:

    - is_external – Is true, no node is created and need is referencing external url

    - external_url – URL as string, which is used as target if `is_external` is `True`

    - external_css – CSS class name as string, which is set for the <a> tag.

  Additional parameters:

  Parameters:

    - app – Sphinx application object.

    - state – Current state object.

    - need_type – Name of the need type to create.

    - title – String as title.

    - full_title – This is given, if an auto-generated title was trimmed. It is used to auto-generate the ID, if required.

    - id – ID as string. If not given, an id will get generated.

    - content – Content of the need

    - status – Status as string.

    - tags – A list of tags, or a comma separated string.

    - constraints – Constraints as single, comma separated, string.

    - constraints_passed – Contains bool describing if all constraints have passed

    - hide – boolean value.

    - collapse – boolean value.

    - style – String value of class attribute of node.

    - layout – String value of layout definition to use

    - template_root – Root path for template files, only required if the template_path config is relative.

    - template – Template name to use for the content of this need

    - pre_template – Template name to use for content added before need

    - post_template – Template name to use for the content added after need

get_needs_view(app: Sphinx) → NeedsView

  Return a read-only view of all resolved needs.

  Important

  this should only be called within the write phase, after the needs have been fully collected. If not already done, this will ensure all needs are resolved (e.g. back links have been computed etc), and then lock the data to prevent further modification.

## Exceptions

exception InvalidNeedException(type_: Literal['invalid_kwargs', 'invalid_type', 'missing_id', 'invalid_id', 'duplicate_id', 'invalid_status', 'invalid_tags', 'invalid_constraints', 'invalid_jinja_content', 'invalid_template', 'global_option'], message: str)

  Raised when a need could not be created/added, due to a validation issue.

exception NeedsApiConfigException

  A configuration changes collides with the already provided configuration by the user.

  Example: An extension wants to add an already existing needs_type.

exception NeedsApiConfigWarning

exception NeedsConstraintFailed

exception NeedsInvalidException

exception NeedsInvalidFilter

## Data

Module to control access to sphinx-needs data, which is stored in the Sphinx environment.

class NeedsInfoType

  Data for a single need.

  arch: Required[dict[str, str]]

    Mapping of uml key to uml content.

  collapse: Required[bool]

    Hide the meta-data information of the need.

  constraints: Required[list[str]]

    List of constraint names, which are defined for this need.

  constraints_error: str

    An error message set if any constraint failed, and error_message field is set in config.

  constraints_passed: Required[bool]

    True if all constraints passed, False if any failed, None if not yet checked.

  constraints_results: Required[dict[str, dict[str, bool]]]

    Mapping of constraint name, to check name, to result.

  docname: Required[str | None]

    Name of the document where the need is defined (None if external).

  doctype: Required[str]

    Type of the document where the need is defined, e.g. ‘.rst’.

  external_css: Required[str]

    CSS class name, added to the external reference.

  external_url: Required[None | str]

    URL of the need, if it is an external need.

  has_dead_links: Required[bool]

    True if any links reference need ids that are not found in the need list.

  has_forbidden_dead_links: Required[bool]

    True if any links reference need ids that are not found in the need list, and the link type does not allow dead links.

  hide: Required[bool]

    If true, the need is not rendered.

  id: Required[str]

    ID of the data.

  id_complete: Required[str]

    <parent ID>.<self ID>, or <self ID> if not a part.

  id_parent: Required[str]

    <parent ID>, or <self ID> if not a part.

  is_external: Required[bool]

    If true, no node is created and need is referencing external url.

  is_modified: Required[bool]

    Whether the need was modified by needextend.

  layout: Required[None | str]

    Key of the layout, which is used to render the need.

  lineno: Required[int | None]

    Line number where the need is defined (None if external).

  lineno_content: Required[int | None]

    Line number on which the need content starts (None if external).

  links: list[str]

    List of need IDs, which are referenced by this need.

  links_back: list[str]

    List of need IDs, which are referencing this need.

  modifications: Required[int]

    Number of modifications by needextend.

  parent_need: Required[str]

    Simply the first parent id.

  parent_needs: list[str]

    List of parents of the this need (by id), i.e. if this need is nested in another

  parent_needs_back: list[str]

    List of children of this need (by id), i.e. if needs are nested within this one

  section_name: Required[str]

    Simply the first section.

  signature: Required[str | Text]

    Derived from a docutils desc_name node.

  style: Required[None | str]

    Comma-separated list of CSS classes (all appended by needs_style_).

  title: Required[str]

    Title of the need.

  type_color: Required[str]

    Hexadecimal color code of the type.

class NeedsMutable

  A mutable view of the needs, before resolution

  alias of `dict`[`str`, `NeedsInfoType`]

class NeedsPartType

  Data for a single need part.

  content: str

    Content of the part.

  id: str

    ID of the part

  links: list[str]

    List of need IDs, which are referenced by this part.

  links_back: list[str]

    List of need IDs, which are referencing this part.

## Views

These views are returned by certain functions, and injected into filters, but should not be instantiated directly.

class NeedsAndPartsListView(*, _indexes: _LazyIndexes, _selected_ids: dict[tuple[str, str | None], None] | None)

  A read-only view of needs and parts, after resolution (e.g. back links have been computed etc)

  The parts are created by creating a copy of the need for each item in `parts`, and then overwriting a subset of fields with the values from the part.

  __iter__() → Iterator[NeedsInfoType]

    Iterate over the needs and parts in the view.

  __len__() → int
  filter_has_tag(values: list[str]) → NeedsAndPartsListView

    Create new view with only needs/parts that have at least one of these values in the `tags` field list.

  filter_ids(values: Iterable[str]) → NeedsAndPartsListView

    Create new view with needs/parts filtered by the `id` field.

  filter_is_external(value: bool) → NeedsAndPartsListView

    Create new view with only needs/parts where `is_external` field is true/false.

  filter_statuses(values: list[str]) → NeedsAndPartsListView

    Create new view with only needs/parts that have certain `status` field values.

  filter_types(values: list[str], or_type_names: bool = False) → NeedsAndPartsListView

    Create new view with only needs/parts that have certain `type` field values.

    Parameters:

      - values – List of types to filter by.

      - or_type_names – If True, filter by both `type` and `type_name` field

  get_need(id: str, part_id: str | None = None) → NeedsInfoType | None

    Get a need by id, or return None if it does not exist.

    If `part_id` is provided, return the part of the need with that id, or None if it does not exist.

class NeedsView(*, _indexes: _LazyIndexes, _selected_ids: dict[str, None] | None)

  A read-only view of needs, mapping need ids to need data, with “fast” filtering methods.

  The needs are read-only and fully resolved (e.g. dynamic values and back links have been computed etc)

  __getitem__(key: str) → NeedsInfoType
  __iter__() → Iterator[str]
  __len__() → int
  filter_has_tag(values: list[str]) → NeedsView

    Create new view with only needs that have at least one of these values in the `tags` field list.

  filter_ids(values: Iterable[str]) → NeedsView

    Create new view with needs filtered by the `id` field.

  filter_is_external(value: bool) → NeedsView

    Create new view with only needs where `is_external` field is true/false.

  filter_statuses(values: list[str]) → NeedsView

    Create new view with only needs that have certain `status` field values.

  filter_types(values: list[str], or_type_names: bool = False) → NeedsView

    Create new view with only needs that have certain `type` field values.

    Parameters:

      - values – List of types to filter by.

      - or_type_names – If True, filter by both `type` and `type_name` field

  to_list_with_parts() → NeedsAndPartsListView

    Create a new view with needs and parts.