This tutorial guides you through setting up a new Sphinx documentation
project with sphinx-needs from scratch. By the end, you’ll have a
working documentation system that can manage requirements,
specifications, and traceability.
Note
Target audience: Software developers (especially C++ developers)
who are new to Sphinx but want to leverage documentation-as-code for
requirements management.
Python 3.12+ installed on your system (required by Sphinx 9.x and sphinx-needs 6.x)
uv - a fast Python package and project manager
A terminal/command line
A text editor or IDE (VS Code with ubCode extension recommended)
Note
Version Compatibility:
Sphinx 9.x requires Python 3.12 or higher
sphinx-needs 6.x requires Sphinx 7.4+ and Python 3.10+
For best results, use the latest stable versions of both
If you don’t have uv installed, install it first:
# On macOS/Linux
curl-LsSfhttps://astral.sh/uv/install.sh|sh
# On Windows
powershell-ExecutionPolicyByPass-c"irm https://astral.sh/uv/install.ps1 | iex"
Tip
What is uv?
uv is an extremely fast Python package and project manager written
in Rust. It’s 10-100x faster than pip and replaces pip, virtualenv,
and pyenv in a single tool. It handles virtual environments,
dependencies, and Python version management seamlessly.
# Initialize project with Python 3.12
uvinit--python3.12
# Create virtual environment (uv manages this automatically)
uvvenv
# On macOS/Linux, activate it:source.venv/bin/activate
# On Windows:# .venv\Scripts\activate
Your project structure now looks like:
my-docs-project/
├── .venv/
├── .python-version
├── pyproject.toml
└── hello.py # You can delete this
Note
With uv, you can also run commands directly without activating the
virtual environment by prefixing them with uvrun. This is the
recommended approach as it ensures the correct environment is always
used.
Run the Sphinx quickstart wizard. This creates a source directory and
generates a default conf.py with useful configuration values:
uvrunsphinx-quickstartdocs
Answer the prompts as follows:
> Separate source and build directories (y/n) [n]: n
> Project name: My Documentation Project
> Author name(s): Your Name
> Project release []: 0.1.0
> Project language [en]: en
Instead of configuring sphinx-needs directly in conf.py, we use a
separate ubproject.toml file. This declarative approach has several
advantages:
Clean separation: Configuration is separate from Python code
Tooling support: Works with ubCode (VS Code extension) for
real-time previews, linting, and code intelligence
Easier maintenance: TOML is easier to read and modify than Python
Schema validation: Can be validated against a JSON schema
Portability: Configuration can be consumed by other tools
Note
What is ubCode?
ubCode is a VS Code extension that provides a lightning-fast language
server for Sphinx-Needs projects. It offers real-time RST previews,
linting, smart need filtering, and editor navigation. The
ubproject.toml file is the standard configuration format for
ubCode-compatible projects.
Create docs/ubproject.toml:
# Sphinx-Needs configuration in TOML format.# Announced to Sphinx-Needs via needs_from_toml in conf.py.# Schema: https://ubcode.useblocks.com/ubproject.schema.json"$schema"="https://ubcode.useblocks.com/ubproject.schema.json"[project]name="My Documentation Project"description="Requirements management with Sphinx-Needs"srcdir="."#--------------------------------------------------------------------------# Sphinx-Needs Configuration# All settings go under [needs] WITHOUT the needs_ prefix#--------------------------------------------------------------------------[needs]# Export needs to JSON for external tools and CI/CD integrationbuild_json=true# Force authors to set IDs manually (recommended for stable links)# Without this, Sphinx-Needs auto-generates IDs from titles,# which break when titles changeid_required=true# ID format validation using regex# This pattern requires: 2-10 uppercase letters/underscores,# optionally followed by _NNN (1-3 digits)# Examples: REQ_001, SPEC_42, TC_1id_regex="[A-Z_]{2,10}(_[\\d]{1,3})*"# Additional options available for all need types# These become :option: fields in your RST directivesextra_options=["priority","author","version",]#--------------------------------------------------------------------------# Need Types# Each [[needs.types]] entry defines a new directive you can use in RST#--------------------------------------------------------------------------[[needs.types]]directive="req"# Use as: .. req:: Titletitle="Requirement"# Display name in outputprefix="REQ_"# Suggested ID prefixcolor="#FFB300"# Color in diagrams (amber)style="node"# PlantUML style: node, artifact, frame, etc.[[needs.types]]directive="spec"title="Specification"prefix="SPEC_"color="#ec6dd7"# Pink/magentastyle="node"[[needs.types]]directive="impl"title="Implementation"prefix="IMPL_"color="#fa8638"# Orangestyle="node"[[needs.types]]directive="test"title="Test Case"prefix="TC_"color="#A6BDD7"# Light bluestyle="node"#--------------------------------------------------------------------------# Link Types# Define relationships between needs for traceability# Each link type creates bidirectional connections#--------------------------------------------------------------------------[[needs.extra_links]]option="implements"# Use as: :implements: REQ_001outgoing="implements"# Label on forward linkincoming="implemented by"# Label on backward link (auto-generated)color="#00AA00"# Green in diagrams[[needs.extra_links]]option="tests"outgoing="tests"incoming="tested by"color="#0000AA"# Blue[[needs.extra_links]]option="derives"outgoing="derives from"incoming="derived by"color="#AA0000"# Red
Edit docs/conf.py to enable sphinx-needs and load the TOML
configuration. The conf.py file is executed as Python, allowing
complex customization, but we keep it minimal by delegating sphinx-needs
configuration to the TOML file:
# docs/conf.py# Configuration file for the Sphinx documentation builder.# https://www.sphinx-doc.org/en/master/usage/configuration.html# -- Project information -------------------------------------------project='My Documentation Project'copyright='2025, Your Name'author='Your Name'release='0.1.0'# -- General configuration -----------------------------------------extensions=['sphinx_needs',# Requirements management]templates_path=['_templates']exclude_patterns=['_build','Thumbs.db','.DS_Store']# -- Sphinx-Needs configuration ------------------------------------# Load configuration from external TOML file# This is the key line that connects sphinx-needs to ubproject.tomlneeds_from_toml="ubproject.toml"# -- Options for HTML output ---------------------------------------html_theme='alabaster'html_static_path=['_static']
The key line is needs_from_toml="ubproject.toml" which tells
sphinx-needs to read its configuration from the TOML file. All settings
in the [needs] section of the TOML file are loaded automatically.
Welcome to My Documentation Project====================================
This project demonstrates requirements management with Sphinx-Needs.
..toctree:::maxdepth: 2
:caption: Contents:
requirements
specifications
traceability
Indices and tables==================*:ref:`genindex`*:ref:`search`
Requirements============
This section contains all project requirements.
System Requirements-------------------..req:: User Authentication
:id: REQ_001
:status: open
:priority: high
:author: Your Name
The system shall provide user authentication functionality.
Users must be able to log in with username and password.
**Acceptance Criteria:*** Users can register with email and password
* Users can log in with valid credentials
* Failed login attempts are logged
..req:: Data Persistence
:id: REQ_002
:status: open
:priority: high
:derives: REQ_001
The system shall persist user data securely in a database.
This requirement depends on user authentication.
..req:: Performance Target
:id: REQ_003
:status: open
:priority: medium
The system shall respond to API requests within 200ms
under normal load conditions (< 1000 concurrent users).
Create docs/traceability.rst to visualize the relationships between
your needs:
Traceability============
This section provides various views of requirements traceability.
Requirements Overview---------------------
All requirements and their current status:
..needtable:::filter: type == 'req'
:columns: id;title;status;priority
:style: table
:sort: id
The ``:filter:`` option uses Python-like expressions to select needs.
Common filters:
*``type == 'req'`` - All requirements
*``status == 'open'`` - Open items only
*``'auth' in title.lower()`` - Title contains "auth"
Full Traceability Flow----------------------
This diagram shows how requirements, specifications, and tests
connect:
..needflow:::filter: type in ['req', 'spec', 'test']
:engine: graphviz
:show_link_names::show_legend:
The ``needflow`` directive creates a visual flowchart of needs and
their relationships. Use ``:show_link_names:`` to label the
connections.
..note::
We use ``:engine: graphviz`` here because Graphviz is easier to
set up (no Java required). For more advanced diagrams and
additional directives like ``needsequence`` or ``needuml``, see
:ref:`tutorial-plantuml-setup`.
Specifications Matrix---------------------
Which requirements are covered by specifications:
..needtable:::filter: type == 'spec'
:columns: id;title;status;implements
:style: table
Test Coverage-------------
Which specifications have test cases:
..needtable:::filter: type == 'test'
:columns: id;title;status;tests
:style: table
Open Items----------
All items that are not yet done:
..needtable:::filter: status == 'open'
:columns: id;type;title;status
:style: table
:sort: type
All settings go under [needs]without the needs_ prefix:
[needs]build_json=true# Export needs to JSONid_required=true# Require manual IDs (recommended)id_regex="..."# ID format validationtitle_optional=false# Require titles on needs
[[needs.types]]directive="req"# RST directive: .. req::title="Requirement"# Display titleprefix="REQ_"# ID prefixcolor="#FFB300"# Hex color for diagramsstyle="node"# PlantUML style
Available styles: node, artifact, frame, storage,
database, actor
Use [[needs.extra_links]] for traceability relationships:
[[needs.extra_links]]option="implements"# RST option: :implements:outgoing="implements"# Forward link labelincoming="implemented by"# Auto-generated backward linkcolor="#00AA00"# Link color in diagrams
Note
As of sphinx-needs 6.1.0, the incoming and outgoing fields are
optional. If omitted, the option name is used as the default label.
Starting with sphinx-needs 6.0, you can define typed extra options with
JSON schema constraints. This provides validation for custom fields:
# Typed extra options with validation[[needs.extra_options]]name="priority"schema.type="string"schema.enum=["low","medium","high","critical"][[needs.extra_options]]name="effort_hours"schema.type="integer"schema.minimum=1schema.maximum=1000[[needs.extra_options]]name="verified"schema.type="boolean"
This approach provides:
Type checking - Ensure values match expected types (string, integer,
boolean, array)
Enum constraints - Restrict values to a predefined set
Range validation - Set minimum/maximum for numeric fields
Build-time warnings - Invalid values trigger warnings during build
When schema violations occur, sphinx-needs generates a
schema_violations.json file alongside needs.json for debugging.
If you see errors like plantumlcommandcannotberun or
FileNotFoundError:java, you’re using the default PlantUML engine
without proper setup. You have two options:
Quick fix: Add :engine:graphviz to your needflow
directives
Ensure the target need ID exists and is spelled correctly. IDs are
case-sensitive. Use the generated needs.json to verify all IDs.
Schema validation warnings (sphinx-needs 6.0+)
If you’re using typed extra options with schema validation, you may see
warnings like sn_schema_warning or sn_schema_violation. To
suppress specific warning types, add to conf.py: