A lightweight WebService API for Apple devices, written in Swift 5.x and using Structured Concurrency. It builds on top of HTTPTypes library by Apple.
Add the following dependency clause to your Package.swift:
// swift-tools-version:5.9
import PackageDescription
let package = Package(
name: "MyApp",
platforms: [.iOS(.v16), .tvOS(.v16), .macOS(.v12), .watchOS(.v9), .macCatalyst(.v16), .visionOS(.v1)],
products: [
.executable(name: "MyApp", targets: ["MyApp"])
],
dependencies: [
.package(url: "https://github.com/wmalloc/HTTPRequestable.git", from: "0.7.11")
],
targets: [
.target(name: "MyApp", dependencies:
[.product(name: "HTTPRequestable", package: "HTTPRequestable")])
]
)
Protocol | Features |
---|---|
HTTPRequstable |
Define your request |
URLTransferable |
To create your API client |
class HackerNews: HTTPTransferable {
let session: URLSession
var requestInterceptors: [any RequestInterceptor] = []
var responseInterceptors: [any ResponseInterceptor] = []
required init(session: URLSession = .shared) {
self.session = session
}
func storyList(type: String) async throws -> StoryList.ResultType {
let request = try StoryList(storyType: type)
return try await object(for: request, delegate: nil)
}
}
struct StoryList: HTTPRequestable {
typealias ResultType = [Int]
let environment: HTTPEnvironment = .init(scheme: "https", authority: "hacker-news.firebaseio.com")
let headerFields: HTTPFields? = .init([.accept(.json)])
let queryItems: [URLQueryItem]? = [URLQueryItem(name: "print", value: "pretty")]
let path: String?
var responseTransformer: Transformer<Data, ResultType> {
{ data, _ in
try JSONDecoder().decode(ResultType.self, from: data)
}
}
init(storyType: String) throws {
guard !storyType.isEmpty else {
throw URLError(.badURL)
}
path = "/v0/" + storyType
}
}
Then you can create an instantiate your API object to make calls
var api = HackerNews()
let topStories = try await api.storyList(type: "topstories.json")
HTTPRequestable is released under the MIT license. See LICENSE for details.
If you would like to support this project, please consider donating.
Bitcoin: bc1qzxs3wk29vfxlr9e4frq9cdmgkvrp62m5xhm93l
Ethereum: 0xa824353280d2A0F32b2d258904509EFAEaE6603d