ConvAPI
ConvAPI 允许在 Swift 中轻松进行 HTTP 请求,针对具有 JSON 格式的 REST-style APIs,通过支持 codable 主体和 promised 响应。
词源
ConvAPI (/kənˈveɪ-piː-aɪ/
) 是由 Convey ( transportation from one place to another ) 和 API ( Application Programming Interface ) 缩写而成。
用法
ConvAPI 内核有方法
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>
其中 T: Encodable, U: Decodable, E: (Error & Decodable)
此方法允许您指定以下内容来从 API 请求资源
- 方法 (例如
GET
) - 基本 URL
- 资源 URI (例如
/users/42
) - 作为字典的 HTTP 标头
- 作为字典的查询参数
- 请求体 (任何符合
Encodable
的类型) - API 可能响应的错误结构体 (
Decodable
),以及 - 一个装饰器来访问或修改下面的
URLRequest
并获取一个类型为 (U
) 的响应,该类型符合 Decodable
。所有错误处理(例如状态码、空响应等)和解析都为您完成。
请求资源
通过指定来请求资源
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")
}
指定错误
如果您的API响应有错误JSON,只需定义错误响应并将其提交
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.
}
}
安装
Cocoapods
pod 'ConvAPI'
致谢
这使用了mxcl/PromiseKit作为依赖项。