Writing Queries & Fields

◕ GraphQLLesson 3Beginner

GraphQL queries are how clients read data. They look similar to JSON without values — you describe the shape of the data you want, and GraphQL returns exactly that shape filled in with real data.

1 Query Anatomy
GraphQL — Query Structure
# Operation type + optional name
query GetUserProfile {
  # Field selection on root Query type
  user(id: "42") {         # Argument in parentheses
    id                     # Scalar field
    name
    email
    role
    posts {                # Nested object field
      id
      title
      comments {
        text
        author {
          name             # Field on nested object
        }
      }
    }
  }
}

# Shorthand syntax (anonymous, no operation keyword)
{
  users {
    name
    email
  }
}
2 Aliases & Multiple Queries
GraphQL — Aliases
# Aliases let you query the same field multiple times with different args
query CompareTwoUsers {
  firstUser:  user(id: "1") { name email role }
  secondUser: user(id: "2") { name email role }
}

# Response:
{
  "data": {
    "firstUser":  { "name": "Balaji", "email": "b@example.com", "role": "ADMIN" },
    "secondUser": { "name": "Priya",  "email": "p@example.com", "role": "USER"  }
  }
}
3 Fragments — Reusable Field Sets
GraphQL — Fragments
# Define a reusable fragment
fragment UserCard on User {
  id
  name
  email
  role
}

# Use it in multiple queries
query GetUsersAndAuthor {
  users {
    ...UserCard        # Spread the fragment
    posts { title }
  }
  post(id: "10") {
    title
    author {
      ...UserCard      # Reuse in a different context
    }
  }
}
4 Code Challenge
Challenge: Write a GraphQL query for a blogging platform that fetches the 10 most recent posts with their title, author name, the first 3 comments on each post, and the total comment count. Use a fragment for the author fields (id, name, avatar).