Skip to content

Latest commit

 

History

History
88 lines (68 loc) · 3.12 KB

README.md

File metadata and controls

88 lines (68 loc) · 3.12 KB

ConvAPI

Build Status

ConvAPI allows easy HTTP requests in Swift against REST-style APIs with JSON formatting by supporting codable bodies and promised responses.

Etymology

ConvAPI (/kənˈveɪ-piː-aɪ/) is a contraction of Convey (to carry, bring, or take from one place to another) and API (Application Programming Interface).

Usage

ConvAPI has the method

func request<T, U, E>(method: APIMethod,
                      baseURL: URL,
                      resource: String,
                      headers: [String: String]?,
                      params: [String: Any]?,
                      body: T?,
                      error: E.Type,
                      decorator: ((inout URLRequest) -> Void)?) -> Promise<U>

where T: Encodable, U: Decodable, E: (Error & Decodable) at its core.

This method allows you to request a resource from an API specifying the

  • method (e.g. GET),
  • baseURL,
  • resource URI (e.g. /users/42),
  • http headers as a dictionary,
  • query params as a dictionary,
  • request body (any type that conforms to Encodable),
  • an error struct (Decodable) your API might respond with and,
  • a decorator to access/alter the URLRequest that gets fired underneath

and getting the response with a type (U) conforming to Decodable. All of the error handling (status code, empty response, etc.) and parsing is done for you.

Requesting a resource

Request a resource by specifying

struct User: Codable {
    let id: Int
    let name: String
}
        
let api = ConvAPI()
let baseURL = URL(string: "https://jsonplaceholder.typicode.com")!
firstly { () -> Promise<User> in
    api.request(method: .GET, baseURL: baseURL, resource: "/users/1", error: ConvAPIError.self)
}.done { user in
    print(user) // User(id: 1, name: "Leanne Graham")
}

Specifying an error

If your API has an error JSON it is responsing with, just define your error response and hand it in:

struct MyAPIError: Error, Codable {
    let code: Int
    let message: String
}

firstly { () -> Promise<User> in
    api.request(method: .GET, baseURL: baseURL, resource: "/users/1", error: MyAPIError.self)
}.done { user in
    // [...]
}.catch { error in
    switch error {
        case let error as MyAPIError: print(error.code)
        default: break // Request error, network down, etc.
    }
}

Install

Cocoapods

pod 'ConvAPI'

Acknowledgments

This uses mxcl/PromiseKit as a dependency.