graphql-api-design
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.
git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills /tmp/graphql-api-design && cp -r /tmp/graphql-api-design/api-and-integration/graphql-api-design ~/.claude/skills/graphql-api-designSKILL.md
# 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
1. **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.
2. **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.
3. **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.
4. **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.
5. **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.
6. **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
```graphql
# 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!
}
```
```javascript
// resolvers.js — Resolvers with DataLoader forDesign reproducible evaluations for AI agents with representative task sets, explicit rubrics, appropriate graders, baselines, regression gates, and failure analysis. Use when defining agent quality, comparing prompts or models, validating a release, measuring tool-use reliability, investigating regressions, or deciding whether an agent is ready for production.
Design privacy-aware observability for AI agents using traces, spans, structured events, metrics, cost attribution, dashboards, alerts, and investigation workflows. Use when instrumenting an agent, debugging intermittent tool or model failures, defining service-level objectives, analyzing latency or spend, auditing agent decisions, or preparing production monitoring.
Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows. Use when deciding which agent actions require review, adding approve/reject or dual-control flows, preventing unauthorized autonomous effects, creating decision records, reducing rubber-stamping, or recovering safely from rejected, expired, or failed actions.
Design, implement, harden, and verify Model Context Protocol (MCP) servers with precise tool contracts, least-privilege authorization, safe transports, structured errors, and interoperability tests. Use when creating a new MCP server, exposing an API or data source through MCP, reviewing an MCP server design, adding or revising MCP tools, or preparing an MCP server for production.
Design and operate bounded multi-agent workflows with task decomposition, dependency graphs, ownership, handoff contracts, shared-state controls, approvals, recovery, and synthesis. Use when a task contains genuinely independent workstreams, specialized roles, parallel research or implementation, reviewer-worker loops, or coordination problems that one agent should not execute sequentially.
Design and validate model-facing tool definitions with clear names, action-oriented descriptions, bounded JSON Schema parameters, explicit side effects, safe defaults, idempotency, errors, and realistic tests. Use when creating function-calling tools, MCP tools, agent actions, structured tool inputs, or when a model selects the wrong tool, invents arguments, or causes unsafe side effects.
Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings. Use when defining red-team rules of engagement, assessing prompt injection or excessive agency, testing tool and identity boundaries, evaluating memory or cross-agent attacks, scoring a campaign, or verifying remediation in an approved environment.
Threat-model and harden AI agents, RAG systems, assistants, and tool-using workflows against direct, indirect, stored, cross-agent, and multimodal prompt injection. Use when reviewing an agent architecture, isolating untrusted content, constraining tools and egress, protecting secrets, adding injection-focused tests, investigating a suspected injection incident, or documenting residual prompt-injection risk.