3

Is it possible to use annotations (at field-level) to provide description for fields?

I know I can use description method for that

.andDo(document("index", responseFields( 
            fieldWithPath("contact").description("The user's contact details"), 

but I would prefer to put that description together with field definition, in my response object.

class IndexResponse {
 //The user's contact details
 String contract;
}

I know that I could have generated constraint descriptions (http://docs.spring.io/spring-restdocs/docs/current/reference/html5/#_using_constraint_descriptions_in_generated_snippets) but it generated description only for validation annotations.

I am looking for something like https://github.com/swagger-api/swagger-core/wiki/Annotations#apimodelproperty from Swagger.

verybadalloc
  • 5,768
  • 2
  • 33
  • 49
Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113

2 Answers2

5

It doesn't. I'm the lead of the REST Docs project and it's my opinion that annotations aren't a good way to write documentation. If you disagree with that opinion and want to use annotations, you could write an add-on that's similar to what's done from constraint descriptions. You could pass it a class to introspect and automatically generate FieldDescriptor instances that you can then pass into the request and response field snippets.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • Just for interest, can you please briefly explain why you consider annotations for documentation bad practice? – aboger Dec 11 '19 at 15:53
  • 1
    Writing good documentation is hard. An attribute on an annotation in your IDE isn't an ideal environment for writing so they only make a hard thing harder. Using Asciidoc in a text editor is more pleasant and more productive in my experience. Also, the location of those annotations, on a Spring MVC controller for example, is a few steps removed from the HTTP requests and responses that someone using your RESTful API cares about. I think that writing documentation at the HTTP level greatly increases the chances of it being accurate. – Andy Wilkinson Dec 11 '19 at 16:50
5

We built an extension to Spring REST Docs that allows using Javadoc for field descriptions:

class IndexResponse {
  /**
   * The user's contact details
   */
  String contract;
}

But currently this only works if Jackson and MockMvc tests are used.

Project: https://github.com/ScaCap/spring-auto-restdocs

An introduction article: https://dzone.com/articles/introducing-spring-auto-rest-docs

Florian Benz
  • 422
  • 4
  • 11