How to create a curl snippet with Spring REST Docs to use double quotes instead of single ones?

Viewed 514

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 Answers

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.

Related