Docs
Try Apollo Studio

9. Write your first mutation


In this section, you will write your first mutation to log in to the backend.

A mutation is used to change data on your server. Here the login mutation will create a session based on your email address.

Note: The way you log in to this particular server might differ from the way you log in with your own server. Login is often handled by middleware, or a layer totally separate from GraphQL, like Oauth. Also note that a typical authentication flow should require a password but for this tutorial, anyone is allowed to book flights with a valid email address!

Prototype your mutation in Sandbox Explorer

Open your Sandbox Explorer and click on the plus symbol to add a new tab. Next, click on the Schema icon to get back to looking at your schema, and select "Mutation" to look at your list of mutations:

The list of available mutations

Scroll down to take a look at the login mutation:

The definition of login in the schema

Click the play button to the right to open that mutation in the Explorer tab. When it opens, click the plus sign to add the operation:

The login mutation after initially being added

Notice the red error indication - this is because the type returned by the mutation is User, which is not a leaf type: you need to choose which of the user's fields the mutation will return. For our purposes, we only need the token field, so add it by clicking the plus sign next to it.

You'll also notice that email wasn't automatically added as an argument even though it doesn't seem to have a default value: that's because email is of type String - which remember, in GraphQL, means that it's not required (although obviously you won't get too far without it).

Click the plus sign next to the email argument to have that argument added:

The operation with the email argument

You'll also notice that Sandbox Explorer has added a variable to your "Variables" section to match the login email.

Click the Submit Operation button your mutation. You'll see that since you sent null for the email address, you get back null for the login:

Results of passing a null email

Now, replace null in the Query Variables section with an actual email address:

(Sandbox Explorer)
{ "email": "me@example.com" }

Press the Submit Operation button, and this time you'll get an actual response:

Results of passing an actual email

Next, copy the operation, either manually or using the three-dot menu's "Copy operation" option.

Add the mutation to the project

Now that your mutation is working, add it to your project. Create a file named Login.graphql next to schema.graphqls and your other GraphQL files and paste the contents of the mutation:

app/src/main/graphql/com/example/rocketreserver/Login.graphql
mutation Login($email: String!) {
login(email: $email) {
token
}
}

Note: we've also marked the email variable as non-nullable by adding ! to the end of the type, since we always want to pass a value for it.

Build your project to generate the LoginMutation class.

Connect the Submit button to your mutation

Open LoginFragment.kt and like you did for the other fragments, override onViewCreated. Add a click listener and some checks to verify that the email is a valid email:

app/src/main/java/com/example/rocketreserver/LoginFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.submitProgressBar.visibility = View.GONE
binding.submit.setOnClickListener {
val email = binding.email.text.toString()
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.emailLayout.error = getString(R.string.invalid_email)
return@setOnClickListener
}
// TODO: More code here
}
}

From the click listener, display the ProgressBar and execute the query with the email the user just entered. Replace the TODO with:

app/src/main/java/com/example/rocketreserver/LoginFragment.kt
binding.submitProgressBar.visibility = View.VISIBLE
binding.submit.visibility = View.GONE
lifecycleScope.launchWhenResumed {
val response = try {
apolloClient.mutation(LoginMutation(email = email)).execute()
} catch (e: Exception) {
null
}
// TODO: handle errors
}

Handle errors if needed by replacing the TODO you just added:

app/src/main/java/com/example/rocketreserver/LoginFragment.kt
val token = response?.data?.login?.token
if (token == null || response.hasErrors()) {
binding.submitProgressBar.visibility = View.GONE
binding.submit.visibility = View.VISIBLE
return@launchWhenResumed
}

Finally if everything is successful, store the token and go back to the previous screen at the end of launchWhenResumed:

app/src/main/java/com/example/rocketreserver/LoginFragment.kt
User.setToken(requireContext(), token)
findNavController().popBackStack()

User is a helper class that saves the token in EncryptedSharedPreference. This is the reason why this tutorial uses API level 23+. Apollo Kotlin itself supports API levels 21+.

Test the login

Go to the details fragment, click Book and in the Login fragment, enter your email and click Submit. You now have a token that allows you to authenticate your operations.

The login screen

In the next section, you will use authenticated operations to book a flight.

Edit on GitHub
Previous
8. Add a details view
Next
10. Authenticate your operations