A simple way to define and execute your web API requests with IORequestable in Swift.
IORequestable provides a clean and easy way to create web API requests by encapsulating codable input and output types together with URL request specifications based on an abstraction layer of Moya.
API = Encodable Input + Decodable Output + URL and other options
import IORequestable
import Moya
protocol SomeIORequestable: MoyaIORequestable {}
extension SomeIORequestable {
var baseURL: URL {
return URL(string: "https://example.com")!
}
}
struct GetBestPerson: SomeIORequestable {
var spec = Spec(.get, "/api/people/best",
inputEncoding: .urlParameter)
struct Input: Encodable {
let trait: String
let gender: String?
}
struct Output: Decodable {
let name: String
let height: Double?
let weight: Double?
}
}
That's it! You have just created an executable API. Let's run it and give it a try.
GetBestPerson(.init(trait: "kindness",
gender: "all"))
.execute() { result in
switch result {
case .success(let output):
// ...
case .failure(let error):
// ...
}
}
To define path placeholders, use { } in path and @PathOnly for input parameters.
struct GetUserInfo: SomeIORequestable {
var spec = Spec(.get, "/api/books/{bookID}") // Use { } for placeholder
struct Input: Encodable {
@PathOnly var bookID: String // Use @PathOnly
var otherParameter: Int
}
struct Output = ...
}
To use an existing model as Input or Output, use typealias.
struct GetUserInfo: SomeIORequestable {
var spec = ...
typealias Input = String // Define input as String
typealias Output = Person // Use Person as Output,
// where Person conforms to Decodable.
}
To run the example project, clone the repo, and run pod install
from the Example directory first.
IORequestable is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'IORequestable'
royhcj, [email protected]
IORequestable is available under the MIT license. See the LICENSE file for more info.