GraphQL API Design
This skill enables an AI agent to design complete GraphQL APIs from specifications, schemas, or natural language descriptions. The agent produces type definitions, queries, mutations, subscriptions, input types, enums, and resolver implementations. It applies performance patterns including DataLoader for N+1 prevention, cursor-based pagination via the Relay connection spec, query depth limiting, and schema federation for microservice architectures.
Workflow
Model the domain as types: Analyze the application domain and define GraphQL object types, input types, enums, interfaces, and unions. Each type should represent a real entity with fields that match the data consumers actually need. Use non-nullable (!) annotations deliberately—fields that can genuinely be absent should be nullable. Prefer specific scalar types (e.g., DateTime, URL) over raw String for self-documenting schemas.
Design queries and mutations: Define Query fields for read operations and Mutation fields for write operations. Queries should be noun-based (user, posts) while mutations should be verb-based (createPost, updateUser). Each mutation should accept a single input type argument and return a payload type that includes the modified object plus any user-facing errors. This pattern keeps mutations consistent and extensible.
Implement pagination with connections: For any list field that could return many items, use the Relay connection specification with edges, node, cursor, and pageInfo. This provides cursor-based pagination that is stable under insertions and deletions, unlike offset-based pagination. Define reusable connection types per entity rather than returning raw arrays.
Write resolvers with DataLoader: Implement resolvers that use DataLoader to batch and cache database lookups within a single request. Without DataLoader, a query that fetches 50 posts and their authors would make 50 separate author queries (the N+1 problem). DataLoader collapses these into a single batched query. Create a new DataLoader instance per request to avoid leaking data between users.
Add subscriptions for real-time data: Define Subscription fields for events clients need to react to in real-time (e.g., new messages, status changes). Use a pub/sub backend (Redis, Kafka, or in-memory for development) to publish events. Keep subscription payloads lean—clients can use the subscription trigger to refetch full data if needed.
Secure and optimize the schema: Add query depth limiting (max 10-15 levels) and query complexity analysis to prevent abusive queries. Implement field-level authorization in resolvers. Use persisted queries in production to reduce bandwidth and prevent arbitrary query execution. Consider schema federation if the API spans multiple services.
Supported Technologies
- Servers: Apollo Server, GraphQL Yoga, Mercurius (Fastify), Strawberry (Python), graphql-java
- Schema tools: SDL-first (typeDefs), code-first (TypeGraphQL, Nexus, Pothos)
- Performance: DataLoader, @defer/@stream directives, persisted queries, automatic persisted queries (APQ)
- Federation: Apollo Federation, GraphQL Mesh, Schema Stitching
- Testing: GraphQL Playground, Apollo Studio, graphql-test (jest), Insomnia
Usage
Provide the agent with a description of the data entities, their relationships, and the operations needed. The agent will produce a complete SDL schema, resolver implementations, and DataLoader setup. Specify whether you want SDL-first or code-first output, and which server framework to target.
Examples
Example 1: Blog Platform Schema with Resolvers
# schema.graphql — Complete blog platform schema
scalar DateTime
enum PostStatus {
DRAFT
PUBLISHED
ARCHIVED
}
type User {
id: ID!
username: String!
email: String!
bio: String
avatarUrl: String
posts(first: Int, after: String): PostConnection!
createdAt: DateTime!
}
type Post {
id: ID!
title: String!
slug: String!
content: String!
excerpt: String
status: PostStatus!
author: User!
tags: [Tag!]!
comments(first: Int, after: String): CommentConnection!
publishedAt: DateTime
createdAt: DateTime!
updatedAt: DateTime!
}
type Comment {
id: ID!
body: String!
author: User!
post: Post!
createdAt: DateTime!
}
type Tag {
id: ID!
name: String!
slug: String!
posts(first: Int, after: String): PostConnection!
}
# Relay connection types for cursor-based pagination
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type PostEdge {
cursor: String!
node: Post!
}
type CommentConnection {
edges: [CommentEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type CommentEdge {
cursor: String!
node: Comment!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
# Queries
type Query {
post(id: ID, slug: String): Post
posts(
first: Int = 10
after: String
status: PostStatus
tagSlug: String
): PostConnection!
user(id: ID!): User
me: User
tags: [Tag!]!
}
# Mutations with input types and payload types
input CreatePostInput {
title: String!
content: String!
tagIds: [ID!]
status: PostStatus = DRAFT
}
type CreatePostPayload {
post: Post
errors: [MutationError!]!
}
input UpdatePostInput {
title: String
content: String
status: PostStatus
tagIds: [ID!]
}
type UpdatePostPayload {
post: Post
errors: [MutationError!]!
}
type MutationError {
field: String
message: String!
}
type Mutation {
createPost(input: CreatePostInput!): CreatePostPayload!
updatePost(id: ID!, input: UpdatePostInput!): UpdatePostPayload!
deletePost(id: ID!): Boolean!
addComment(postId: ID!, body: String!): Comment!
}
# Subscriptions
type Subscription {
commentAdded(postId: ID!): Comment!
postPublished: Post!
}
// resolvers.js — Resolvers with DataLoader for N+1 prevention
const DataLoader = require("dataloader");
// Create loaders per request (called from context factory)
function createLoaders(db) {
return {
userLoader: new DataLoader(async (userIds) => {
const users = await db.users.findByIds(userIds);
const userMap = new Map(users.map((u) => [u.id, u]));
return userIds.map((id) => userMap.get(id) || null);
}),
postLoader: new DataLoader(async (postIds) => {
const posts = await db.posts.findByIds(postIds);
const postMap = new Map(posts.map((p) => [p.id, p]));
return postIds.map((id) => postMap.get(id) || null);
}),
};
}
const resolvers = {
Query: {
post: (_, { id, slug }, { db }) => {
if (id) return db.posts.findById(id);
if (slug) return db.posts.findBySlug(slug);
return null;
},
posts: async (_, { first = 10, after, status, tagSlug }, { db }) => {
const cursor = after ? decodeCursor(after) : null;
const { rows, totalCount } = await db.posts.findPaginated({
limit: first + 1,
cursor,
status,
tagSlug,
});
const hasNextPage = rows.length > first;
const edges = rows.slice(0, first).map((post) => ({
cursor: encodeCursor(post.id),
node: post,
}));
return {
edges,
totalCount,
pageInfo: {
hasNextPage,
hasPreviousPage: !!after,
startCursor: edges[0]?.cursor || null,
endCursor: edges[edges.length - 1]?.cursor || null,
},
};
},
me: (_, __, { currentUser }) => currentUser,
},
Post: {
author: (post, _, { loaders }) => loaders.userLoader.load(post.authorId),
tags: (post, _, { db }) => db.tags.findByPostId(post.id),
},
Comment: {
author: (comment, _, { loaders }) => loaders.userLoader.load(comment.authorId),
},
Mutation: {
createPost: async (_, { input }, { currentUser, db }) => {
if (!currentUser) return { post: null, errors: [{ message: "Not authenticated" }] };
if (!input.title.trim()) {
return { post: null, errors: [{ field: "title", message: "Title cannot be empty" }] };
}
const post = await db.posts.create({ ...input, authorId: currentUser.id });
return { post, errors: [] };
},
},
};
function encodeCursor(id) { return Buffer.from(`cursor:${id}`).toString("base64"); }
function decodeCursor(cursor) { return Buffer.from(cursor, "base64").toString().replace("cursor:", ""); }
Example 2: Cursor-Based Pagination Implementation
// pagination.js — Reusable cursor-based pagination for any entity
/**
* Generic paginated query builder for SQL databases.
* Works with any table that has an auto-incrementing or sortable ID.
*/
async function paginatedQuery(db, { table, first = 10, after, where = {} }) {
const limit = Math.min(first, 100); // Cap at 100 per page
const conditions = [];
const params = [];
// Apply cursor (decode to original ID)
if (after) {
const cursorId = Buffer.from(after, "base64").toString().split(":")[1];
conditions.push(`id < $${params.length + 1}`);
params.push(cursorId);
}
// Apply additional filters
for (const [key, value] of Object.entries(where)) {
if (value !== undefined) {
conditions.push(`${key} = $${params.length + 1}`);
params.push(value);
}
}
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
// Fetch one extra row to determine hasNextPage
const query = `SELECT * FROM ${table} ${whereClause} ORDER BY id DESC LIMIT ${limit + 1}`;
const rows = await db.query(query, params);
// Count total matching rows
const countQuery = `SELECT COUNT(*) as total FROM ${table} ${whereClause}`;
const [{ total: totalCount }] = await db.query(countQuery, params);
const hasNextPage = rows.length > limit;
const nodes = rows.slice(0, limit);
const edges = nodes.map((node) => ({
cursor: Buffer.from(`cursor:${node.id}`).toString("base64"),
node,
}));
return {
edges,
totalCount,
pageInfo: {
hasNextPage,
hasPreviousPage: !!after,
startCursor: edges[0]?.cursor || null,
endCursor: edges[edges.length - 1]?.cursor || null,
},
};
}
// Usage in resolver
const resolvers = {
Query: {
posts: (_, args, { db }) =>
paginatedQuery(db, {
table: "posts",
first: args.first,
after: args.after,
where: { status: args.status },
}),
},
};
Best Practices
- Keep mutations consistent by always using a single
input argument and returning a payload type with both the result and a list of user-facing errors. This makes client code predictable.
- Solve N+1 with DataLoader on every relationship resolver. Create DataLoader instances per-request (in the context factory) to avoid leaking cached data between users or requests.
- Limit query depth and complexity to prevent denial-of-service attacks. Set max depth to 10-15 and assign complexity costs to fields (especially connections and nested relationships).
- Use nullable return types for single-entity queries (
post(id: ID!): Post returns null if not found) and non-nullable arrays for list queries (tags: [Tag!]! always returns an array, possibly empty).
- Version via schema evolution, not URL versioning. Add new fields freely (non-breaking), deprecate old fields with
@deprecated(reason: "Use newField instead"), and remove them after clients have migrated.
- Use input types for all mutation arguments rather than passing individual scalar arguments. This makes it easy to add optional fields later without breaking existing clients.
Edge Cases
- Circular references: Types like
User -> Posts -> Author -> Posts create circular schemas. This is valid in GraphQL but requires depth limiting to prevent infinite queries. DataLoader prevents infinite resolution loops.
- Null propagation: If a non-nullable field resolver throws an error, the null propagates upward to the nearest nullable parent. Design nullable boundaries carefully to prevent one field error from nullifying an entire response.
- Empty connections: Return
{ edges: [], pageInfo: { hasNextPage: false, hasPreviousPage: false }, totalCount: 0 } for empty result sets, not null.
- Cursor stability: Cursors should be opaque and stable across insertions. Using row IDs as cursor values (base64 encoded) is stable; using offsets is not and breaks when items are inserted or deleted.
- File uploads: GraphQL doesn't natively support file uploads. Use the multipart request spec (
graphql-upload) or handle uploads via a separate REST endpoint and pass the resulting URL to a mutation.
- Subscription connection drops: Clients can lose WebSocket connections. Design subscriptions so clients can recover state by re-querying on reconnect rather than relying solely on the subscription stream.
1---2name: graphql-api-design3description: Design GraphQL APIs with well-structured schemas, efficient resolvers, pagination, and performance patterns like DataLoader and federation. Use when the user requests graphql api design or provides relevant inputs for this workflow.4license: MIT5metadata:6 source: https://skillmd.com/skills/seb1n/graphql-api-design7 author: awesome-ai-agent-skills8 version: 1.0.09---1011# GraphQL API Design1213This skill enables an AI agent to design complete GraphQL APIs from specifications, schemas, or natural language descriptions. The agent produces type definitions, queries, mutations, subscriptions, input types, enums, and resolver implementations. It applies performance patterns including DataLoader for N+1 prevention, cursor-based pagination via the Relay connection spec, query depth limiting, and schema federation for microservice architectures.1415## Workflow16171. **Model the domain as types:** Analyze the application domain and define GraphQL object types, input types, enums, interfaces, and unions. Each type should represent a real entity with fields that match the data consumers actually need. Use non-nullable (`!`) annotations deliberately—fields that can genuinely be absent should be nullable. Prefer specific scalar types (e.g., `DateTime`, `URL`) over raw `String` for self-documenting schemas.18192. **Design queries and mutations:** Define Query fields for read operations and Mutation fields for write operations. Queries should be noun-based (`user`, `posts`) while mutations should be verb-based (`createPost`, `updateUser`). Each mutation should accept a single input type argument and return a payload type that includes the modified object plus any user-facing errors. This pattern keeps mutations consistent and extensible.20213. **Implement pagination with connections:** For any list field that could return many items, use the Relay connection specification with `edges`, `node`, `cursor`, and `pageInfo`. This provides cursor-based pagination that is stable under insertions and deletions, unlike offset-based pagination. Define reusable connection types per entity rather than returning raw arrays.22234. **Write resolvers with DataLoader:** Implement resolvers that use DataLoader to batch and cache database lookups within a single request. Without DataLoader, a query that fetches 50 posts and their authors would make 50 separate author queries (the N+1 problem). DataLoader collapses these into a single batched query. Create a new DataLoader instance per request to avoid leaking data between users.24255. **Add subscriptions for real-time data:** Define Subscription fields for events clients need to react to in real-time (e.g., new messages, status changes). Use a pub/sub backend (Redis, Kafka, or in-memory for development) to publish events. Keep subscription payloads lean—clients can use the subscription trigger to refetch full data if needed.26276. **Secure and optimize the schema:** Add query depth limiting (max 10-15 levels) and query complexity analysis to prevent abusive queries. Implement field-level authorization in resolvers. Use persisted queries in production to reduce bandwidth and prevent arbitrary query execution. Consider schema federation if the API spans multiple services.2829## Supported Technologies3031- **Servers:** Apollo Server, GraphQL Yoga, Mercurius (Fastify), Strawberry (Python), graphql-java32- **Schema tools:** SDL-first (typeDefs), code-first (TypeGraphQL, Nexus, Pothos)33- **Performance:** DataLoader, @defer/@stream directives, persisted queries, automatic persisted queries (APQ)34- **Federation:** Apollo Federation, GraphQL Mesh, Schema Stitching35- **Testing:** GraphQL Playground, Apollo Studio, graphql-test (jest), Insomnia3637## Usage3839Provide the agent with a description of the data entities, their relationships, and the operations needed. The agent will produce a complete SDL schema, resolver implementations, and DataLoader setup. Specify whether you want SDL-first or code-first output, and which server framework to target.4041## Examples4243### Example 1: Blog Platform Schema with Resolvers4445```graphql46# schema.graphql — Complete blog platform schema4748scalar DateTime4950enum PostStatus {51 DRAFT52 PUBLISHED53 ARCHIVED54}5556type User {57 id: ID!58 username: String!59 email: String!60 bio: String61 avatarUrl: String62 posts(first: Int, after: String): PostConnection!63 createdAt: DateTime!64}6566type Post {67 id: ID!68 title: String!69 slug: String!70 content: String!71 excerpt: String72 status: PostStatus!73 author: User!74 tags: [Tag!]!75 comments(first: Int, after: String): CommentConnection!76 publishedAt: DateTime77 createdAt: DateTime!78 updatedAt: DateTime!79}8081type Comment {82 id: ID!83 body: String!84 author: User!85 post: Post!86 createdAt: DateTime!87}8889type Tag {90 id: ID!91 name: String!92 slug: String!93 posts(first: Int, after: String): PostConnection!94}9596# Relay connection types for cursor-based pagination97type PostConnection {98 edges: [PostEdge!]!99 pageInfo: PageInfo!100 totalCount: Int!101}102103type PostEdge {104 cursor: String!105 node: Post!106}107108type CommentConnection {109 edges: [CommentEdge!]!110 pageInfo: PageInfo!111 totalCount: Int!112}113114type CommentEdge {115 cursor: String!116 node: Comment!117}118119type PageInfo {120 hasNextPage: Boolean!121 hasPreviousPage: Boolean!122 startCursor: String123 endCursor: String124}125126# Queries127type Query {128 post(id: ID, slug: String): Post129 posts(130 first: Int = 10131 after: String132 status: PostStatus133 tagSlug: String134 ): PostConnection!135 user(id: ID!): User136 me: User137 tags: [Tag!]!138}139140# Mutations with input types and payload types141input CreatePostInput {142 title: String!143 content: String!144 tagIds: [ID!]145 status: PostStatus = DRAFT146}147148type CreatePostPayload {149 post: Post150 errors: [MutationError!]!151}152153input UpdatePostInput {154 title: String155 content: String156 status: PostStatus157 tagIds: [ID!]158}159160type UpdatePostPayload {161 post: Post162 errors: [MutationError!]!163}164165type MutationError {166 field: String167 message: String!168}169170type Mutation {171 createPost(input: CreatePostInput!): CreatePostPayload!172 updatePost(id: ID!, input: UpdatePostInput!): UpdatePostPayload!173 deletePost(id: ID!): Boolean!174 addComment(postId: ID!, body: String!): Comment!175}176177# Subscriptions178type Subscription {179 commentAdded(postId: ID!): Comment!180 postPublished: Post!181}182```183184```javascript185// resolvers.js — Resolvers with DataLoader for N+1 prevention186const DataLoader = require("dataloader");187188// Create loaders per request (called from context factory)189function createLoaders(db) {190 return {191 userLoader: new DataLoader(async (userIds) => {192 const users = await db.users.findByIds(userIds);193 const userMap = new Map(users.map((u) => [u.id, u]));194 return userIds.map((id) => userMap.get(id) || null);195 }),196 postLoader: new DataLoader(async (postIds) => {197 const posts = await db.posts.findByIds(postIds);198 const postMap = new Map(posts.map((p) => [p.id, p]));199 return postIds.map((id) => postMap.get(id) || null);200 }),201 };202}203204const resolvers = {205 Query: {206 post: (_, { id, slug }, { db }) => {207 if (id) return db.posts.findById(id);208 if (slug) return db.posts.findBySlug(slug);209 return null;210 },211 posts: async (_, { first = 10, after, status, tagSlug }, { db }) => {212 const cursor = after ? decodeCursor(after) : null;213 const { rows, totalCount } = await db.posts.findPaginated({214 limit: first + 1,215 cursor,216 status,217 tagSlug,218 });219 const hasNextPage = rows.length > first;220 const edges = rows.slice(0, first).map((post) => ({221 cursor: encodeCursor(post.id),222 node: post,223 }));224 return {225 edges,226 totalCount,227 pageInfo: {228 hasNextPage,229 hasPreviousPage: !!after,230 startCursor: edges[0]?.cursor || null,231 endCursor: edges[edges.length - 1]?.cursor || null,232 },233 };234 },235 me: (_, __, { currentUser }) => currentUser,236 },237 Post: {238 author: (post, _, { loaders }) => loaders.userLoader.load(post.authorId),239 tags: (post, _, { db }) => db.tags.findByPostId(post.id),240 },241 Comment: {242 author: (comment, _, { loaders }) => loaders.userLoader.load(comment.authorId),243 },244 Mutation: {245 createPost: async (_, { input }, { currentUser, db }) => {246 if (!currentUser) return { post: null, errors: [{ message: "Not authenticated" }] };247 if (!input.title.trim()) {248 return { post: null, errors: [{ field: "title", message: "Title cannot be empty" }] };249 }250 const post = await db.posts.create({ ...input, authorId: currentUser.id });251 return { post, errors: [] };252 },253 },254};255256function encodeCursor(id) { return Buffer.from(`cursor:${id}`).toString("base64"); }257function decodeCursor(cursor) { return Buffer.from(cursor, "base64").toString().replace("cursor:", ""); }258```259260### Example 2: Cursor-Based Pagination Implementation261262```javascript263// pagination.js — Reusable cursor-based pagination for any entity264265/**266 * Generic paginated query builder for SQL databases.267 * Works with any table that has an auto-incrementing or sortable ID.268 */269async function paginatedQuery(db, { table, first = 10, after, where = {} }) {270 const limit = Math.min(first, 100); // Cap at 100 per page271 const conditions = [];272 const params = [];273274 // Apply cursor (decode to original ID)275 if (after) {276 const cursorId = Buffer.from(after, "base64").toString().split(":")[1];277 conditions.push(`id < $${params.length + 1}`);278 params.push(cursorId);279 }280281 // Apply additional filters282 for (const [key, value] of Object.entries(where)) {283 if (value !== undefined) {284 conditions.push(`${key} = $${params.length + 1}`);285 params.push(value);286 }287 }288289 const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";290291 // Fetch one extra row to determine hasNextPage292 const query = `SELECT * FROM ${table} ${whereClause} ORDER BY id DESC LIMIT ${limit + 1}`;293 const rows = await db.query(query, params);294295 // Count total matching rows296 const countQuery = `SELECT COUNT(*) as total FROM ${table} ${whereClause}`;297 const [{ total: totalCount }] = await db.query(countQuery, params);298299 const hasNextPage = rows.length > limit;300 const nodes = rows.slice(0, limit);301302 const edges = nodes.map((node) => ({303 cursor: Buffer.from(`cursor:${node.id}`).toString("base64"),304 node,305 }));306307 return {308 edges,309 totalCount,310 pageInfo: {311 hasNextPage,312 hasPreviousPage: !!after,313 startCursor: edges[0]?.cursor || null,314 endCursor: edges[edges.length - 1]?.cursor || null,315 },316 };317}318319// Usage in resolver320const resolvers = {321 Query: {322 posts: (_, args, { db }) =>323 paginatedQuery(db, {324 table: "posts",325 first: args.first,326 after: args.after,327 where: { status: args.status },328 }),329 },330};331```332333## Best Practices334335- **Keep mutations consistent** by always using a single `input` argument and returning a payload type with both the result and a list of user-facing errors. This makes client code predictable.336- **Solve N+1 with DataLoader** on every relationship resolver. Create DataLoader instances per-request (in the context factory) to avoid leaking cached data between users or requests.337- **Limit query depth and complexity** to prevent denial-of-service attacks. Set max depth to 10-15 and assign complexity costs to fields (especially connections and nested relationships).338- **Use nullable return types for single-entity queries** (`post(id: ID!): Post` returns `null` if not found) and non-nullable arrays for list queries (`tags: [Tag!]!` always returns an array, possibly empty).339- **Version via schema evolution, not URL versioning.** Add new fields freely (non-breaking), deprecate old fields with `@deprecated(reason: "Use newField instead")`, and remove them after clients have migrated.340- **Use input types for all mutation arguments** rather than passing individual scalar arguments. This makes it easy to add optional fields later without breaking existing clients.341342## Edge Cases343344- **Circular references:** Types like `User -> Posts -> Author -> Posts` create circular schemas. This is valid in GraphQL but requires depth limiting to prevent infinite queries. DataLoader prevents infinite resolution loops.345- **Null propagation:** If a non-nullable field resolver throws an error, the null propagates upward to the nearest nullable parent. Design nullable boundaries carefully to prevent one field error from nullifying an entire response.346- **Empty connections:** Return `{ edges: [], pageInfo: { hasNextPage: false, hasPreviousPage: false }, totalCount: 0 }` for empty result sets, not `null`.347- **Cursor stability:** Cursors should be opaque and stable across insertions. Using row IDs as cursor values (base64 encoded) is stable; using offsets is not and breaks when items are inserted or deleted.348- **File uploads:** GraphQL doesn't natively support file uploads. Use the multipart request spec (`graphql-upload`) or handle uploads via a separate REST endpoint and pass the resulting URL to a mutation.349- **Subscription connection drops:** Clients can lose WebSocket connections. Design subscriptions so clients can recover state by re-querying on reconnect rather than relying solely on the subscription stream.