spring-projects / spring-restdocs

Test-driven documentation for RESTful services
https://spring.io/projects/spring-restdocs
Apache License 2.0
1.16k stars 736 forks source link

Add ability to document an object root, just like it is possible to document an array #745

Open sherzinger opened 3 years ago

sherzinger commented 3 years ago

Hi,

We're using this framework to document a REST API. The API has several endpoints that return a user object like {"name": "Danny Default", "id": 123}.

To create a user:

POST /users/ 

To get all users:

GET /users/

To get a specific user:

GET /users/123

To update certain parts of the user object:

PATCH /users/123 

All these endpoints have in common that they are returning user object(s). Naturally, we would like to avoid documenting the same object again and again, but instead refer to an already existing (response-fields) documentation of the user object returned by another endpoint or dedicated model section in the docs.

To solve this case for array response of GET /users/ is quite simple, as we can just .ignore() all fields and document the root array itself like this: fieldWithPath("[]").type(JsonFieldType.Array).description("<<UserRepresentation>>"). This results in response-fields snippet with a single entry that contains a link to [[UserRepresentation]], which maybe resides at the end of the docs under a === Common Models section.

However, this solution fails when the root of the response is no array, but the object itself like in PATCH /users/123, which responds with an updated user object like {"name": "Bob Basic", "id": 123}. As in the above section we can .ignore() all fields, but then there is no way to document the root becausefieldWithPath("") as well as fieldWithPath(".") result in NPEs. That leaves us only with very few options, aside from heavily modifying the template or the hardcoding the response-fields table into the .adoc file directly.

I'd appreciate some advice regarding this and if possible suggest the ability to document the root object as a feature.

Thank you!

wilkinsona commented 3 years ago

Thanks for the suggestion. This is covered by #627 but I think it's worth tracking separately as the two are only loosely connected.