Search code examples
spring-restdocs

How to document recursive data structures in response with Spring REST Docs


I have a question with regards to Spring Restdocs. One of the rest calls I want to document returns a recursive data structure, with different types children: leaf and subtree. Leaf and subtrees have different attributes. For example:

{
    "id": "$",
    "left": {
        "id": "l",
        "left": {
            "id": "l1",
            "type": "leaf",
            "value": "Leaf 1"
        },
        "right": {
            "id": "l2",
            "type": "leaf",
            "value": "Leaf 2"
        },
        "type": "subtree"
    },
    "right": {
        "id": "l3",
        "type": "leaf",
        "value": "Leaf 3"
    },
    "type": "subtree"
}

I could not find how to document those recursive data structures with Spring Restdocs. Has anybody some example or could help me.

I have setup a git repo with some code which shows my problem: https://github.com/dibog/spring-restdocs-recursive-demo

Best regards, Dieter


Solution

  • It depends on exactly what you want to document and how you want to describe things to your users. I would focus on the two different types of nodes – subtrees and leafs – and provide documentation that describes their format and that each node in the tree will either be a leaf or a subtree.

    You can use REST Docs to document the structure of the two different node types using the response fields snippet, focussed on a specific part of the response:

    responseFields(beneathPath("left.left").withSubsectionId("leaf"),
        fieldWithPath("id").description("ID of the node"),
        fieldWithPath("type").description("Type of the node. Always 'leaf' for leaf nodes"),
        fieldWithPath("value").description("Value of the node")),
    responseFields(beneathPath("left").withSubsectionId("subtree"),
        fieldWithPath("id").description("ID of the node"),
        fieldWithPath("type").description("Type of the node. Always 'subtree' for nodes with children"),
        subsectionWithPath("left").description("Left-hand child node. Either a subtree or a leaf"),
        subsectionWithPath("right").description("Right-hand child node. Either a subtree or a leaf"))
    

    The use of subsectionWithPath when documenting a subtree node allows you to cover the entire subtree with a single descriptor. The description informs the user that the value of left and right will be a node that is either a leaf or another subtree.