5. Execute your first query
6m

Overview

Let's test out our and validate that it can return data from our remote .

In this lesson we will:

  • Create a Network class
  • Add some temporary code to the LaunchListViewModel to show how to execute a

Create an ApolloClient

To use the generated in RocketReserverAPI, you first create an instance of ApolloClient. This instance takes your generated code and uses it to make network calls to your server. It's recommended that this instance is a singleton or static instance that's accessible from anywhere in your codebase.

  1. Create a new Swift file within RocketReserver called Network.swift. Set the target to RocketReserver and add import Apollo to the top of the file.

  2. Now add the following code into the file:

Network.swift
class Network {
static let shared = Network()
private(set) lazy var apollo = ApolloClient(url: URL(string: "https://apollo-fullstack-tutorial.herokuapp.com/graphql")!)
}

Implement the query

To make sure your ApolloClient instance is communicating correctly with the server, jump into the RocketReserver directory and open up LaunchListViewModel. We'll add the imports shown below, then add the following code to the init() method just below the TODO:

LaunchListViewModel.swift
import SwiftUI
import Apollo
import RocketReserverAPI
// ...class initialization
init() {
// TODO (later in the tutorial)
Network.shared.apollo.fetch(query: LaunchListQuery()) { result in
switch result {
case .success(let graphQLResult):
print("Success! Result: \(graphQLResult)")
case .failure(let error):
print("Failure! Error: \(error)")
}
}
}

Test your query

Build and run your application. The web host might take a few seconds to spin up your if nobody's been using it recently, but once it's up, you should see a response in your console that resembles the following:

Query console log output, beginning with 'Success! Result: GraphQLResult...'

This means the request was correctly executed and you now have a list of launch sites 🚀🚀🚀

Go ahead and remove the code added to the init() method so there is just the TODO for later:

LaunchListViewModel.swift
init() {
// TODO (later in the tutorial)
}
Todo list

Up next

Next, let's connect this data to our UI 🚀

Previous

Share your questions and comments about this lesson

This course is currently in

beta
. Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.

You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.