Swiftpack.co - Package - malt03/CodableAPIClient

CodableAPIClient SwiftPM compatible License

CodableAPIClient is an very typesafe api client library with Codable.

Usage

Create Request Model

struct ExampleRequest: APIRequest {
    var baseUrl: URL { URL(string: "http://example.com/")! }
    
    var method: HTTPMethod { .post }
    var path: String { "/path" }
    
    let parameters = Parameters(a: "a", b: "b")
    typealias ResponseType = Response

    var headers: [String : String] { ["Custom-Header": "xxx"] }
    var timeoutInterval: TimeInterval? { 10 }
    
    var encoder: JSONEncoder { JSONEncoder() }
    var decoder: JSONDecoder { JSONDecoder() }
    
    func didBeginRequest(task: URLSessionUploadTask) {}
    func didProgress(progress: Double) {}
    func didSuccess(response: Response, rawResponse: Data) {}
    func didFailure(error: Error, response: ErrorResponse?, rawResponse: Data?) {}

    struct Parameters: Encodable {
        let a: String
        let b: String
    }

    struct Response: Decodable {
        let c: String
        let d: String
    }
    
    struct ErrorResponse: Decodable {
        let debugMessage: String
    }
}

Request

ExampleRequest().run(progress: { print($0) }, success: { response in print(response) }, failure: { error, response in print(response) })

Recommended Extension

extension APIRequest {
    var baseUrl: URL { URL(string: "http://example.com")! }
    
    var headers: [String: String] {
        [
            "MyService-Session-Token": Session.shared.token ?? "",
        ]
    }
    
    var timeoutInterval: TimeInterval? { nil }

    var encoder: JSONEncoder {
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .secondsSince1970
        return encoder
    }
    var decoder: JSONDecoder {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .secondsSince1970
        return decoder
    }
    
    func didBeginRequest(task: URLSessionUploadTask) {
        debugPrint("beginRequest: \(path)")
    }
    func didProgress(progress: Double) {
        debugPrint("progress: \(progress) \(path)")
    }
    func didSuccess(response: ResponseType, rawResponse: Data) {
        debugPrint("success: \(String(data: rawResponse, encoding: .utf8) ?? "")")
    }
    func didFailure(error: Error, response: ErrorResponseType?, rawResponse: Data?) {
        debugPrint("failure: \(error.localizedDescription) \(rawResponse.flatMap { String(data: $0, encoding: .utf8) } ?? "")")
    }
}
struct ExampleRequest: APIRequest {
    var method: HTTPMethod { .post }
    var path: String { "/path" }

    let parameters = Parameters(a: "a", b: "b")
    typealias ResponseType = Response
}

Installation

SwiftPM

  • On Xcode, click File > Swift Packages > Add Package Dependency...
  • Input https://github.com/malt03/CodableAPIClient.git

Test

docker run -p 80:80 kennethreitz/httpbin

Github

link
Stars: 0

Used By

Total: 0

Releases

0.0.1 - 2020-01-09 13:38:36