Logo for tanaschita.com

GraphQL essentials for iOS development

Understand the concept behind GraphQL in context of iOS development.

updated on 22 Apr 2024 · 12 min read

GraphQL is an API design paradigm which has emerged as an alternative to RESTful APIs. Compared to REST, which exposes fixed endpoints for different resources, GraphQL enables clients to query and retrieve only the data they need, in a single request.

In this article, we'll dive into the essentials of GraphQL for iOS development. Let's jump in.

Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

Understanding the difference between GraphQL and REST

To get a first impression of how GraphQL works, let's look at an example and how it is solved with GraphQL compared to REST.

Let's say we're implementing the frontend of a dog treats shop displaying an overview of the orders a user made.

When working with a REST API, we would use multiple endpoints where each endpoint returns specific information, for example:

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

It may happen that the information we get from the /orders endpoint will not be enough for our frontend needs because we want to display some of the details directly in the orders overview. To achieve this with REST, we 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, we end up sending a lot of requests to the server. With the second approach, every time frontend requirements change, we may need to change the backend.

In comparison to REST, GraphQL APIs only expose a single endpoint. We can specify precisely what data we need. By using GraphQL, we define all needed detail fields in a GraphQL query:

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

When we send a request with this query to the server, we get exactly the data we defined, nothing more and nothing less.

GraphQL as server-side runtime

As an iOS developer, in most cases we won't need to know all the details on how GraphQL is implemented server-side wise.

An interesting thing to know is that GraphQL isn't tied to any specific framework, programming language or database. GraphQL acts 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.

Basic concepts of GraphQL

Queries

In the example above we already saw an example of a GraphQL query. Let's look at its the basic parts:

Basic parts of a GraphQL query.
Basic parts of a GraphQL query.

As shown above, we can name a query to be able to reference it.

Additionally, we can pass in arguments into the query. In our example, the id of an order is an argument. The exclamation point ! indicates, that the argument is required.

A field is a unit of data, which ends up as a field in the JSON response data. For the query above, we could get the following JSON response:

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

Mutations

When working with APIs, we also need to be able 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 as follows:

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

In the mutation above, we create a new order by passing it in as an argument of type OrderInput. The mutation will return the id of the freshly created order in the response.

GraphQL schema and explorer

As a frontend developer, we need to know what kind of data we can ask for and what fields we can select. That's where the schema comes in.

Each GraphQL service defines a set of types which completely describe all possible data we can query or mutate as a client. When we send a query to that service, it will be executed against that schema to check if it's valid.

To explore that schema, GraphQL services often offer an in-browser exlorer like GraphiQL. With GraphiQL, we can write and test queries against the service. It offers a documentation and supports debugging as we type, giving hints and pointing out errors.

GitHub's GraphQL explorer.
GitHub's GraphQL explorer.

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, we 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, we can now use the defined fragment as follows:

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

GraphQL in iOS

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

For example, for sending a GraphQL query, you would send the query and its 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", ... }
}

I prefer to use another way to communicate with a GraphQL service by using the library Apollo iOS Client. This networking library was specifically designed for working with GraphQL.

After we provide a schema file of the GraphQL service, the library will generate strongly typed Swift files out of our defined queries, which we can then use to send 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):
// handle success.
case .failure(let error):
// handle error.
}
}

To dive deeper, check out this article on getting started with Apollo iOS for GraphQL in Swift.

Conclusion

I hope, I could give you a good introduction into the world of GraphQL. If you are new to GraphQL, 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 first 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.

Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

graphql

networking

swift

ios

Getting started with Apollo iOS for GraphQL in Swift

Learn how to integrate GraphQL into a Swift application using Apollo iOS.

12 Feb 2024 · 8 min read

Latest articles and tips

© 2024 tanaschita.com

Privacy policy

Impressum