Mykola  Slutskyi
Mykola Slutskyi

Reputation: 168

Documenting PUT REST call without body and with path and query parameters

There's REST API call designed via HTTP PUT that has only path and query parameters and does not need a body:

PUT /posts/{id}/read?currentUser={loginId} 

Trying to document it using Spring REST Docs 2.0.0.RELEASE I noticed that http-request.adoc is as below:

[source,http,options="nowrap"]
----
PUT /posts/42?currentUser=johndoe HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded

currentUser=johndoe
----

I am confused, why currentUser=johndoe is rendered in body (like form parameter)? Is it a bug? Complete example of application below:

@RestController
@RequestMapping("/posts")
@SpringBootApplication
public class DemoApplication {

    @PutMapping("{id}/read")
    public void markPostRead(@PathVariable("id") String id, @RequestParam("currentUser") String login) {
        System.out.println("User " + login + " has read post " + id);
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class DemoApplicationTests {

    @Rule
    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext context;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
                .apply(documentationConfiguration(this.restDocumentation))
                .build();
    }
    @Test
    public void contextLoads() throws Exception {
        mockMvc.perform(
                RestDocumentationRequestBuilders.put("/posts/{id}/read?currentUser=johndoe", 42))
                .andDo(document("mark-as-read", pathParameters(
                        parameterWithName("id").description("ID of the Post")
                )))
                .andDo(document("mark-as-read", requestParameters(
                        parameterWithName("currentUser").description("Login ID of user")
                )));
    }

}

Upvotes: 2

Views: 3732

Answers (2)

evainga
evainga

Reputation: 41

Also, according to your endpoint "@PutMapping("{id}/read")", I noticed that in your REST documentation test the "/read" part of the path is missing.

Upvotes: 2

mle
mle

Reputation: 2542

If you study RFC 2616 with special attention on the PUT section you will read…

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

So the question is, although the spec is not 100 % clear in this part: Is it allowed to send a PUT request with no request body at all?

This is one of the questions on which you get 11 answers if you ask 10 developers but just to be fine with all imponderables, Spring REST Docs puts your query parameter in the request body just to be prepared for all those little more strict web servers out there. ;-)

Upvotes: 3

Related Questions