Attempt to use GraphQL java library to build GraphQL server using spring boot.MongoDB is used as a storage.
resources/schema.graphqls
contains GraphQL schema defination for query,resolver and types
- Unit tests runs using
gradle clean test
- Make sure you have mongo installed on your machine.App will connect on port
27017
by default. - Start mongoDB using
mongo
command. - Embedded tomcat of spring boot starts using
gradle bootRun
-
Fetch all blogs :
http://localhost:8080/graphql
POST Endpoint. Request body format :{ "query": "{allBlogs{title}}" }
-
It sounds little stupid here to fetch all blogs using
POST
http method but it is used so we can pass query as a part of request body. We can change is toGET
and pass actual query as query param. -
Resonse that you will get is :
{ "allBlogs": [ { "title": "REST in peace.GraphQL live long" }, { "title": "Kotlin for Android" } ] }
-
Lets add one more parameter to request body i.e content
{ "query": "{allBlogs{title content}}" }
-
Response :
{ "allBlogs": [ { "title": "REST in peace.GraphQL live long", "content": "GraphQL dominating now days" }, { "title": "Kotlin for Android", "content": "how useful is kotlin for android dev" } ] }
-
GraphQL provides feature of Mutation which let us create new enitity.
-
Create Blog:
http:/localhost:8080/graphql
. Request Body:{ "query": "mutation createBlog {createBlog(title:\"hello\",content:\"world\") {title content}}" }
-
Response:
{ "createBlog": { "title": "hello", "content": "world" } }
-
If you now again Query all blogs response would be
{ "allBlogs": [ { "title": "REST in peace.GraphQL live long", "content": "GraphQL dominating now days" }, { "title": "Kotlin for Android", "content": "how useful is kotlin for android dev" }, { "title": "hello", "content": "world" } ] }