0
0
GraphqlHow-ToBeginner · 3 min read

How to Deprecate a Field in GraphQL: Syntax and Examples

In GraphQL, you can deprecate a field by adding the @deprecated directive to it. Optionally, you can provide a reason string to explain why the field is deprecated and suggest alternatives.
📐

Syntax

The @deprecated directive is added to a field in your GraphQL schema to mark it as deprecated. You can optionally include a reason argument to explain why the field is deprecated.

  • @deprecated: Marks the field as deprecated.
  • reason: A string explaining why the field is deprecated or what to use instead.
graphql
type ExampleType {
  oldField: String @deprecated(reason: "Use newField instead")
  newField: String
}
💻

Example

This example shows a GraphQL type with a deprecated field oldField and a new recommended field newField. The @deprecated directive includes a reason message.

graphql
type User {
  id: ID!
  username: String!
  email: String @deprecated(reason: "Use contactEmail instead")
  contactEmail: String!
}
⚠️

Common Pitfalls

Common mistakes when deprecating fields include:

  • Not providing a reason, which leaves clients unsure why the field is deprecated.
  • Removing the field immediately without deprecation, breaking existing clients.
  • Failing to update documentation or client code to use the new field.

Always keep deprecated fields in the schema for some time and provide clear reasons.

graphql
type Product {
  # Wrong: no reason given
  oldPrice: Float @deprecated(reason: "No longer supported")
  # Right: clear reason provided
  newPrice: Float
  discountedPrice: Float @deprecated(reason: "Use newPrice instead")
}
📊

Quick Reference

DirectivePurposeExample
@deprecatedMarks a field as deprecatedoldField: String @deprecated(reason: "Use newField")
reasonExplains why the field is deprecatedreason: "Use newField instead"

Key Takeaways

Use the @deprecated directive to mark fields as deprecated in GraphQL schemas.
Always provide a reason to guide clients on what to use instead.
Do not remove deprecated fields immediately to avoid breaking clients.
Update documentation and client code to reflect deprecations.
Deprecation helps maintain backward compatibility while evolving your API.