3

Spring REST Docs is a very nice way to create up-to-date API documentation. It also generates code snippets from your test code, that you can insert into your API documentation. When a user of your API reads your documentation they can easily copy-and-paste the snippets into their terminal and execute it.

Currently it generates snippets using single quotes around string values:

$ curl 'https://some.url.com/teams' -i -X POST -H 'Content-Type: application/json' 
-H 'Accept: application/hal+json' -H 'Authorization: Bearer $TOKEN'
-d '{
  "description" : "Test Team"
}'

In the above generated curl request $TOKEN would be an environmental variable, but because of the single quotes the variable substitution would not work. That is why I would like to configure Spring REST Docs somehow to use double quotes around the header's value. Does anybody know how to do this?

Karel
  • 33
  • 4

1 Answers1

2

Looking at the source for spring rest docs the single quotes wrapping the header variables is hard coded in CurlRequestSnippet and I don't see an easy way to extend/override that behavior - https://github.com/spring-projects/spring-restdocs/blob/master/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java#L148

But you can end the single quote, wrap the $TOKEN variable with double quotes then restart the single quote like: header("Authorization", "Bearer '\"$TOKEN\"'"))

More context for an example test with a variable substitution:

this.mockMvc.perform(get("/").header("Authorization", "Bearer '\"$TOKEN\"'"))
                    .andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")))
                .andDo(document("home"));

Which generates curl snippet:

$ curl 'http://localhost:8080/' -i -X GET 
    -H 'Authorization: Bearer '"$TOKEN"''

Not as pretty, but when that snippet is executed the bash variable substitution works.

camtastic
  • 955
  • 6
  • 15
  • Thanks for your answer, it works for me. It would be better if the Spring team would use double quotes in `CurlRequestSnippet` or it would be configurable, but they might have their reason they hardcoded the single quotes in each of their `writer` methods of the `CurlRequestSnippet` class. – Karel Oct 03 '19 at 08:38
  • @Karel I'm a member of the Spring team and the lead of Spring REST Docs. I agree about the quotes. Could you please [open an issue](https://github.com/spring-projects/spring-restdocs/issues/new) so that we can make an improvement here? – Andy Wilkinson Oct 03 '19 at 17:09
  • @AndyWilkinson Thanks for your comment. Sorry for the late answer. I created the issue on github: https://github.com/spring-projects/spring-restdocs/issues/650. I hope I followed your team's convention how to create and describe an issue. – Karel Oct 15 '19 at 10:53
  • @Karel Thanks for opening an issue. – Andy Wilkinson Oct 15 '19 at 20:15