GraphQL Object Types

Object types are the main building blocks of a GraphQL schema. They group related fields together into a named structure, just like a class in programming or a row in a database table. Every entity your API exposes — users, orders, products, comments — is an object type.

Defining an Object Type

  type Vehicle {
    id:        ID!
    make:      String!
    model:     String!
    year:      Int!
    electric:  Boolean!
    mileage:   Float
  }

The keyword type starts the definition. The name follows. Curly braces contain the fields. Each field has a name and a type separated by a colon.

Object Types Referencing Each Other

The real power of object types comes from linking them together. A Car has an Owner. An Owner has an Address. GraphQL handles this graph of relationships natively — the name "GraphQL" comes from this graph nature of connected data.

  type Address {
    street: String!
    city:   String!
    country:String!
  }

  type Owner {
    id:      ID!
    name:    String!
    address: Address!    ← References Address type
  }

  type Car {
    id:     ID!
    model:  String!
    owner:  Owner!       ← References Owner type
  }

  Query — traverse all three types at once:
  ──────────────────────────────────────────
  {
    car(id: "c1") {
      model
      owner {
        name
        address {
          city
          country
        }
      }
    }
  }

The Query and Mutation Types Are Also Object Types

Query and Mutation are special object types that GraphQL treats as entry points. Every field you define on them becomes an operation clients can call.

  type Query {             ← Special object type
    car(id: ID!): Car
    allCars: [Car!]!
  }

  type Mutation {          ← Special object type
    addCar(model: String!, ownerId: ID!): Car!
  }

Self-Referencing Types

Object types can reference themselves. This models tree and graph structures like comment threads, categories with subcategories, or employee-manager hierarchies.

  type Category {
    id:          ID!
    name:        String!
    parent:      Category       ← Points to itself
    subcategories: [Category]   ← List of the same type
  }

  Query — go as deep as needed:
  ──────────────────────────────
  {
    category(id: "electronics") {
      name
      subcategories {
        name
        subcategories {
          name
        }
      }
    }
  }

Two Types Can Reference Each Other

GraphQL allows circular references between types. A Student can have a list of Course objects, and each Course can have a list of Student objects. The schema defines both directions.

  type Student {
    name:    String!
    courses: [Course!]!   ← Points to Course
  }

  type Course {
    title:    String!
    students: [Student!]! ← Points back to Student
  }

Circular references in queries need depth limiting on the server to prevent infinitely nested queries from overloading the system — a topic covered in the security section.

Leave a Comment