0
0
GraphQLquery~5 mins

Interface types in GraphQL

Choose your learning style9 modes available
Introduction

Interface types let you define a common set of fields that different data types share. This helps organize data and makes queries simpler.

When you have different data types that share some common fields, like different kinds of users.
When you want to write queries that work on multiple types without repeating code.
When you want to ensure certain fields always exist on several types.
When you want to build flexible APIs that can return different types but with shared fields.
Syntax
GraphQL
interface InterfaceName {
  field1: Type1
  field2: Type2
}

type TypeA implements InterfaceName {
  field1: Type1
  field2: Type2
  extraField: ExtraType
}

type TypeB implements InterfaceName {
  field1: Type1
  field2: Type2
  anotherField: AnotherType
}

Interfaces define fields without specifying how they work.

Types that implement the interface must include all its fields.

Examples
This example shows an interface Animal with two fields. Both Dog and Cat types implement it and add their own fields.
GraphQL
interface Animal {
  name: String
  age: Int
}

type Dog implements Animal {
  name: String
  age: Int
  breed: String
}

type Cat implements Animal {
  name: String
  age: Int
  color: String
}
Here, Vehicle interface is shared by Car and Bike. Each type adds unique fields.
GraphQL
interface Vehicle {
  make: String
  model: String
}

type Car implements Vehicle {
  make: String
  model: String
  doors: Int
}

type Bike implements Vehicle {
  make: String
  model: String
  type: String
}
Sample Program

This example defines a Person interface with id and name. Both Employee and Customer implement it. The query fetches all people showing only the shared fields.

GraphQL
interface Person {
  id: ID!
  name: String!
}

type Employee implements Person {
  id: ID!
  name: String!
  salary: Float
}

type Customer implements Person {
  id: ID!
  name: String!
  purchaseCount: Int
}

# Query to get all persons with their common fields
query {
  people {
    id
    name
  }
}
OutputSuccess
Important Notes

Interfaces help keep your API organized and consistent.

You can use fragments in queries to get fields from specific types implementing an interface.

Summary

Interfaces define shared fields for multiple types.

Types must implement all interface fields.

Use interfaces to write flexible and reusable queries.