Saturday, May 18, 2024
HomeProgrammingAPI Layer in Swift with Async/Await

API Layer in Swift with Async/Await


An Async/Await API layer that will help you ace dwell coding interviews

Picture by Firmbee from Pixabay

A typical requirement in iOS developer dwell coding interviews is having the ability to implement networking layers from scratch inside a set timeframe. Whereas it could not come up usually when working professionally as most apps will already include a longtime community layer, figuring out the way to construct one rapidly when eager to prototype one thing is extremely helpful.

I need to exhibit a fast and simple community layer you should utilize to ace dwell coding interviews, it conforms to SOLID rules, makes use of generics, implements Async/Await, has acceptable error dealing with, works in UIKit and SwiftUI apps and if you happen to observe writing it from scratch, might be up and working inside 10 minutes which leaves you extra time in a technical interview to deal with the remainder of the performance.

Let’s get began!

To start with, we’ll want an API to tug information from, ideally one thing with a few completely different endpoints that return various kinds of information. The UK authorities’s meals hygiene ranking API is an efficient start line.

Take a while to familiarise your self with it, nevertheless it’s not essential to realize it as we’ll be taking a look at a few the endpoints specifically as a part of this information.

On to some coding:

We’ll begin coding the APIRouter with an enum to behave as our router object which can home the elements wanted to assemble every of our requests. For this information, we’ll be creating 3 completely different requests:

  1. getAuthorities — Returns particulars of the completely different authorities (learn: areas) throughout the UK
  2. getRatings — Returns particulars on the ranking methods utilized by meals hygiene authorities
  3. getEstablishments — Returns the main points of institutions, we’ll be passing an ID to this to return institutions inside a particular authority (area)

We’re going to be turning the elements we arrange on this enum into URLComponents afterward as a part of the APIRequestDispatcher however we’d like a couple of issues:

  1. host — That is the widespread root of your API requests, suppose medium.com
  2. scheme — That is your API’s internet server protocol (HTTP / HTTPS)
  3. path — That is the particular useful resource endpoint we’re requesting, suppose {host}/@soaringearth
  4. technique — The API technique that you simply’re utilizing to make the request (POST/PUT/PATCH/GET/DELETE)
  5. parameters — These are any question parameters you need to ship to the API

You may discover I’ve not lined physique objects, I’ve by no means been requested personally to implement POST requests throughout interviews, this will likely be because of the extra time to arrange and configure in comparison with extra easy GET requests. If we did need to add physique information, it could be added as a part of the URLRequestDispatcher as URLComponents in iOS solely take care of the development of URLs (which appears apparent) — It will be the URLRequest objects to which we have to add information to.

You’ll see the whole router above, which matches what was mentioned beforehand. You may marvel why we determined to make use of an enum, and it’s for fairly a easy cause. If we determine so as to add a 4th request, the compiler will throw errors inside every computed variable to point we’re lacking a dealt with case, which prevents you from forgetting to implement its scheme/path/technique and many others.

A observe relating to the APIRouter — since I discussed SOLID rules, having a single router that holds all of the elements for each request the applying desires to make doesn’t fairly sit properly with the one duty precept, in a manufacturing app you may need to contemplate having completely different routers for every endpoint if in case you have a number of paths per endpoint i.e (/rankings, /rankings/{id}, /rankings/{id}/xxxYYY), however maintaining the context of this information in thoughts which is the flexibility to supply one thing inside a time-limited technical interview, the strategy on this information will likely be greater than adequate.

We’re now transferring on to the APIRequestDispatcher. That is in all probability essentially the most sophisticated facet of the information and incorporates some options that you simply may not be accustomed to, specifically generics and async/await which I’ll embrace some hyperlinks to the documentation:

There will likely be a component of customized error dealing with as properly however that’s fairly simple to see what’s occurring.

The category itself will likely be easy and solely include a single class perform request<T: Codable>(router: APIRouter) async throws -> T. For many instances, will probably be greater than adequate to deal with easy API requests. Breaking it down, you possibly can see it expects and can return objects that conform to the codable protocol, you might want to present an APIRouter as a parameter, the perform runs asynchronously, and may throw errors.

Let’s break down the snippet above:

  1. The URLComponent is what we’ll assemble primarily based on the enum we created beforehand and why we have to go in an APIRouter to the perform.
  2. URLComponent incorporates a property that means that you can get an non-obligatory URL again which can return nil if the URL can’t be constructed primarily based on the assorted elements it has set. We additionally need to throw a customized error right here if we fail to get the whole URL.
  3. This can be a nuance of the Meals Hygiene API, it requires all requests to include a x-api-version header, you wouldn’t want this with different APIs.
  4. strive await withCheckedThrowingContinuation { continuation — That is an Async/Await perform which suspends the present activity and calls the closure with a checked throwing continuation which is a elaborate manner of claiming that it is a closure that may be known as with the results of asynchronous work. The contents of the closure are principally the identical as common URLSession requests.
  5. If our dataTask fails to get any information again, we are able to throw our different customized error right here to point a noData response, dealing with the error appropriately.
  6. DispatchQueue.primary.async will return us onto the primary thread.
  7. The primary distinction with utilizing Async/Await is as an alternative of simply returning, we have to name continuation.resume(with: and supply our end result (success/failure).

That’s just about it for the request dispatcher, our generics are decoded and returned, and any errors are dealt with and thrown accordingly.

Creating customized errors are so simple as defining a brand new enum:

The API Purchasers that we’ll make are how the customers/apps interactions will talk with the API. We are going to create 1 shopper per request utilizing a POP (Protocol Oriented Programming) strategy. Every request could have its personal protocol and a category that conforms to it, we do it this fashion for ease of mocking the API Shopper and higher separation of considerations as some screens could solely need to entry an inventory of authorities, whereas others could solely need rankings.

You possibly can see the implementations above, you may discover that with the RatingClient we go a parameter however to not the router, it’s because there’s a limitation within the API, the ranking endpoint doesn’t settle for and question parameters so filtering needs to be completed on the system.

The mannequin objects used inside this implementation are easy to know, they’re fundamental structs that conform to codable. For improved readability when utilizing the objects there are a pair CodingKeys which have been used which translate the important thing of the thing acquired to the identify of the property current throughout the mannequin object. Extra data might be discovered right here

Lastly, right here’s an instance of the way to truly fetch information utilizing the Async/Await strategy. It’s only a case of wrapping the API requests inside Activity.init and utilizing a do/catch to deal with the errors.

Thanks for studying I do hope all the pieces was clearly defined and comprehensible, I used this strategy in a number of interviews and when you’ve practiced it a couple of instances you possibly can genuinely have the API Layer written in round 10 minutes if not much less. When you’ve got questions on this information or interviewing for iOS roles usually be happy to succeed in out.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments