API classes in Swift & Kotlin

Eric Silverberg
Perry Street Software Engineering
3 min readDec 21, 2020

API classes initiate network calls to one remote service, specific to the Repository you are implementing. Though it may be tempting for your API class to itself interact with the network, don’t do it — instead, inject an HTTP client (such as Retrofit on Android) into your API class that itself provides general-purpose network access, including adding necessary authorization parameters and headers.

What you’re going to do to that network response

Each feature area is broken up into a specific interface that defines the necessary GET/POST/PUT/DELETE operations for that feature. API classes are always injected into Repositories. Your API class will coordinate the threading and (in some cases) do the mapping of response data or HTTP error codes to the appropriate domain-specific type.

In Swift, API classes are object that implements a Protocol. In Kotlin, we have an object that implements an Interface.

Naming API classes

For your sanity, rely on a consistent approach to naming APIs, such as:

Methods should be prefixed by the HTTP method (i.e., get, post, put, delete).

Method signatures

All network methods should be Reactive. API classes forward the requests to an injected networking service, either Retrofit in Android, Alamofire or Moya on iOS. Calls to an API class are always first consumed by a Repository.

(Note that TError is a custom error type specific to the feature being implemented.)

Mapping HTTP Errors

API classes should map generic errors into feature-specific errors, for example:

Thus, rather than allowing a 400 Bad Request error to leak up into our application logic, we map HTTP response codes at the API class level to ensure that errors have domain-specific meaning before they are consumed by repositories, logic classes, or are seen by users at the View layer.

Match API Example

In this example, we again continue our Match feature by showing what a potential API might look like for retrieving stacks and posting ratings.

Next up

We’ve covered all of the inner layers and the outer networking layer; all that remains is our View layer.

More in the series

Other series you might like

Clean API Architecture (2021)
Classes, execution patterns, and abstractions when building a modern API endpoint.

Android Activity Lifecycle considered harmful (2021)
Android process death, unexplainable NullPointerExceptions, and the MVVM lifecycle you need right now

About the author

Eric Silverberg is the CEO and founder of Perry Street Software, publisher of two of the world’s largest LGBTQ+ dating apps on iOS and Android.

--

--