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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 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 so that we can make an improvement here?
@AndyWilkinson Thanks for your comment. Sorry for the late answer. I created the issue on github: github.com/spring-projects/spring-restdocs/issues/650. I hope I followed your team's convention how to create and describe an issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.