GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data.
# Basic Query
query {
user(id: "1") {
id
name
email
}
}
# Query with Parameters
query getUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
# Nested Query
query {
user(id: "1") {
id
name
posts {
id
title
}
}
}
# Basic Mutation
mutation {
createUser(input: { name: "John", email: "john@example.com" }) {
id
name
email
}
}
# Mutation with Parameters
mutation createUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
}
}
# Basic Subscription
subscription {
userCreated {
id
name
email
}
}
# Subscription with Parameters
subscription onUserCreated($email: String) {
userCreated(email: $email) {
id
name
email
}
}
# Object Type
type User {
id: ID!
name: String!
email: String!
posts: [Post]
}
# Scalar Types
scalar Date
# Enum Type
enum Role {
ADMIN
USER
}
# Input Types
input CreateUserInput {
name: String!
email: String!
}
# Query Type
type Query {
user(id: ID!): User
users: [User]
}
# Mutation Type
type Mutation {
createUser(input: CreateUserInput!): User
}
# Subscription Type
type Subscription {
userCreated: User
}
query {
user(id: "1") {
id
name
email @include(if: $includeEmail)
}
}
query getUser($id: ID!, $includeEmail: Boolean = true) {
user(id: $id) {
id
name
email @include(if: $includeEmail)
}
}
Reusable units for query structures.
# Fragment Definition
fragment userFields on User {
id
name
email
}
# Using Fragments
query {
user(id: "1") {
...userFields
}
}
Errors in GraphQL are returned in the errors
field of the response.
{
"errors": [
{
"message": "User not found",
"locations": [{ "line": 2, "column": 3 }],
"path": ["user"]
}
],
"data": null
}