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.10
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.10.1")
],
targets: [
.target(name: "MyApp", dependencies:
[.product(name: "HTTPRequestable", package: "HTTPRequestable")])
]
)
Protocol | Features |
---|---|
HTTPRequstable |
Define your request |
HTTPTransferable |
To create your API client |
class HackerNews: HTTPTransferable, @unchecked Sendable {
var requestInterceptors: [any RequestInterceptor] = []
var responseInterceptors: [any ResponseInterceptor] = []
let session: URLSession
required init(session: URLSession = .shared) {
self.session = session
let logger = LoggerInterceptor()
requestInterceptors.append(logger)
responseInterceptors.append(logger)
}
func storyList(type: String) async throws -> StoryList.ResultType {
let request = try StoryListRequest(environment: environment, storyType: type)
return try await object(for: request, delegate: nil).value ?? []
}
}
struct StoryListRequest: HTTPRequestable {
typealias ResultType = [Int]
let environment: HTTPEnvironment
let headerFields: HTTPFields? = .init([.accept(.json)])
let queryItems: [URLQueryItem]? = [URLQueryItem(name: "print", value: "pretty")]
let path: String?
var responseDataTransformer: Transformer<Data, ResultType>? {
Self.jsonDecoder
}
init(environment: HTTPEnvironment, storyType: String) throws {
precondition(!storyType.isEmpty, "Story type cannot be empty")
self.environment = environment
self.path = "/\(storyType).json"
}
}
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