Skip to content

wmalloc/HTTPRequestable

Repository files navigation

Swift Platforms Swift Package Manager License

HTTPRequestable

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.

Getting Started

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")])
  ]
)

Features

Protocol Features
HTTPRequstable Define your request
URLTransferable To create your API client

Usage

Creating an API

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

To defineing a request

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")

License

HTTPRequestable is released under the MIT license. See LICENSE for details.

Support

If you would like to support this project, please consider donating.
Bitcoin: bc1qzxs3wk29vfxlr9e4frq9cdmgkvrp62m5xhm93l
Ethereum: 0xa824353280d2A0F32b2d258904509EFAEaE6603d

About

Generic protocol to make swift requests

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages