SimpleNetworking is a Swift Package that helps you create scalable API clients, simple and elegantly. It uses Combine to expose API responses, making it easy to compose and transform them.
It also includes other goodies, like logging and response stubbing.
The APIClient is responsible for making requests to an API and handling its responses. To create an API client, you need to provide the base URL and, optionally, any additional parameters or headers that you would like to append to all requests, like an API key or an authorization header.
The APIRequest type contains all the data required to make an API request, as well as the logic to decode valid and error responses from the request’s endpoint.
Before creating an API request, we need to model its valid and error responses, preferably as types conforming to Decodable.
Usually, an API defines different valid response models, depending on the request, but a single error response model for all the requests. In the case of The Movie Database API, error responses take the form of a Status value:
struct Status: Decodable {
var code: Int
var message: String
enum CodingKeys: String, CodingKey {
case code = "status_code"
case message = "status_message"
}
}
Now, consider the GET /genre/movie/list API request. This request returns the official list of genres for movies. We could implement a GenreList type for its response:
struct Genre: Decodable {
var id: Int
var name: String
}
struct GenreList: Decodable {
var genres: [Genre]
}
With these response models in place, we are ready to create the API request:
let movieGenresRequest = APIRequest<GenreList, Status>.get("/genre/movie/list")
But we can do better, and extend APIClient to provide a method to get the movie genres:
The response(for:) method takes an APIRequest and returns a publisher that wraps sending the request and decoding its response. We can implement all the API methods by relying on it:
Your app must be prepared to handle errors when working with an API client. SimpleNetworking provides APIClientError, which unifies URL loading errors, JSON decoding errors, and specific API error responses in a single generic type.
let cancellable = tmdbClient.movieGenres()
.catch { error in
switch error {
case .loadingError(let loadingError):
// Handle URL loading errors
...
case .decodingError(let decodingError):
// Handle JSON decoding errors
...
case .apiError(let apiError):
// Handle specific API errors
...
}
}
.sink { movieGenres in
// handle response
}
The generic APIError type provides access to the HTTP status code and the API error response.
Combining and transforming responses
Since our API client wraps responses in a Publisher, it is quite simple to combine responses and transform them for presentation.
Consider, for example, that we have to present a list of popular movies, including their title, genre, and cover. To build that list, we need to issue three different requests.
SimpleNetworking formats the headers and JSON responses, producing structured and readable logs. Here is an example of the output produced by a GET /genre/movie/list request:
NetworkImage, a Swift µpackage that provides image downloading and caching for your apps. It leverages the foundation URLCache, providing persistent and in-memory caches.
Help & Feedback
Open an issue if you need help, if you found a bug, or if you want to discuss a feature request.
Open a PR if you want to make some change to SimpleNetworking.
SimpleNetworking
SimpleNetworking is a Swift Package that helps you create scalable API clients, simple and elegantly. It uses Combine to expose API responses, making it easy to compose and transform them.
It also includes other goodies, like logging and response stubbing.
Let’s explore all the features using The Movie Database API as an example.
Configuring the API client
The
APIClient
is responsible for making requests to an API and handling its responses. To create an API client, you need to provide the base URL and, optionally, any additional parameters or headers that you would like to append to all requests, like an API key or an authorization header.Creating API requests
The
APIRequest
type contains all the data required to make an API request, as well as the logic to decode valid and error responses from the request’s endpoint.Before creating an API request, we need to model its valid and error responses, preferably as types conforming to
Decodable
.Usually, an API defines different valid response models, depending on the request, but a single error response model for all the requests. In the case of The Movie Database API, error responses take the form of a
Status
value:Now, consider the
GET /genre/movie/list
API request. This request returns the official list of genres for movies. We could implement aGenreList
type for its response:With these response models in place, we are ready to create the API request:
But we can do better, and extend
APIClient
to provide a method to get the movie genres:The
response(for:)
method takes anAPIRequest
and returns a publisher that wraps sending the request and decoding its response. We can implement all the API methods by relying on it:Handling errors
Your app must be prepared to handle errors when working with an API client. SimpleNetworking provides
APIClientError
, which unifies URL loading errors, JSON decoding errors, and specific API error responses in a single generic type.The generic
APIError
type provides access to the HTTP status code and the API error response.Combining and transforming responses
Since our API client wraps responses in a
Publisher
, it is quite simple to combine responses and transform them for presentation.Consider, for example, that we have to present a list of popular movies, including their title, genre, and cover. To build that list, we need to issue three different requests.
GET /configuration
, to get the base URL for images.GET /genre/movie/list
, to get the list of official genres for movies.GET /movie/popular
, to get the list of the current popular movies.We could model an item in that list as follows:
To build the list, we can use the
zip
operator with the publishers returned by the API client.Logging requests and responses
Each
APIClient
instance logs requests and responses using a SwiftLog logger.To see requests and responses logs as they happen, you need to specify the
.debug
log-level when constructing the APIClient.SimpleNetworking formats the headers and JSON responses, producing structured and readable logs. Here is an example of the output produced by a
GET /genre/movie/list
request:Stubbing responses for API requests
Stubbing responses can be useful when writing UI or integration tests to avoid depending on network reachability.
For this task, SimpleNetworking provides
HTTPStubProtocol
, aURLProtocol
subclass that allows stubbing responses for specific API or URL requests.You can stub any
Encodable
value as a valid response for an API request:Or as an error response for the same API request:
To use stubbed responses, you need to pass
URLSession.stubbed
as a parameter when creating anAPIClient
instance:Installation
Using the Swift Package Manager
Add SimpleNetworking as a dependency to your
Package.swift
file. For more information, see the Swift Package Manager documentation.Related projects
URLCache
, providing persistent and in-memory caches.Help & Feedback
SimpleNetworking
.