Skip to content

Simple, flexible, generic and easy to use HTTP API Client written in Swift

License

Notifications You must be signed in to change notification settings

hromni/SwiftAPIClient

Repository files navigation

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

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 => 'git@github.com:hromni/SwiftAPIClient.git'
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"
        }
    }
    
}
struct GetDataEndpoint: Endpoint {
    var baseUrlString: String {  "https://example.com/" }
    // URL path should always start with forward slash
    var path: String { "/getData" }
}

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
}

Create client wrapper with Combine using the endpoints

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

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

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

Contributors are welcome.