GraphQL Queries and Mutations
GraphQL Queries
Standard Query
Use the standard query to get all Posts out of your database:
- Query:
query{
posts{
title
author{
name
}
}
}
- Response:
"data": {
"posts": [
{
"title": "First Post",
"author": {
"name": "Author Name"
}
},
{
"title": "Second Post",
"author": {
"name": "Author Name"
}
},
{
"title": "Third Post",
"author": {
"name": "Author Name"
}
}
]
}
Aliases
Use aliases to query for multiple separate posts:
- Query:
query{
firstquery: post(id:2){
title
author{
name
}
}
secondquery: post(id:3){
title
author{
name
}
}
}
- Response:
"data": {
"firstquery": {
"title": "Second Post",
"author": {
"name": "Author Name"
}
},
"secondquery": {
"title": "Third Post",
"author": {
"name": "Author Name"
}
}
}
Fragments
Use fragments to shorten your queries:
- Query:
query{
firstquery: post(id:2){
...basicPostDetails
}
secondquery: post(id:3){
...basicPostDetails
}
}
fragment basicPostDetails on Post{
title
author{
name
}
}
- Response:
"data": {
"firstquery": {
"title": "Second Post",
"author": {
"name": "Author Name"
}
},
"secondquery": {
"title": "Third Post",
"author": {
"name": "Author Name"
}
}
}
Variables
Use fragments to shorten your queries - the query variable has to be send alongside, e.g. user clicked on post number two -> {"postID": 2}
:
- Query:
query($postId: Int!) {
post(id:$postId){
...basicPostDetails
}
}
fragment basicPostDetails on Post{
title
author{
name
}
}
- Response:
{
"data": {
"post": {
"title": "Second Post",
"author": {
"name": "Author Name"
}
}
}
}
Mutations
Queries retrieve data from your database. A mutation can be used to make changes to your data - e.g. add a post:
- Query:
mutation {
addPost( post: {
title: "New Post",
content: "Post content",
author: "sd35xzdfg"
}){
title,
author: {
name
}
}
}
- Response:
{
"data": {
"post": {
"title": "New Post",
"author": {
"name": "Author Name"
}
}
}
}
Mutations with Variables
With a variable the new post data has to be passed along as a javascript object, e.g.:
{"post": {
"title": "New Post",
"content": "Post content",
"author": "sd35xzdfg"
}
}
- Query:
mutation ($post: PostInput!) {
addPost( post: $post){
title,
author: {
name
}
}
}
- Response:
{
"data": {
"post": {
"title": "New Post",
"author": {
"name": "Author Name"
}
}
}
}