A simple generic API layer implemented in Swift. Good solution to avoid external dependencies in small/midsize projects.
- Instantiate APICore
let api: APIProvider = APICore()
- Access the generic request method passing your parameters
let urlPath: [PathURL] = [.base, .myPath, .variable("dynamicValue")]
api.request(url: urlPath, httpMethod: .get, body: nil) { (result: Result<Object, ErrorHandler>) in
switch result {
case .success(let value):
// handle value (as your custom Object or [Object])
case .failure(let error):
// handle error.message (as String)
}
}
enum PathURL {
case base
case myPath
case variable(String)
}
extension PathURL: RawRepresentable {
public typealias RawValue = String
public init?(rawValue: RawValue) { switch rawValue { default: return nil } }
public var rawValue: RawValue {
switch self {
case .base: return "http://myUrlBasePath.com/"
case .myPath: return "myPath/"
case .variable(let value): return value
}
}
}
enum NetworkErrors: String {
case `default` = "Default message error"
case connection = "Connection message error"
case json = "Json message error"
}
enum HttpMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
}
- Add API Stub with Unit test sample