GraphQL Overview
Query
# Basic query
query {
user(id: "1") {
id
name
email
}
}
# Named query with variable
query GetUser($id: ID!) {
user(id: $id) {
id
name
posts {
title
createdAt
}
}
}
# Variables
{ "id": "42" }
Mutation
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
}
}
# Variables
{
"input": {
"name": "Alice",
"email": "alice@example.com",
"role": "ADMIN"
}
}
Subscription
subscription OnMessageAdded($roomId: ID!) {
messageAdded(roomId: $roomId) {
id
content
author {
name
}
createdAt
}
}
Fragments
fragment UserFields on User {
id
name
email
avatarUrl
}
query {
user(id: "1") {
...UserFields
}
admin(id: "2") {
...UserFields
permissions
}
}
# Inline fragment
query {
search(term: "Alice") {
... on User { name email }
... on Post { title body }
}
}
Directives
query GetUser($id: ID!, $showEmail: Boolean!) {
user(id: $id) {
name
email @include(if: $showEmail)
address @skip(if: $showEmail)
}
}
# @deprecated in schema
type User {
id: ID!
name: String!
username: String @deprecated(reason: "Use name instead")
}
Schema Definition Language
type Query {
user(id: ID!): User
users(limit: Int = 10, offset: Int = 0): [User!]!
}
type Mutation {
createUser(input: CreateUserInput!): User!
deleteUser(id: ID!): Boolean!
}
type User {
id: ID!
name: String!
email: String!
role: Role!
posts: [Post!]!
}
enum Role { ADMIN USER GUEST }
input CreateUserInput {
name: String!
email: String!
role: Role = USER
}
Scalar Types
| Type | Description |
|---|---|
| Int | 32-bit signed integer |
| Float | Double-precision floating point |
| String | UTF-8 character sequence |
| Boolean | true or false |
| ID | Unique identifier (serialized as String) |