Contents

hromni/swiftapiclient

## SwiftAPIClient

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 |

<a name="spm"/>

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

Concurency safe networking

import Foundation
import SwiftAPIClient

// Define your response objects
struct UserDTO: JsonResponse {
    let id: Int
    let name: String
}

// send API calls
func getUser() async throws -> UserDTO {
    let client = ApiClient()
    return try await client.send(.init(
        baseURL: "https://www.example.com",
        path: "/api/users/1",
        method: HTTPMethod = .get,
        headers: [String : String] = ["Content-Type":"application/json"]
    ))
}

<a name="enum-endpoints"/>

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

<a name="struct-endpoint"/>

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

<a name="decode-json"/>

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.

```swift import Foundation import SwiftAPIClient

struct ExampleDataResponse: JsonResponse { let name: String } ```

<a name="send-combine"/>

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

<a name="send-async"/>

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

<a name="response-validation"/>

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

<a name="contribution"/>

Contribution

Contributors are welcome.

Package Metadata

Repository: hromni/swiftapiclient

Default branch: master

README: README.md