0
0
GraphqlHow-ToBeginner · 3 min read

How to Name Queries and Mutations in GraphQL Correctly

In GraphQL, name queries using clear, descriptive nouns or noun phrases that represent the data you want to fetch, like getUser or listBooks. For mutations, use verbs or verb phrases that describe the action, such as createUser or updatePost, to clearly indicate the operation performed.
📐

Syntax

GraphQL queries and mutations are named operations that help clients request or modify data. The name should be a single word or camelCase phrase that clearly describes the purpose.

  • Query name: Usually a noun or noun phrase representing the data requested.
  • Mutation name: Usually a verb or verb phrase describing the action performed.
graphql
query getUser {
  user(id: "1") {
    id
    name
  }
}

mutation createUser {
  createUser(input: {name: "Alice"}) {
    id
    name
  }
}
💻

Example

This example shows a query named getUser to fetch user data and a mutation named updateUserEmail to update a user's email address. The names clearly describe their purpose.

graphql
query getUser {
  user(id: "123") {
    id
    name
    email
  }
}

mutation updateUserEmail {
  updateUserEmail(id: "123", email: "newemail@example.com") {
    id
    email
  }
}
Output
{ "data": { "user": { "id": "123", "name": "John Doe", "email": "john@example.com" }, "updateUserEmail": { "id": "123", "email": "newemail@example.com" } } }
⚠️

Common Pitfalls

Common mistakes include using vague or inconsistent names, mixing verbs in queries, or nouns in mutations, which confuse API users. Avoid names like doUser for queries or userData for mutations.

Always keep query names focused on data retrieval and mutation names focused on data changes.

graphql
query doUser {
  user(id: "1") {
    id
  }
}

mutation userData {
  updateUser(id: "1", name: "Bob") {
    id
    name
  }
}

# Corrected version:
query getUser {
  user(id: "1") {
    id
  }
}

mutation updateUser {
  updateUser(id: "1", name: "Bob") {
    id
    name
  }
}
📊

Quick Reference

Operation TypeNaming StyleExample
QueryNoun or noun phrasegetUser, listBooks, allOrders
MutationVerb or verb phrasecreateUser, updatePost, deleteComment

Key Takeaways

Name queries with clear nouns that describe the data being fetched.
Name mutations with verbs that describe the action performed.
Keep naming consistent and descriptive to improve API clarity.
Avoid mixing verbs in queries or nouns in mutations.
Use camelCase for readability and standard GraphQL style.