Swiftpack.co - jaredh159/x-http as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by jaredh159.
jaredh159/x-http v1.0.0
A zero-dependency, bare-bones Swift async/await HTTP library
⭐️ 0
🕓 1 year ago
macOS
.package(url: "https://github.com/jaredh159/x-http.git", from: "v1.0.0")

XHttp

A zero-dependency, bare-bones Swift HTTP library, using async/await.

Usage

Make a GET request, decoding the response:

import XHttp

struct XkcdComic: Decodable {
  let num: Int
  let title: String
  let month: String
  let year: String
}

let bobbyTables = try await HTTP.get(
  "https://xkcd.com/327/info.0.json",
  decoding: XkcdComic.self
)

Supports posting arbitrary JSON and decoding the response:

let slackResponse = try await HTTP.postJson(
  slack, // 👋 <-- some `Encodable` type instance
  to: "https://slack.com/api/chat.postMessage",
  decoding: SlackResponse.self
)

All methods allow passing headers, a handful of authorization types (bearer, basic), and custom encoding/decoding strategies:

let slackResponse = try await HTTP.postJson(
  slack,
  to: "https://slack.com/api/chat.postMessage",
  decoding: SlackResponse.self,
  headers: ["X-Foo": "Bar"], // 👋 <-- custom headers
  auth: .bearer(token), // 👋 <-- authorization
  keyEncodingStrategy: .convertToSnakeCase, // 👋 <-- encoding strategy
  keyDecodingStrategy: .convertFromSnakeCase // 👋 <-- decoding strategy
)

Also includes a method for posting posting x-www-form-urlencoded data:

try await HTTP.postFormUrlencoded(
  ["payment_intent": "pi_abc123lolrofl"], // 👋 <-- url params
  to: "https://api.stripe.com/v1/refunds",
  decoding: Stripe.Api.Refund.self,
  auth: .basic(STRIPE_SECRET_KEY, ""),
  keyDecodingStrategy: .convertFromSnakeCase
)

All the methods have overloads allowing you to directly access to the Data and HTTPURLResponse if you don't want to decode to a decodable type:

let (data, httpUrlResponse) = try await HTTP.get("https://xkcd.com/327/info.0.json")
let (data, httpUrlResponse) = try await HTTP.postJson(
  slack,
  to: "https://slack.com/api/chat.postMessage"
)

Installation

Use SPM:

// swift-tools-version:5.5
import PackageDescription

let package = Package(
  name: "RadProject",
  products: [
    .library(name: "RadProject", targets: ["RadProject"]),
  ],
  dependencies: [
+   .package(url: "https://github.com/jaredh159/x-http.git", from: "1.0.0")
  ],
  targets: [
    .target(name: "RadProject", dependencies: [
+     .product(name: "XHttp", package: "x-http"),
    ]),
  ]
)

Used by

A few basic higher-level client/sdk's built on top of XHttp include:

GitHub

link
Stars: 0
Last commit: 1 year ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Release Notes

v1.0.0
1 year ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics