Swiftpack.co - hromni/SwiftAPIClient as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by hromni.
hromni/SwiftAPIClient 0.1.5
Simple, flexible, generic and easy to use HTTP API Client written in Swift
⭐️ 9
🕓 14 weeks ago
iOS macOS watchOS tvOS
.package(url: "https://github.com/hromni/SwiftAPIClient.git", from: "0.1.5")

SwiftAPIClient

Group 3032 (3)

Light weight and simplistic API Client written in Swift using protocol oriented programming. You can send requests using async await or Combine publishers without having to change anything. SwiftAPIClient can help you implement your HTTP and server API calls with just a couple lines of code.

Open Sourced by HR Omni Solutions

Table of contents
Install with SPM
Define your endpoints using enum
Define endpoint using struct
Decode JSON responses
Send request using Combine
Send request using async
Response validation
Contribution

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding SwiftAPIClient as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/hromni/SwiftAPIClient.git", .upToNextMajor(from: "0.1"))
]

Cocoapods

pod 'HROmni.SwiftApiClient'

or

pod 'HROmni.SwiftApiClient', :git => '[email protected]:hromni/SwiftAPIClient.git'

Define your endpoints using enum

import Foundation
import SwiftAPIClient

enum Endpoints: Endpoint {

    case getData, addData(_ name: String)

    var baseUrlString: String {  "https://example.com/" }

    var httpBody: RequestBody? {
        switch self {
        case .addData(let name):
            return .jsonDictionary(["name" : name])
        default: return nil
        }
    }

    var httpMethod: HTTPMethod {
        switch self {
        case .getData: return .get
        case .addData: return .post
        }
    }

    var path: String {
    // URL path should always start with forward slash
        switch self {
        case .getData:
            return "/getData"
        case .addData(let data):
            return "/addData"
        }
    }
    
}

Endpoint example using struct

struct GetDataEndpoint: Endpoint {
    var baseUrlString: String {  "https://example.com/" }
    // URL path should always start with forward slash
    var path: String { "/getData" }
}

Decode JSON responses

If you're expecting a JSON response you can use JsonResponse protocol which is a wrapper of Decodable with some extra build-in functionality. You can also create your own response type by conforming to Response protocol.

import Foundation
import SwiftAPIClient

struct ExampleDataResponse: JsonResponse {
   let name: String
}

Send request using Combine

Create client wrapper with Combine using the endpoints


struct ApiClient {
    static func getData() -> AnyPublisher<ExampleDataResponse, SwiftApiClientError> {
        Endpoints.getData.send() 
        // GetDataEndpoint().send()
    }
}

Send request using async

As mentioned the endpoint automatically handles both Combine and async, so you can use either approach. For example if you want to use async all you need to do is replace send() with asyncSend() using the same Endponts definition above


struct ApiClient {
    static func getData() async throws -> ExampleDataResponse {
        try await Endpoints.getData.asyncSend() 
        // try await GetDataEndpoint().asyncSend()
    }
}

Validating responses

The default validator code is below.

struct BasicResponseValidator: ResponseValidator {
    public func validate(_ response: (data: Data, response: URLResponse)) throws {
        if let statusCode = (response.response as? HTTPURLResponse)?.statusCode,
           statusCode >= 300 {
            throw SwiftApiClientError.serverError(statusCode: statusCode, payload: response.data)
        }
    }
}

You can also create your own validator by conforming to

public protocol ResponseValidator {
    func validate(_ response: (data: Data, response: URLResponse)) throws
}

and then pass it as a validator to your endpoints to replace the default response validation

Contribution

Contributors are welcome.

GitHub

link
Stars: 9
Last commit: 14 weeks ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Related Packages

Release Notes

0.1.5
14 weeks ago

support for cocoapods

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