Examples
Four small examples that cover the surface area you actually use: schema, query, mutation, subscription.
GraphQL by example
EXAMPLE
# 1. Schema (SDL)
type User {
id: ID!
email: String!
posts(first: Int = 10, after: String): PostConnection!
}
type Post {
id: ID!
title: String!
body: String!
author: User!
publishedAt: DateTime
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
}
type PostEdge { node: Post!; cursor: String! }
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
scalar DateTime
type Query {
me: User
post(id: ID!): Post
}
type Mutation {
createPost(input: CreatePostInput!): CreatePostPayload!
}
input CreatePostInput {
title: String!
body: String!
}
type CreatePostPayload {
post: Post
errors: [UserError!]!
}
type UserError {
field: String
code: String!
message: String!
}
type Subscription {
postCreated: Post!
}
# 2. Query
query MyFeed($count: Int = 5, $cursor: String) {
me {
id
email
posts(first: $count, after: $cursor) {
edges {
cursor
node { id title publishedAt }
}
pageInfo { hasNextPage endCursor }
}
}
}
# 3. Mutation
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
post { id title }
errors { field code message }
}
}
# Variables
# { 'input': { 'title': 'Hello', 'body': 'World' } }
# 4. Subscription (WebSocket)
subscription NewPosts {
postCreated {
id
title
author { email }
}
}
Why it matters
Lean on connections for lists, mutation payloads for errors, and small input types. Subscriptions are the GraphQL feature most teams over-reach for - use them for genuine push (notifications, live counters), not for replacing polling everywhere.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…