swift-http-types
swift-http-types copied to clipboard
Add HTTPClient for Web API Client Library
HTTPClient
Web API Client Library needs HTTPClient
for URLSession
, SwiftNIO
...
Example: GitHub API Client Library
import Foundation
import HTTPTypes
import HTTPClient
import HTTPClientFoundatiaon
let api = GitHubAPI(
token: <#API_TOKEN#>,
httpClient: .urlSession(.shared)
)
let user = try await api.user(id: <#USER_ID#>)
struct GitHubAPI<HTTPClient: HTTPClientProtocol>: Sendable where HTTPClient.Data == Foundation.Data, HTTPClient: Sendable {
let token: String
let httpClient: HTTPClient
func user(id: String) async throws -> User {
let request = HTTPRequest(
method: .get,
url: url,
headerFields: [.authorization: token]
)
let (data, response) = try await httpClient.execute(for: request, from: nil)
let user = try JSONDecoder().decode(User.self, from: data)
return user
}
}