swift-http-types icon indicating copy to clipboard operation
swift-http-types copied to clipboard

Add HTTPClient for Web API Client Library

Open zunda-pixel opened this issue 6 months ago • 0 comments

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
  }
}

zunda-pixel avatar Aug 13 '24 04:08 zunda-pixel