Swift
APIkit

Github Search Repository with swift and APIKit

Introduction to APIKit

I am going to give a brief introduction of APIKit with swift, APIKit is a type-safe networking abstraction layer that associates request type with response type which simplifies the design and implementation of REST APIs.

Demo Code

protocol RequestType: APIKit.Request {}

extension RequestType {

    /// Base URL
    var baseURL: URL {
        return URL(string: "https://api.github.com")!
    }

    /// Header
    var headerFields: [String : String] {
        return [
            "Accept": "application/json",
            "Accept-Encoding": "gzip"
        ]
    }

    func intercept(urlRequest: URLRequest) throws -> URLRequest {
        return urlRequest
    }

    func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any {
        guard (200..<300).contains(urlResponse.statusCode) else {
            throw APIError(object: object)
        }
        return object
    }

}


// MARK: - JSON Decode
extension RequestType where Response: Himotoki.Decodable {
    func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Self.Response {
        return try decodeValue(object)
    }
}

This APIClient Class will return to the Session Class for responding the data.

struct APIClient {
    public static var configuration = URLSessionConfiguration.default

    static var session: Session {
        self.configuration.urlCache?.diskCapacity = 0
        self.configuration.urlCache?.memoryCapacity = 0

        return Session(adapter: URLSessionAdapter(configuration: configuration))
    }

    struct Fetch {
        static func get(query: String) -> Observable<APIClient.Fetch.ResponseFetchRepositoryDecode> {
            return Session.sendRequest(
                request: Fetch.GetFetchRepositoryRequest(query: query)
            )
        }
    }
}

This is where we transform APIKit Session Class into Rx System so that we can use Observable for data response.

extension Session {
    func sendRequest<T: Request>(request: T) -> Observable<T.Response> {
        return Observable.create{ [unowned self] observer in
            let task = self.send(request) { result in
                switch result {

                case .success(let response):
                    observer.onNext(response)

                case .failure(.responseError(let apiError as APIError)):
                    observer.onError(apiError)

                case .failure(let error):
                    observer.onError(error)
                }
            }
            return Disposables.create {
                task?.cancel()
            }
        }
    }

    static func sendRequest<T: Request>(request: T) -> Observable<T.Response> {
        return Session.shared.sendRequest(request: request)
    }

}

Sample Github Search Repository using APIKit

Within this sample project, you can search any repositories in github, I am using APIKit in this project to request github API and response as webview. Maybe next sample I will use Moya lib instead of APIKit.

Intallation

In podfile, the add the following lines:

# auto layoutp
pod 'SnapKit'

# Rx
pod 'ReactorKit'
pod 'RxCocoa'
pod 'RxSwift'

# APIKit
pod 'APIKit'
pod 'Himotoki'
pod 'Result'

# Swift Initializer
pod 'Then'

Sample Demo
IMG_2854.GIF

Here is the Sample Code Github Here!!! Feel Free to check with this sample :D