Lessons learned from redesigning our GraphQL API
Tags: graphql, ruby, api
Published: 2019-12-23 14:18:20

---
title: Lessons learned from redesigning our GraphQL API
published: true
description: What did we learn when we redesigned our GraphQL API? Here are a few of our GraphQL best practices when building an API.
tags: GraphQL, Ruby, API
canonical_url: https://www.bearer.sh/blog/lessons-learned-from-graphql
---

_(This article originally appeared on [Bearer.sh](https://www.bearer.sh/blog/lessons-learned-from-graphql))_


At Bearer, we use GraphQL to allow our [Dashboard application](https://app.bearer.sh) to communicate with our database. Recently we gave this GraphQL API a re-design. Here are a couple of lessons we learned during the process.

## Lesson one: Serve the user, not your database

> "[[GraphQL](https://graphql.org/)] is a query language for your API". 

This bears repeating: GraphQL is a query language _for your API_. When consumers want to talk to your API, they’ll be doing so in GraphQL.

The primary focus of your GraphQL API is the needs of your API consumers. Unlike other query languages such as SQL, **GraphQL does not care that much about your database structure**. This may sound trivial in theory, but it is surprisingly tempting in practice to take a database-first approach when designing a GraphQL API. 

To give a simplistic example, let’s imagine we are building a profile website for dogs. Our UI contains the dog's name, date of birth, and favorite toy.

![Example Dog UI component](https://blog.bearer.sh/content/images/2019/12/dog-ui-example.png)
Our database looks something like this: 

```
dogs
name: String
birthdate: Date

toys
dog_id: Int
description: String
preference: Int
```

A dog has a name, a birthday, and can have any number of toys. Each toy has a preference, meaning that each dog with one or more toys has a “favorite toy”. 

In Rails, this would look something like:

```ruby
class dog < ApplicationRecord
  has_many :toys

  def favourite_toy
    toys.order(preference: :desc).first
  end
end

class toy < ApplicationRecord
  belongs_to :dog
end
```

Modeling our GraphQL API directly against this database would give us a Dog type that looks something like this:

```graphql
type Dog {
  id: ID!
  name: String!
  birthDate: DateTime!
  toys: [Toy!]!
}

type Toy {
  preference: Int!
  description: String!
}
```

And a query endpoint that looks something like this:

```graphql
query {
  dogs {
    name
    birthDate
    toys {
      preference
      description
    }
  }
}
```

This works fine for our API consumer, but it asks them to understand how our toy preference metric works and to calculate each dog’s favorite toy using this metric.

If, however, we could shift our focus away from our existing database structure and towards the needs of our API consumer (in this case, building that profile website), we would arrive at a Dog type more like this: 

```graphql
type Dog {
  id: ID!
  name: String!
  birthDate: DateTime!
  favoriteToy: Toy!
}

type Toy {
  description: String!
}
```

And a query endpoint more like this:
```graphql
query {
  dogs {
    name
    birthDate
    favoriteToy {
      description
    }
  }
}
```

Here, our GraphQL API gives its consumers exactly what they want: the name and favorite toy for each dog, without requiring any calculations or any knowledge about the underlying data structure. 

Focusing on the consumer in this way can have hidden benefits. For example, we are free to switch up our current “favorite toy” calculation, or to restructure our existing database, all without bothering the consumers of our GraphQL API.

This is how we approached the re-design of our internal GraphQL API. We started with the consumer, our re-designed Dashboard application, and worked backwards to our database. In this way, we arrived at a GraphQL API that is consumer-focused, pleasant to use, and largely shielded from behind-the-scenes changes and updates. 

## Lesson two: Say no to null! Embrace interfaces

Let’s imagine we want to show additional information on our dog profile: 
For rescue dogs, we want to show their adoption date and adoption shelter. 
For show dogs, we want to show their full, registered name. 

We can expand our GraphQL API to accommodate this. Since the new data does not apply to all dogs, we add the additional fields as nullable fields:

```graphql
type Dog {
  id: ID!
  name: String!
  birthDate: DateTime!
  favoriteToy: Toy!
  adoptionDate: DateTime
  adoptionShelter: String
  registeredName: String
}
```

These nullable fields allow us to represent different kinds of dogs within a single Dog type. A schema like this keeps our API simple, but this simplicity can come at a cost. Because we are representing all dogs under one Dog type, information about the different kinds of dogs becomes implicit. 

Our API, for example, does not tell us about the two subsets of dogs available, rescue and show, nor does it tell us that only show dogs would have registered names, and that rescue dogs have adoption dates and shelters. It expects its consumers to know what kinds of dogs (rescue dogs, show dogs) are represented and what fields are associated with which kinds of dogs. 

Moreover, we cannot express which fields are mandatory for which kinds of dogs. Can we expect that every rescue dog has an adoption date and an adoption shelter, or do only some rescue dogs have their shelter name recorded?

Lastly, in its current form, our schema makes no guarantee against returning nonsensical data like the following: 

```json
{
  "data": {
    "dogs": [
      {
        "id":"RG9nLTE=",
        "name": "Fido",
        "birthDate": "2017-08-30",
        “favouriteToy”: {
          “description”: “Yellow Tennis Ball”
        },
        “adoptionDate”: null,
        “adoptionShelter”: “Second Chance”,
        “fullName”: “Patrice Fidelius Wonderful III”
      },
      ...
    ]
  }
}
```

Is Fido a rescue dog, or is he a show dog? Even if we grant that Fido is a rescue show dog, he has no adoption date, which we may or may not be expecting for a rescue dog. 

Instead, we could use a [GraphQL interface](https://graphql.org/learn/schema/#interfaces) to express shared fields between related types. Interfaces in GraphQL operate as abstract classes that define which fields must be present on any type which implements the interface. Following our example, we would have a Dog interface like so

```graphql
interface Dog {
  id: ID!
  name: String!
  birthDate: DateTime!
  favoriteToy: Toy!
}
```

Common dogs, rescue dogs, and show dogs (and, if we so fancy, rescue show dogs) would then be represented as different types implementing this Dog interface

```graphql
type CommonDog implements Dog {
  id: ID!
  name: String!
  birthDate: DateTime!
  favoriteToy: Toy!
}


type RescueDog implements Dog {
  id: ID!
  name: String!
  birthDate: DateTime!
  favoriteToy: Toy!
  adoptionDate: DateTime!
  adoptionShelter: String!
}

type ShowDog implements Dog {
  id: ID!
  name: String!
  birthDate: DateTime!
  favoriteToy: Toy!
  registeredName: String!
}
```

By using an interface, we can clearly show the relationship between the different kinds of dogs, while also removing the problems that nullable fields bring. 

Querying interface types looks something like this, and fully embraces the GraphQL philosophy of “Ask for what you need, get exactly that”. 

```graphql
query {
  dogs {
    name
    birthDate
    favoriteToy {
      description
    }
    ... on ShowDog {
      registeredName
    }
    ... on RescueDog {
      adoptionDate
      adoptionShelter
    }
  }
}
```

## Conclusion

These are only a couple of insights we gained from re-designing our GraphQL API, and some things to keep in mind when building your own. 

We’d love to hear your thoughts on GraphQL, and any lessons you’ve got to share from your own experience building and working with GraphQL APIs.