Skip to content

A set of Swift helpers for interacting with APIs in a Codable format

License

Notifications You must be signed in to change notification settings

gotranseo/CodableAPI

Repository files navigation

CodableAPI

CI Status Version License Platform

Motivation

This library is an opinionated way to handle making API requests and receiving responses in a Codable format. Please feel free to fork this project and make changes as you see fit, but note that every element of the existing protocol is extensible and customizable.

Installation

CodableAPI is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'CodableAPI'

Usage

Declaring a Request model

Every time a request is made, that request needs an object. For example,

struct LoginRequest: APIRequestRepresentable {
    //specify a Codable type that you want the response parsed into 
    typealias ResponseType = User

    //specify an error type that conforms to `APIError` that you want any errors parsed into
    typealias ErrorType = MyErrorType

    //the request's method
    var method: CodableAPI.HTTPRequestType = .post
    
    //the url of the request
    func url() -> String {
        return "your_url_here"
    }
}

We also need to create a model to hold the login information:

struct Login: Parameters {
    var email: String
    var password: String
}

Then, in your controller, do the following:

let loginRequest = Login(email: "[email protected]", password: "secret password")
let successHandler: ((User?) -> Void) = { user in
    //handle the success
}

let errorHandler: ((Codable?) -> Void) = { error in
    //handle the error
}

LoginRequest().request(parameters: loginRequest, success: successHandler, error: errorHandler)

And that's it! Enjoy the type safe nature of Swift in all of its glory.

Headers

You can implement a headers() function in APIRequestRepresentable models. This will add the headers to the request. If none are added, Content-Type: application/json is set automatically.

Custom Decoder

You can also implement a jsonDecoder() function in APIRequestRepresentable models. This is useful if you need to set properties like dateDecodingStrategy. If not implemented, a default JSONDecoder() instance is returned.

Author

Slate Solutions, Inc.

License

CodableAPI is available under the MIT license. See the LICENSE file for more info.