GraphQL is a query language for APIs and a runtime for executing those queries with existing data. Below is a GraphQL cheat sheet covering common operations and syntax:
Basics
Query Example:
query {
user(id: 1) {
name
email
}
}
Mutation Example:
mutation {
createUser(input: { name: "John", email: "[email protected]" }) {
id
name
email
}
}
Fields and Selection Sets
Specify Fields in Query:
query {
user(id: 1) {
name
email
}
}
Nested Fields:
query {
user(id: 1) {
name
posts {
title
body
}
}
}
Query Parameters
Query with Variables:
query($userId: Int!) {
user(id: $userId) {
name
email
}
}
Default Values for Variables:
query($userId: Int = 1) {
user(id: $userId) {
name
email
}
}
Aliases
Use Aliases to Rename Fields:
query {
firstUser: user(id: 1) {
name
}
secondUser: user(id: 2) {
name
}
}
Fragments
Define a Fragment:
fragment UserInfo on User {
name
email
}
Use Fragment in Query:
query {
user(id: 1) {
...UserInfo
}
}
Directives
Conditional Fields with @include:
query($showEmail: Boolean!) {
user(id: 1) {
name
email @include(if: $showEmail)
}
}
Skip Fields with @skip:
query($skipEmail: Boolean!) {
user(id: 1) {
name
email @skip(if: $skipEmail)
}
}
Enums
Query with Enum:
query {
posts(status: PUBLISHED) {
title
}
}
Pagination
Cursor-Based Pagination:
query {
posts(first: 10, after: "cursor") {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
title
}
cursor
}
}
}
Subscriptions
Subscribe to Real-Time Updates:
subscription {
newPost {
title
author
}
}
Schema Definition
Define Types and Fields in Schema:
type User {
id: ID!
name: String!
email: String!
}
type Query {
user(id: ID!): User
users: [User]
}
type Mutation {
createUser(input: UserInput): User
}
input UserInput {
name: String!
email: String!
}
Scalar Types:
- Int, Float, String, Boolean, ID.
This cheat sheet provides a quick reference for common GraphQL operations and syntax. GraphQL is highly flexible, and its usage can vary depending on the specific schema and requirements. Always refer to the official GraphQL documentation for more detailed information and advanced features.