Swift: Making a modern API client with Async/Await

Saad El Oulladi
2 min readAug 18, 2022

Nowadays, most of all popular mobile applications use Rest api to access dynamic data.

That’s why Apple did a lot of improvement in network layer and concurrency in the recent Swift releases.

In the following article, we will cover how to create an API client component that allows to call a remote API and parse its result into models using async/await.

In order for any project to start using async/await, it’s important to implement it in the lower layers, like the network layer or database access.

In the following example will use a free API called thecocktaildb, we will make an API client that searches cocktail by name 🍹.

Here is an example of a json response we get from search API:

iOS version compatibility

The following example uses async await which is available starting from iOS 13.
URLSession async data task is only compatible from iOS 15.
If your project is below iOS 15, you can use withCheckedThrowingContinuation to convert dataTask closure to async await.
You can check the following article for further details.

ApiError

First we will create an enumeration that represents the different errors we might have.

BaseApi

Then we create the Base api, which allows to send a GET request and return the result as a Result in async way.

Build Api URL

--

--