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

144,004

Solution 1

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

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

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

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

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.

Share:
144,004
alexanoid
Author by

alexanoid

Updated on December 22, 2021

Comments

  • alexanoid
    alexanoid over 2 years

    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 ?

  • alexanoid
    alexanoid over 6 years
    Thanks for your answer. I'm not using the curl directly. This is some internal output from Swagger 2.8.0. By the way - I have downgraded the Swagger version to 2.7.0 and the issue is gone. What may be wrong with Swagger 2.8.0?
  • Boris
    Boris over 6 years
    I see, maybe this is the Swagger issue?
  • Rahul Kargwal
    Rahul Kargwal over 6 years
    I am using 2.7.0 as well without any issues. Probably this is an issue what @Boris mentioned above.
  • Felipe Augusto
    Felipe Augusto over 5 years
    Welcome to Stackoverflow. Try to format your code properly as described here
  • Kalpesh Soni
    Kalpesh Soni over 5 years
    but he is using swagger ui, not curl
  • Evgeny Gorbovoy
    Evgeny Gorbovoy over 4 years
    @Boris In the link you've provided it does not say that it's impossible to use GET and body at same time. Http specification allows that and thus this topic is about swagger issue (swagger does not implement http properly)
  • Hamit YILDIRIM
    Hamit YILDIRIM over 4 years
    Perfect answer!
  • denisq
    denisq over 4 years
    Please provide the link to the source where you read that. Because in fact, the official specification allows the GET method to have the body.
  • Babbz77
    Babbz77 about 4 years
    For future visitors I was getting this as well using the ruby gem 'rswag' to setup swagger docs. To piggie back off the above answer, I fixed it by changing how the parameter is passed in using a different parameter method. There was one for body params and one for url params. I just had to change a piece from in: :body to in: :path.
  • Khalil Gharbaoui
    Khalil Gharbaoui almost 4 years
    @Boris I disagree with your answer. Because curl -d also known as --data flag does not care and yes you can pass data to it and yes it does work even on GET requests for example: curl -X GET "https://veggies.com/carrots" -H "Content-Type: application/json" -d "{\"bunny_id\": 22 }". Works perfectly for me because the API supports it and curl also does!. Now for the question of whether it is common or if we should do it that way is another story. curl has no issues with it in any case. I tried it. so the problem must be swagger's fetch function/method not curl -d
  • Khalil Gharbaoui
    Khalil Gharbaoui almost 4 years
  • Khalil Gharbaoui
    Khalil Gharbaoui almost 4 years
    @Babbz77 changing in: :body to in: :query also works! using the rswag ruby gem
  • Slobodan Savkovic
    Slobodan Savkovic almost 4 years
    CURL works fine when using the -d parameter as tested on Ubuntu with version 7.68. It is really Swagger that does not support GET request with body.
  • Soren
    Soren over 3 years
    The body could have information about what kind of data the user wants. I don't the that is a contradiction.
  • sɐunıɔןɐqɐp
    sɐunıɔןɐqɐp over 3 years
    From Review: Hi, this post does not seem to provide a quality answer to the question. Please either edit your answer and improve it, or just post it as a comment to the question/other answer.
  • Boris
    Boris over 3 years
    @Sören see GET - HTTP: "Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined. It is better to just avoid sending payloads in GET requests."
  • Nick Turner
    Nick Turner over 2 years
    @Boris this has been changed to accept a body in a Get request, or at least the specification has
  • Boris
    Boris over 2 years
    @NickTurner can you share a link please?
  • max
    max over 2 years
    I confirm that this works...however, I want to be able to use the body for GET request in swagger if possible.
  • Najeeb
    Najeeb about 2 years
    This worked! I don't know why the OP did not mark this an the correct answer.
  • NitinSingh
    NitinSingh about 2 years
    POST is used to create a new entity in the existing entity set.... A GET method accepting multiple input criteria can be issue when using query strings when the text associated with the input gets longer than URL limit..