Swagger TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body

Spring BootSwaggerSwagger UiSwagger 2.0

Spring Boot Problem Overview


I have added Swagger to my Spring Boot 2 application:

This is my Swagger config:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
	    // @formatter:off
        return new Docket(DocumentationType.SWAGGER_2)  
                .select()                                  
                .apis(RequestHandlerSelectors.any())              
                .paths(PathSelectors.any())                          
                .build();
        // @formatter:on
    }
}

This is Maven dependency:

<!-- Swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

When I try to invoke for example http://localhost:8080/api/actuator/auditevents it fails with the following error:

TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

enter image description here

What am I doing wrong and how to fix it ?

Spring Boot Solutions


Solution 1 - Spring Boot

The error message actually says what the problem is. You post data with curl using the -d option while trying to use GET.

If you use the -d option curl will do POST.
If you use -X GET option curl will do GET.

The HTTP GET method is for requesting a representation of the specified resource. Requests using GET should only retrieve data and hence cannot have body.

More info on GET vs POST

Solution 2 - Spring Boot

I ran into this issue. Here is how I resolved it:

I had a method like this:

[HttpGet]
public IEnumerable<MyObject> Get(MyObject dto)
{
      ...
}

and I was getting the error. I believe swagger UI is interpreting the Get parameters as FromBody, so it uses the curl -d flag. I added the [FromQuery] decorator and the problem was resolved:

[HttpGet]
public IEnumerable<MyObject> Get([FromQuery]MyObject dto)
{
      ...
}

FYI this also changes the UI experience for that method. instead of supplying json, you will have a form field for each property of the parameter object.

Solution 3 - Spring Boot

I had same problem with my .net core 2.0 solution and GET method that takes element id as header key or search for it by parameters in body. That is not the best way to implement but it's kind of special case.

As mentioned in this discussion. The HTTP spec does not forbid using body on a GET, but swagger is not implementing it like this. Even if there are APIs that work fine with body in GET Requests.

What more, the swagger frontend adds this body object into request even if it is null/undefined/empty object. It is -d "body_content_here" parameter. So in my case when i only search by id and body is empty, it still sends empty object (-d "{}") and throws mentioned error.

Possible solutions:

  • Start using postman app for this request - It will work fine. Tested.

  • Consider moving more advanced GET request (like search with criteria) to the independent POST Method

  • Use swagger generated CURL request request without -d parameter

Solution 4 - Spring Boot

Don't pass method type in Get method.

let res = await fetch("http://localhost:8080/employee_async",{
    			method: "POST",
	    		body:JSON.stringify(data),
		    	mode:"cors",
			    headers: {"Content-type":"application/json;charset=utf-8"}})

This is used for post only, If we don't assign any method type node automatically considered as Get method

Solution 5 - Spring Boot

To avoid this error be sure to annotate parameters in your controller with @RequestParam, like

@GetMapping("/get")
public Response getData(@RequestParam String param)

Solution 6 - Spring Boot

Looking at swagger exception/error message , looks like you are calling Get method with a set of input body. As per documentation of GET method doesn't accept any body. You need to change the GET method to POST method. It should work.

Solution 7 - Spring Boot

Pass Paremeters with [FromQuery] in Methods InPut

Solution 8 - Spring Boot

Maybe the problem is with the mapping of the method, make sure to use @RequestMapping(value = "/<your path>" , method = RequestMethod.POST) and put the data as body with @RequestBody

Solution 9 - Spring Boot

I also got the same error on the Swagger UI. My problem was I have mistakenly marked the Api Method as GET and send data in the request body. Once I change the annotation @GET to @POST issue got resolved.

Solution 10 - Spring Boot

Because you used GET http method with body. If you want to have Json body, etc you need to use POST http method, For example in your controller class, top of your method:

    @PostMapping(value = "/save")
    public ResponseEntity<HttpStatus> savePerson(@RequestBody Person person) 
    {...}

Use GET without body.

Solution 11 - Spring Boot

I was having this issue when trying to use Swagger UI on a Ruby On Rails app. I fixed it by changing the information container on the curl command. This is a example line:

parameter name: :body, in: :body, schema: {'$ref' => '#/definitions/ActivitiesFilter'}, required: true

into

parameter name: :attribute_name1, in: :query, required: true
parameter name: :attribute_name2, in: :query, required: true
parameter name: :attribute_name3, in: :query, required: true

note that you have to add as many lines as attributes are defined on your schema inside swagger_helper

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexanoidView Question on Stackoverflow
Solution 1 - Spring BootBorisView Answer on Stackoverflow
Solution 2 - Spring BootironfistView Answer on Stackoverflow
Solution 3 - Spring BootchotkosView Answer on Stackoverflow
Solution 4 - Spring BootAkshaykumar ChormuleView Answer on Stackoverflow
Solution 5 - Spring BootАлексей ВиноградовView Answer on Stackoverflow
Solution 6 - Spring BootkrisView Answer on Stackoverflow
Solution 7 - Spring Bootbehnam farzadmehrView Answer on Stackoverflow
Solution 8 - Spring BootMichaelKView Answer on Stackoverflow
Solution 9 - Spring BootTharindu JayasuriyaView Answer on Stackoverflow
Solution 10 - Spring Bootsalman pierView Answer on Stackoverflow
Solution 11 - Spring BootSebastian EcheverriaView Answer on Stackoverflow