Swiftpack.co - Package - futuredapp/FTAPIKit
FTAPIKit logo

FTAPIKit

Cocoapods Cocoapods platforms License

Declarative and generic REST API framework using Codable. With standard implementation using URLSesssion and JSON encoder/decoder. Easily extensible for your asynchronous framework or networking stack.

Installation

When using Swift package manager install using Xcode 11+ or add following line to your dependencies:

.package(url: "https://github.com/futuredapp/FTAPIKit.git", from: "1.1.1")

When using CocoaPods add following line to your Podfile:

pod 'FTAPIKit', '~> 1.1'

Features

The main feature of this library is to provide documentation-like API for defining web services. This is achieved using declarative and protocol-oriented programming in Swift.

The framework provides two core protocols reflecting the physical infrastructure:

  • Server protocol defining single web service.
  • Endpoint protocol defining access points for resources.

Combining instances of type conforming to Server and Endpoint we can build request. URLServer has convenience method for calling endpoints using URLSession. If some advanced features are required then we recommend implementing API client. This client should encapsulate logic which is not provided by this framework (like signing authorized endpoints or conforming to URLSessionDelegate).

Architecture

This package contains predefined Endpoint protocols. Use cases like multipart upload, automatic encoding/decoding are separated in various protocols for convenience.

  • Endpoint protocol has empty body. Typically used in GET endpoints.
  • DataEndpoint sends provided data in body.
  • UploadEndpoint uploads file using InputStream.
  • MultipartEndpoint combines body parts into InputStream and sends them to server. Body parts are represented by MultipartBodyPart struct and provided to the endpoint in an array.
  • RequestEndpoint has encodable request which is encoded using encoding of the Server instance.

Endpoint types

Usage

Defining web service (server)

Firstly we need to define our server. Structs are preferred but not required:

struct HTTPBinServer: URLServer {
    let baseUri = URL(string: "http://httpbin.org/")!
    let urlSession = URLSession(configuration: .default)
}

If we want to use custom formatting we just need to add our encoding/decoding configuration:

struct HTTPBinServer: URLServer {
    ...

    let decoding: Decoding = JSONDecoding { decoder in
        decoder.keyDecodingStrategy = .convertFromSnakeCase
    }
    let encoding: Encoding = JSONEncoding { encoder in
        encoder.keyEncodingStrategy = .convertToSnakeCase
    }
}

If we need to create specific request, add some headers, usually to provide authorization we can override default request building mechanism.

struct HTTPBinServer: URLServer {
    ...
    func buildRequest(endpoint: Endpoint) throws -> URLRequest {
        var request = try buildStandardRequest(endpoint: endpoint)
        request.addValue("MyApp/1.0.0", forHTTPHeaderField: "User-Agent")
        return request
    }
}

Defining endpoints

Most basic GET endpoint can be implemented using Endpoint protocol, all default propertires are inferred.

struct GetEndpoint: Endpoint {
    let path = "get"
}

Let's take more complicated example like updating some model. We need to supply encodable request and decodable response.

struct UpdateUserEndpoint: RequestResponseEndpoint {
    typealias Response = User

    let request: User
    let path = "user"
}

Executing the request

When we have server and enpoint defined we can call the web service:

let server = HTTPBinServer()
let endpoint = UpdateUserEndpoint(request: user)
server.call(response: endpoint) { result in
    switch result {
    case .success(let updatedUser):
        ...
    case .failure(let error):
        ...
    }
}

Contributors

Current maintainer and main contributor is Matěj Kašpar Jirásek, matej.jirasek@futured.app.

We want to thank other contributors, namely:

License

FTAPIKit is available under the MIT license. See the LICENSE file for more information.

Github

link
Stars: 9

Dependencies

Used By

Total: 1

Releases

Combine in CocoaPods fix - 2020-05-04 10:57:31

Imports Combine extension in CocoaPods properly

Platforms specifics and README updates - 2020-04-09 11:23:29

  • Properly defined platform support
  • Tuned README

Rewritten and out of alpha! - 2020-02-13 08:02:39

  • Removed API adapter.
  • Removed RequestType enum.
  • Introduced Server protocols.
  • Improved Endpoint protocols.
  • Enables different encodings.

Futured APIKit - 2020-01-20 13:09:56

SPM, Swift 5.0 and bug fixes - 2019-07-02 17:25:21

  • Fix thread safety and implement serialization (#33)
  • Add Swift package manager support for Xcode 11 (#32)
  • Fix requestType .urlEncoded use percent encoding (#27)

v0.4.1: Valid podspec and CocoaPods release - 2019-03-19 09:56:44

  • Lint podpec
  • Create Core subspec
  • Increase deployment targets
  • Fix public access modifier warnings

v0.4.0: Multipart streams - 2019-03-11 15:51:31

Breaking change:

  • MultipartFile renamed to MultipartBodyPart and has different initializers.

Enhancements:

  • Multipart requests are made using streams to lower memory usage
  • Proper content-length and headers for multipart request
  • Increased code coverage

v0.3.1: Rewritten promise subspec - 2019-02-13 11:20:07

v0.3.0: Return of the data task - 2019-01-11 09:05:40

Add mechanism to allow cancellation of data task, progress monitoring etc. by optional return of data task from URLSessionAPIAdapter.

v0.2.1 - 2019-01-03 12:16:38

Fixes

  • Do not add query when no parameters are present

v0.2 - 2018-11-12 07:51:57

Changes

  • Add result do APIAdapterDelegate method so the signing can complete with errors

Improvements

  • Update documentation
  • Reorganize files and imports

v0.1 - 2018-10-25 12:53:08