DEV Community

loading...

SWAPI GraphQL Demo

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

Star Wars API, the Holy Grail of all the demonstration APIs. There is no mentionable service without having Luke Skywalker or Darth Vader be involved. So, as the first step of our public GraphQL API demos, let's just have our very own Star Wars demo app to be implemented.

Before getting started we need to find a working GraphQL SWAPI endpoint. The official repo is only for setting up our own server (which is nice to have), but if we don't want to set up a demo server, then we need a ready to use endpoint.

There is no API key requirement here, so we only need the endpoint link. Also, we need to decide what info to grab and display since the Schema is pretty diversified.

In our demo app, we will move forward with the following query.

query GetAllData {
  allPeople {
    people { id name gender birthYear eyeColor hairColor height mass skinColor created edited }
  }
}
Enter fullscreen mode Exit fullscreen mode

Screenshot

To keep things simple, we will use the following local database structure.

class People: NSObject, GQLObject {

  @objc var id = ""
  @objc var name = ""
  @objc var gender = ""
  @objc var birthYear = ""
  @objc var eyeColor = ""
  @objc var hairColor = ""
  @objc var height = 0
  @objc var mass = 0
  @objc var skinColor = ""
  @objc var created = ""
  @objc var edited = ""

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

Since the server and the local data structure naming are synchronized, we can fetch and save the data using the following.

func fetchAll() {

  let query = GQLQuery["GetAllData"]

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

  gqldb.updateInsert("People", values)
}
Enter fullscreen mode Exit fullscreen mode

After these preparations, there are no other steps than display the data (from the local database) using some TableViews.

Screenshot

There are probably million other ways to demonstrate how a SWAPI GraphQL endpoint can be accessed from an iOS app, but this is our version. You can check the full source code here.

Discussion (0)