Search code examples
springspring-bootgraphqlspring-graphql

Method not allowed error for GraphQL requests with Spring


I have a Java Spring web server that I want to force to use Spring's GraphQL library over GraphQL's own Java library so that I can manage the access to individual queries/mutations.

After following a guide online on how to do that, I have the following dependencies in my pom.xml:

...
<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.7.3</version>
</parent>
...
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-graphql</artifactId>
    <version>2.7.3</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.7.3</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>2.7.3</version>
</dependency>

This is the simple controller I set up

@Controller
public class GraphQLController {

    private MyObject obj;

    public GraphQLController(MyObject obj) {
        this.obj = obj;
    }

    @SchemaMapping
    public Query query(){
        return new Query(obj);
    }

    @SchemaMapping
    public Mutation mutation(Path path){
        return new Mutation(obj, path);
    }
}

However, no matter the GraphQL request I am sending to the server, I always get the same response:

{
  "timestamp": "2022-08-29T07:59:09.470+00:00",
  "status": 405,
  "error": "Method Not Allowed",
  "path": "/graphql"
}

I'm pasting here the properties file just in case.

graphql.servlet.corsEnabled=false
graphql.servlet.mapping=/graphql

I also tried using

@RestController
@RequestMapping(value="/graphql", method = {RequestMethod.POST, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.PUT}, path = "/graphql",
        consumes = "application/json", produces = "application/json")
class GraphQLController {...

but with no success.

# Schema
type Query{
    listProjects: [Project]
...
}

# Query I'm sending to localhost:8080/graphql
query {
    listProjects {
        name
    }
}

I'm no expert of Spring and this has been bugging me for the past couple of days, can anyone help? Many thanks!


Solution

  • As pointed out by @NilsHartmann in the comments, the problem was that I had the schema file under src/main/resources/ instead of src/main/resources/graphql.