DEV Community

loading...

Rick and Morty GraphQL Demo

Related Code
Mobile Application Development. Scalable Architecture Design. Custom Backend Development. Application Security. Performance Engineering. Analytics. Maintenance.
・2 min read

Another great demonstration API example is the Rick and Morty API. They have both REST and GraphQL endpoints, and not just the source code is available, but there is also a ready-to-use endpoint.

No API key is required, so we only need the base url. Also, since the Schema is nicely detailed, to keep things simple we will fetch the characters using the following query.

query GetCharacters($page: Int!) {
  characters(page: $page) {
    info { count pages next prev }
    results {
      id name status species type gender image created
      origin { id name type dimension created }
      location { id name type dimension created }
      episode { id name air_date episode created }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Screenshot

To store the data in the local database we will use separated tables, as described below.

class Character: NSObject, GQLObject {

  @objc var id = ""
  @objc var name = ""
  @objc var status = ""
  @objc var species = ""
  @objc var type = ""
  @objc var gender = ""
  @objc var image = ""
  @objc var originId = ""
  @objc var locationId = ""
  @objc var episodeIds = ""
  @objc var created = ""

  static func primaryKey() -> String {
    return "id"
  }
}
Enter fullscreen mode Exit fullscreen mode
class Location: NSObject, GQLObject {

  @objc var id = ""
  @objc var name = ""
  @objc var type = ""
  @objc var dimension = ""
  @objc var created = ""
  @objc var residents = ""

  static func primaryKey() -> String {
    return "id"
  }
}
Enter fullscreen mode Exit fullscreen mode
class Episode: NSObject, GQLObject {

  @objc var id = ""
  @objc var name = ""
  @objc var air_date = ""
  @objc var episode = ""
  @objc var characters = ""
  @objc var created = ""

  static func primaryKey() -> String {
    return "id"
  }
}
Enter fullscreen mode Exit fullscreen mode

Updating the local database with the fetched data is a little more complex than in the previous examples, but this is still not rocket science.

func fetch(_ query: String, _ variables: [String: Any]) {

  server.query(query, variables) { [self] result, error in
    if let error = error {
      print(error.localizedDescription)
    } else {
      if let characters = result["characters"] as? [String: Any] {
        if let results = characters["results"] as? [[String: Any]] {
          for values in results {
            updateDatabase(values)
          }
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
func updateDatabase(_ values: [String: Any]) {

  let character = Character.create(values)

  if let origin = values["origin"] as? [String: Any] {
    gqldb.updateInsert("Origin", origin)
    if let originId = origin["id"] as? String {
      character.originId = originId
    }
  }

  if let location = values["location"] as? [String: Any] {
    gqldb.updateInsert("Location", location)
    if let locationId = location["id"] as? String {
      character.locationId = locationId
    }
  }

  if let episodes = values["episode"] as? [[String: Any]] {
    var episodesIds: [String] = []
    for episode in episodes {
      gqldb.updateInsert("Episode", episode)
      if let episodeId = episode["id"] as? String {
        episodesIds.append(episodeId)
      }
    }
    character.episodeIds = episodesIds.joined(separator: ", ")
  }

  character.updateInsert(gqldb)
}
Enter fullscreen mode Exit fullscreen mode

Once we have the fetched data in the local database, we only need to display them in some TableViews.

Screenshot

Since the API automatically paginates the responses (20 documents per page), we need to fetch the data page by page.

func characters(_ page: Int) {

  let query = GQLQuery["GetCharacters"]
  let variables: [String: Any] = ["page": page]

  fetch(query, variables)
}
Enter fullscreen mode Exit fullscreen mode

And pretty much that's all we need for a basic Rick and Morty demo app. You can check the full source code here.

Discussion (0)