Part 2 of GraphQL Integration in iOS with Apollo
In the first article, I explained how you can connect GraphQL to an iOS app. We connected the Apollo client and fetched data (list of fruits from the
Fruits API) by writing our first query.
As any complete data platform needs a way to modify server-side data, this is where mutations come. For example, mutation can be a registration of the user, signing in/out, or editing their nickname.
So, the difference between query and mutation is simple:
Query is a way to get data, mutation — to change.
Hint: both mutation can return an object type, as well as queries. This may be useful to get a new state of the object after mutation.
Open the docs section of Fruits API playground. Here you can see a list of mutations API provides:
Let’s assume we want to add the fruit not mentioned in the fruit list. We can use the
addFruit mutation for this.
Open a new tab in the playground and start writing with
mutation, then adding a name that describes which data you mutate (usually, go with the same name as in the API docs).
Hint: Do not use mutation at the end of your query name, as Apollo will add this automatically when generating your
The mutation also returns a
Fruit object, so let’s get the name of the fruit we add (it is required to query at least one field if
mutation returns an object) :
So we query the deleted fruit’s name. Also, I have added an
mutation’s parameters as the API should somehow know which fruit to delete. The needed parameters for mutations are mentioned in the docs tab:
Hint: you can set the default values for parameter in the same way we get used to it in Swift:
As we did with the query, you add an empty file, name it (I recommend you use the same as the name of the mutation), and add .graphql extension:
Copy and paste the mutation from the playground and build the project.
After the project is built, Apollo generates the
AddFruitMutation class in
Now we can update our
ViewController with the
addFruit() function, which will perform an
AddFruit mutation with the Apollo client and handle the result:
Paste this code, update it with whatever fruit you like, and run the app. You may run the
GetAllFruits query to check if your fruit was added to the database.