I had some trouble setting up graphql in a spring boot project and I wanted to make a checklist for anyone trying to set this up as well. My answer is down below:
Add graphql dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Create .graphqls file:
type Query {
myQuery(firstName: String): Obj
}
type Obj {
name: String
description: String
}
Create Object
public class Obj
{
private String name;
private String description;
...
}
Create Controller
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
@Controller
public class AttractionsGraphql {
private final DAO yourDatabaseAccessObject;
@QueryMapping
public Obj myQuery(@Argument String firstName) {
return yourDatabaseAccessObject.getObj(firstName);
}
}
Add this to your application.properties file to use the graphql ui to call your endpoint:
spring.graphql.graphiql.enabled=true
Start up your app and you can test your endpoint at http://localhost:8080/graphiql?path=/graphql with the graphql ui.
Hitting [shift + space] in the query window you can see what possible parameters you can get from your schema. Here's an example query:
query whateverName {
myQuery (firstName: "bob") {
name
description
}
}
Hope this helps! These two sites helped me figure this out:
If your object has a nested object you'd need to make a method with an @SchemaMapping in your controller. The links above go into that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With