TANASCHITA.COM
Articles about Swift and iOS Development by Natascha Fadeeva

GraphQL essentials you need to know as an iOS Developer

Master the networking concept behind GraphQL and their usage on iOS

Published 12. April 2020 - 6 min read

In a nutshell, GraphQL is an API design paradigm that describes how to ask for data. It is an alternative to the currently more known REST approach. Originally, GraphQL was developed and open-sourced in 2015 by Facebook. Since then, it has been adopted by many companies. The reason why they are choosing GraphQL over REST is because GraphQL eliminates inefficiencies of REST by giving clients the ability to exactly define the data that need from the server.

This post provides you with the essentials of GraphQL, especially those you need to know as an iOS developer.

Hey buddy, I have an idea on how we can get all the data we need in one request.

First impression of GraphQL

For the first impression of how GraphQL works, let's look at an example of how you would use GraphQL compared to REST.

Imagine, you are implementing a frontend of a dog treats shop and you want to display an overview of the orders a user made.

A REST API would expose multiple endpoints where each endpoint returns specific information. So by using a REST API, you could have the following endpoints:

  • /orders to get all orders with basic information
  • /order/[id] to get the details of a specific order

It may happen that the information you get from the /orders endpoint will not be enough for frontend needs, because you want to display some of the details directly in the orders overview. To achieve this with REST, you could:

  1. Send an additional request for every order to load more details to the /order/[id] endpoint.
  2. Or ask the backend team to add more data to the /orders endpoint.

Both ways are not ideal. With the first approach, you end up sending a lot of requests to the server. With the second approach, every time frontend requirements change, you may need to change the backend.

And here comes GraphQL to the rescue.

In contrast to REST, GraphQL APIs only expose a single endpoint. You can specify precisely what data you need.

By using GraphQL, you would define all the detail fields you need from an order in a GraphQL query:

{
  orders {
    id
    name
    price
    status
    supplier {
        id
        name
    }
  }
}

Then, you would send a request with this query to the server and get exactly the data you defined back, nothing more and nothing less.

GraphQL as server-side runtime

As an iOS developer, you don't necessarily need to know all the details on how GraphQL is implemented server-side wise. So I will not go into too much detail here.

An interesting thing to know is that GraphQL isn't tied to any specific framework, programming language or database. You can image GraphQL more as a layer lying between an existing backend implementation and the client.

Many different programming languages support GraphQL, including Swift. For example, Graphiti is a Swift library for building GraphQL schemas. To get a GraphQL service running on the server, you would define so called resolvers for every data piece that can be accessed. A resolver is a method that tells GraphQL how and where to fetch the data you are asking for, for example by accessing an existing database.

GraphQL basic concepts

Queries

In the example above we already saw a GraphQL query in their short form. Queries are used to get data from server, like with a GET request in REST. Let's look at the basic parts of a query.

Basic parts of a GraphQL query.

Compared to the short form, we use a long form of a query here and give it the name Order. In production apps, you will mostly use this long form to add more readability to your code.

To be able to reuse queries, GraphQL offers variables that you can pass in as arguments into the query. In our example, the id of an order is passed in as an argument. The exclamation point ! behind the argument indicates, that it is required. Without it the argument would be optional.

A field is a unit of data you are asking for, which ends up as a field in your JSON response data. So for the above query, you would get a JSON response that looks like this:

{
 order {
    name: "Dog soft frisbee",
    status: "PAID"
 }
}

Mutations

When working with APIs, you also want to mutate, delete or create new data. As an equivalent to POST, PUT and DELETE requests in REST, so called mutations are used in GraphQL.

Mutations consist of the same parts as a query. A mutation for creating a new order could look like this:

mutation CreateOrder($order: OrderInput!) {
    createOrder($order: OrderInput!) {
        id
    }
}

Here, the order data that is needed to create one is passed in as an argument of type OrderInput. In the same way as in a query, you define fields that should be returned in the response. The mutation above will return the id of the freshly created order.

GraphQL schema and explorer

As a frontend developer, you need to know what kind of data you can ask for and what fields you can select. That's where the schema comes in.
Each GraphQL service defines a set of types which completely describe all possible data you can query or mutate as a client. When you send a query to that service, it will be executed against that schema to check if it is valid.

And to explore that schema, GraphQL services often offer an in-browser exlorer like GraphiQL. With GraphiQL, you can write and test your queries against the service. It offers a documentation and supports debugging as you type, giving hints and pointing out errors. In the image below, you can see GitHub's GraphiQL service for exploring their API in action.

GitHub's GraphQL explorer in action.

Fragments

The last GraphQL concept I like to introduce are fragments. Fragments are reusable units that can be used when building more complicated queries. For example, you could extract the supplier behind an ordered product into a separate fragment to reuse it in different queries.

fragment Supplier on Order {
    supplier {
        id
        name
    }
}

When fetching an order, you can now use the defined fragment like this:

{
  order($id: Id!) {
    name
    ...Supplier 
  }
}

GraphQL in iOS

To be able to send requests to a GraphQL service from an iOS application, you could build the request on your own with the same tools you would use for sending REST requests.

For example, for sending a GraphQL query, you would send the query and it's variables in the query parameter of a HTTP GET request.

http://myapi/graphql?query={me{name...}}&variables={...}

Or send it in the body of a POST request:

{
  "query": "...",
  "operationName": "...",
  "variables": { "myVariable": "someValue", ... }
}

But a much simpler way to communicate with a GraphQL service is using a library like Apollo iOS Client. This networking library was specifically designed for working with GraphQL. All you need to do is to provide a schema file of the GraphQL service. The library will then generate strongly typed Swift files out of your defined queries, so you can easily use them to make requests.

Here is an example of how sending a request looks like with Apollo:

apollo.fetch(query: GetOrderQuery(id: id)) { result in
  switch result {
  case .success(let graphQLResult):
    print("Success! Result: \(graphQLResult)")
  case .failure(let error):
    print("Failure! Error: \(error)")
  }
}

If you are interested, you can read more on how to work with Apollo iOS Client in more detail in this (coming soon) post.

Conclusion

I hope, I could give you a good introduction into the world of GraphQL. If you want to take the next step, I recommend playing around with Githubs GraphQL explorer, by reading through their docs and try out different types of queries. This will give you a good impression on how GraphQL works in practice.

And of course, you can also dive deeper into the concepts of GraphQL by reading the official documentation.

Written by

Natascha Fadeeva
Author and creator of this site

Contact