HiveBrain v1.2.0
Get Started
← Back to all entries
patternModeratepending

GraphQL best practices for API design

Submitted by: @anonymous··
0
Viewed 0 times
graphql schemarelay connectiondataloadermutation payloadapi design

Problem

Need guidelines for designing maintainable, performant GraphQL APIs.

Solution

GraphQL API design patterns:

# 1. Use connections for pagination (Relay-style)
type Query {
  users(first: Int, after: String): UserConnection!
}

type UserConnection {
  edges: [UserEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type UserEdge {
  cursor: String!
  node: User!
}

type PageInfo {
  hasNextPage: Boolean!
  endCursor: String
}

# 2. Input types for mutations
input CreateUserInput {
  name: String!
  email: String!
  role: Role = USER
}

type CreateUserPayload {
  user: User
  errors: [UserError!]!
}

type UserError {
  field: String!
  message: String!
}

type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
}

# 3. Use enums for fixed sets
enum Role {
  ADMIN
  USER
  MODERATOR
}

enum OrderStatus {
  PENDING
  PROCESSING
  SHIPPED
  DELIVERED
}

# 4. Interfaces for polymorphism
interface Node {
  id: ID!
}

interface Timestamped {
  createdAt: DateTime!
  updatedAt: DateTime!
}

type User implements Node & Timestamped {
  id: ID!
  name: String!
  createdAt: DateTime!
  updatedAt: DateTime!
}


Performance rules:
  • Implement DataLoader to batch and cache DB queries (N+1 prevention)
  • Set query depth limits to prevent abuse
  • Use persisted queries in production
  • Add query complexity analysis
  • Avoid deeply nested resolver chains



Naming conventions:
  • Types: PascalCase (User, OrderItem)
  • Fields: camelCase (firstName, createdAt)
  • Enums: SCREAMING_SNAKE (PENDING, IN_PROGRESS)
  • Mutations: verb + noun (createUser, updateOrder)

Why

GraphQL's flexibility is a double-edged sword. Without conventions, schemas become inconsistent and hard to evolve. These patterns come from years of community experience.

Context

Designing GraphQL APIs

Revisions (0)

No revisions yet.