0
0
GraphqlHow-ToBeginner · 4 min read

How to Use Fragment in Query in GraphQL: Syntax and Examples

In GraphQL, use fragment to define reusable sets of fields that can be included in queries with ...FragmentName. This helps avoid repeating fields and keeps queries clean and maintainable.
📐

Syntax

A fragment defines a reusable group of fields on a specific type. You declare it with fragment FragmentName on TypeName. Then, include it in queries using ...FragmentName.

This lets you write the fields once and reuse them in multiple places.

graphql
fragment UserDetails on User {
  id
  name
  email
}

query GetUser {
  user(id: "1") {
    ...UserDetails
  }
}
💻

Example

This example shows a fragment UserDetails that fetches id, name, and email fields of a User. The query GetUser uses this fragment to get user data by ID.

graphql
fragment UserDetails on User {
  id
  name
  email
}

query GetUser {
  user(id: "1") {
    ...UserDetails
  }
}
Output
{ "data": { "user": { "id": "1", "name": "Alice", "email": "alice@example.com" } } }
⚠️

Common Pitfalls

1. Forgetting to specify the type in the fragment declaration. The on TypeName part is required.

2. Using fragments on the wrong type. The fragment must match the type of the field you apply it to.

3. Not including the fragment spread (...FragmentName) inside the query. Declaring a fragment alone does nothing unless you use it.

graphql
/* Wrong: Missing type in fragment */
fragment UserDetails {
  id
  name
}

/* Correct: Include type */
fragment UserDetails on User {
  id
  name
}

/* Wrong: Using fragment on wrong type */
fragment UserDetails on Post {
  id
  title
}

query GetUser {
  user(id: "1") {
    ...UserDetails
  }
}

/* Correct: Fragment type matches field type */
fragment UserDetails on User {
  id
  name
}

query GetUser {
  user(id: "1") {
    ...UserDetails
  }
}
📊

Quick Reference

ConceptDescriptionExample
Fragment DeclarationDefines reusable fields on a typefragment UserDetails on User { id name email }
Fragment SpreadIncludes fragment fields in query...UserDetails
Type MatchingFragment type must match field typefragment UserDetails on User {...} used on user field
ReuseUse fragments to avoid repeating fieldsMultiple queries can use ...UserDetails

Key Takeaways

Use fragment to define reusable field sets on a specific type.
Include fragments in queries with ...FragmentName to reuse fields.
Always specify the type in the fragment declaration with on TypeName.
Ensure the fragment type matches the type of the field where it is used.
Fragments help keep queries clean and avoid repeating the same fields.