Reputation: 249
I am new to graphql. I want to implement backend in spring boot using graphql. I am still confused about endpints. So if i have 2 entities user and product. so do i have to implement 2 endpoints
@RequestMapping(value="/graphql/user", method=RequestMethod.POST, produces = "application/json")
public GraphQLResponse<Object> getService(@RequestHeader HttpHeaders headers, @RequestBody GraphQLRequest graphql) {
GraphQLResponse<Object> execute = graphQLService.execute(headers, graphql);
return execute;
}
like this one for user and another one for product. or just one.
Upvotes: 2
Views: 5942
Reputation: 763
Graphql exposes only one endpoint and depending on your setup it may be accessible like this: http://localhost:8080/graphql
. Usually you never access graphql directly but rather via libraries that perform actions that allow you to communicate with graphql (like type-checking, converting between graphql types and your types and more).
Java GraphQL Kickstart is one of them and all you do is define schema and write resolvers for your queries, mutations and subscriptions:
schema {
query: Query
}
type Query {
allUsers: User
}
type User {
id: ID!
firstName: String
lastName: String!
}
And your resolver:
package your.project.resolvers;
import graphql.kickstart.tools.GraphQLQueryResolver;
import org.springframework.stereotype.Service;
import your.project.domain.persistence.User;
import your.project.repository.UserRepository;
import java.util.List;
@Service
public class UserResolver implements GraphQLQueryResolver {
private final UserRepository userRepository;
// be carefull about the name of this method
public List<User> allUsers() {
// perform actions based on your needs
return userRepository.findAll();
}
}
Notice that I'm using service annotation because this is basically performing some business logic on data retrieved from persistence layer. Also the name of the method allUsers()
in the UserResolver
is important. GraphQL will look for it based on your schema like this:
allUsers
get
: getAllUsers
Upvotes: 0
Reputation: 1715
With spring-boot-grpahql, there's no need to write controller at all. You just need to write ORM layer rest will be taken care by it.
Here's an example implementation of GraphQL in java using spring-boot, gradle, spring-jpa and mongo.
Upvotes: 1
Reputation: 161
No you need only one Endpoint. I suggest you to use this library. With this library it is very easy to start into the world of GraphQL: https://github.com/leangen/GraphQL-SPQR
And a good example with this library and Springboot you find here, just clone the repo and run it local: https://github.com/leangen/graphql-spqr-samples
Install this Plugin in Chrome to get read and query your schema easely: https://chrome.google.com/webstore/detail/chromeiql/fkkiamalmpiidkljmicmjfbieiclmeij
I hoped this answer helped you.
Upvotes: 3