Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

GraphQL Interfaces & Unions

Introduction

In GraphQL, interfaces and unions are special types that allow you to define schema flexibility. They enable a single field to return different types of data based on certain conditions, enhancing the API's versatility.

Interfaces

An interface is an abstract type that can be implemented by multiple types, allowing for polymorphism. This means that you can query a field that may return different types that implement the same interface.

Key Concepts:

  • Interfaces define a set of fields that types must implement.
  • Interfaces allow for returning multiple types from a single field.

Defining an Interface


type Character {
    id: ID!
    name: String!
}

interface Human {
    id: ID!
    name: String!
}

type Droid implements Human {
    id: ID!
    name: String!
    primaryFunction: String!
}

type HumanCharacter implements Human {
    id: ID!
    name: String!
    homePlanet: String!
}
            

In this example, Human is an interface that both Droid and HumanCharacter implement. This allows queries to return either type when asking for a Human.

Unions

A union type is a type that can represent multiple types, but unlike interfaces, it does not require the types to share any fields.

Key Concepts:

  • Unions allow fields to return different types without shared fields.
  • Unions are useful when types do not share a common structure.

Defining a Union


union SearchResult = Human | Droid

type Query {
    search(phrase: String!): [SearchResult]
}
            

Here, the SearchResult union allows the search query to return either a Human or a Droid, depending on the search results.

Best Practices

When using interfaces and unions in GraphQL, consider the following best practices:

  • Use interfaces when you need a common set of fields across types.
  • Use unions when types do not share common fields but need to be returned from the same field.
  • Keep your schema simple and avoid overusing interfaces and unions to prevent complexity.
  • Document your interfaces and unions clearly to help consumers understand their usage.

FAQ

What is the difference between interfaces and unions?

Interfaces require the types to implement specific fields, while unions do not require any shared fields. Use interfaces for polymorphic types and unions for types that simply need to coexist.

Can a type implement multiple interfaces?

Yes, a type can implement multiple interfaces, allowing for more complex schemas and behaviors.

Are there limitations on using unions?

Unions can return types that do not share fields, but querying for specific fields on a union type requires using inline fragments to specify the type.

Conclusion

Understanding interfaces and unions is essential for designing a flexible and scalable GraphQL schema. They provide powerful mechanisms for polymorphism and type safety in your API.