Schema Definition
Schema Root
schema { query: Query mutation: Mutation }
Object Type
type User { id: ID! name: String! email: String }
Queries
Basic Query
query { user(id: "1") { name email } }
Named Query with Alias
query GetUsers { admin: user(role: ADMIN) { name } guest: user(role: GUEST) { name } }
Mutations
Basic Mutation
mutation { createUser(input: { name: "Alice" }) { id name } }
Input Types
input CreateUserInput { name: String! email: String }
Subscriptions
Basic Subscription
subscription { messageAdded(channel: "general") { text sender { name } } }
Overview
subscriptionReal-time data via WebSocket
Server pushServer sends updates to client
Single fieldOnly one root field per subscription
Types
Scalar Types
IntSigned 32-bit integer
FloatDouble-precision floating point
StringUTF-8 character sequence
Booleantrue or false
IDUnique identifier (serialized as String)
Type Modifiers
StringNullable string
String!Non-null string
[String]Nullable list of nullable strings
[String!]!Non-null list of non-null strings
Enum & Union
enum Role { ADMIN USER GUEST } union SearchResult = User | Post interface Node { id: ID! }
Arguments & Variables
Variables
query GetUser($id: ID!) { user(id: $id) { name } } # Variables: { "id": "123" }
Default Values
query GetUsers($limit: Int = 10) { users(limit: $limit) { name } }
Fragments
Named Fragment
fragment UserFields on User { id name email }
Using Fragments
query { user(id: "1") { ...UserFields } admin: user(id: "2") { ...UserFields } }
Inline Fragment
query { search(text: "a") { ... on User { name } ... on Post { title } } }
Directives
Built-in Directives
@include(if: Boolean!)Include field only when condition is true
@skip(if: Boolean!)Skip field when condition is true
@deprecated(reason: String)Mark field as deprecated
Usage Example
query GetUser($withEmail: Boolean!) { user(id: "1") { name email @include(if: $withEmail) } }
Introspection
Type Introspection
query { __type(name: "User") { name fields { name type { name } } } }
Schema Introspection
query { __schema { types { name kind } queryType { name } } }
Introspection Fields
__schemaQuery the schema's types and directives
__type(name:)Query a specific type by name
__typenameReturns the type name of any object
Common Patterns
Pagination (Relay-style)
query { users(first: 10, after: "cursor") { edges { node { name } cursor } pageInfo { hasNextPage } } }
Error Handling
{ "data": { "user": null }, "errors": [{ "message": "Not found", "path": ["user"] }] }
Best Practices
Name operationsAlways name queries and mutations
Use variablesNever interpolate values into query strings
Request only needed fieldsAvoid over-fetching with precise selections
Use fragmentsShare field sets across queries