Create a Beautiful Network Layer to Interact with your API in Swift (2022)
--
This story is an iteration, my spin, on the original story Create a beautiful Network Layer With Swift written by Ertem Biyik. He starts by writing:
“Barely all swift developers once upon a time face with a task of interacting with API’s.”
I agree. Many, if not all, developers will face having to interact with an API of some sort at some point in their career. Although I have no problem writing code myself to interact with API’s, there are so many different API’s and so many approaches to writing code to interact with them. I was interested to see which approach he choose and what he considered scalable, clean and pretty.
Let’s first get something out of the way. He did a good job. However my expectations were to find code that was using some of the modern tools we got over the years like the Combine framework, Tasks and Concurrency (Async/Await). So the approach he went with, felt a bit, outdated. Which I noticed from the comments I wasn’t the only one to think that. So I took it to myself to rewrite his story in an attempt to present my view of a more modern approach. Hopefully it will be useful to some people.
The Rick and Morty API
In the tutorial he used the Rick and Morty API (https://rickandmortyapi.com), which has 3 main routes:
Just like his tutorial, this tutorial will only be focussing on the Character part.
Service
First we need a base to encapsulate our code for the service, we name it RickAndMortyService
. Within we define a constant for the base URL for the API.
Character
What the schema for the character looks like can be found in the documentation of the Rick and Morty API. We take the information and translate it into the Swift language. I ommit the properties origin, location and episodes because they are beyond the scope of this tutorial.