Simple REST Client based on RxSwift and Alamofire.

Overview

RxRestClient

CI Status Version License Platform

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

  • iOS 10.0+
  • tvOS 10.0+
  • macOS 10.12+
  • Swift 5.1+
  • Xcode 11+

Migration Guides

Installation

CocoaPods

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

pod 'RxRestClient'
Swift Package Manager

You can use The Swift Package Manager to install RxRestClient by adding the proper description to your Package.swift file:

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    targets: [],
    dependencies: [
        .package(url: "https://github.com/STDevTM/RxRestClient.git", from: "2.1.0")
    ]
)

Next, add RxRestClient to your targets dependencies like so:

.target(
    name: "YOUR_TARGET_NAME",
    dependencies: [
        "RxRestClient",
    ]
),

Then run swift package update.

Features

  • Simple way to do requests
  • Simple way to have response state in reactive way
  • Ability to customization
  • Retry on any error
  • Handle network reachability status
  • Retry on become reachable
  • Ability to use absolute and relative urls
  • Swift Codable protocol support
  • Use custom SessionManager
  • Pagination support
  • Complete Documentation
  • more coming soon

How to use

First of all you need to create struct of your response state and implement ResponseState protocol.

struct RepositoriesState: ResponseState {

    typealias Body = Data

    var state: BaseState?
    var data: [Repository]?

    private init() {
        state = nil
    }

    init(state: BaseState) {
        self.state = state
    }

    init(response: (HTTPURLResponse, Data?)) {
        if response.0.statusCode == 200, let body = response.1 {
            self.data = try? JSONDecoder().decode(RepositoryResponse.self, from: body).items
        }
    }

    static let empty = RepositoriesState()
}

It is required to mention expected Body type (String or Data).

After that you need to create request model:

struct RepositoryQuery: Encodable {
    let q: String
}

Then you can do the request to get repositories:

import RxSwift
import RxRestClient

protocol RepositoriesServiceProtocol {
    func get(query: RepositoryQuery) -> Observable<RepositoriesState>
}

final class RepositoriesService: RepositoriesServiceProtocol {

    private let client = RxRestClient()

    func get(query: RepositoryQuery) -> Observable<RepositoriesState> {
        return client.get("https://api.github.com/search/repositories", query: query)
    }
}

In order to customize client you can use RxRestClientOptions:

var options = RxRestClientOptions.default
options.addHeader(key: "x-apikey", value: "<API_KEY>")
client = RxRestClient(baseUrl: <BASE _URL>), options: options)

Relative vs absolute url

In order to use relative url you need to give <BASE_URL> when initializing client object.

let client = RxRestClient(baseURL: <BASE_URL>)

When calling any request you can provide either String endpoint or absolute URL. If you will String it will be appended to baseURL.

client.get("rest/contacts")

If baseURL is nil then it will try to convert provided String to URL.

In order to use absolute url even when your client has baseURL you can provide URL like this:

if let url = URL(string: "https://api.github.com/search/repositories") {
    client.get(url: url, query: ["q": search])
}

Pagination

Pagination support is working only for GET requests. In order to have pagination (or infinite scrolling) feature you need to implement following protocols for query and response models:

For query model you need to implement PagingQueryProtocol:

struct RepositoryQuery: PagingQueryProtocol {

    let q: String
    var page: Int

    init(q: String) {
        self.q = q
        self.page = 1
    }

    func nextPage() -> RepositoryQuery {
        var new = self
        new.page += 1
        return new
    }
}

For response model you need to implement PagingResponseProtocol:

struct RepositoryResponse: PagingResponseProtocol {
    let totalCount: Int
    var repositories: [Repository]

    private enum CodingKeys: String, CodingKey {
        case totalCount = "total_count"
        case repositories = "items"
    }

    // MARK: - PagingResponseProtocol
    typealias Item = Repository

    static var decoder: JSONDecoder {
        return .init()
    }

    var canLoadMore: Bool {
        return totalCount > items.count
    }

    var items: [Repository] {
        get {
            return repositories
        }
        set(newValue) {
            repositories = newValue
        }
    }

}

For response states you need to use PagingState class or custom subclass:

final class RepositoriesState: PagingState<RepositoryResponse> {
    ...
}

After having all necessary models you can do your request:

client.get("https://api.github.com/search/repositories", query: query, loadNextPageTrigger: loadNextPageTrigger)

loadNextPageTrigger is an Observable with Void type in order to trigger client to do request for next page using new query model generated using nextPage() function.

Author

Tigran Hambardzumyan, [email protected]

Support

Feel free to open issues with any suggestions, bug reports, feature requests, questions.

Let us know!

We’d be really happy if you sent us links to your projects where you use our component. Just send an email to [email protected] and do let us know if you have any questions or suggestion.

License

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

You might also like...
A simple GCD based HTTP client and server, written in 'pure' Swift
A simple GCD based HTTP client and server, written in 'pure' Swift

SwiftyHTTP Note: I'm probably not going to update this any further - If you need a Swift networking toolset for the server side, consider: Macro.swift

Lightweight network abstraction layer, written on top of Alamofire
Lightweight network abstraction layer, written on top of Alamofire

TRON is a lightweight network abstraction layer, built on top of Alamofire. It can be used to dramatically simplify interacting with RESTful JSON web-

A progressive download manager for Alamofire
A progressive download manager for Alamofire

ALDownloadManager A progressive download manager for Alamofire (Alamofire下载器) The default support breakpoint continues. Sequential Download(顺序下载 ) Dow

Alamofire network layer

NVNetworkRequest Alamofire network layer Installation Add this to your Package dependencies: dependencies: [ .package(url: "https://github.com/vin

Advanced Networking Layer Using Alamofire with Unit Testing

Advanced Networking Layer Using Alamofire with Unit Testing

Elegantly connect to a JSON api. (Alamofire + Promises + JSON Parsing)
Elegantly connect to a JSON api. (Alamofire + Promises + JSON Parsing)

⚠ Important Notice: Farewell ws... hello Networking ! Networking is the next generation of the ws project. Think of it as ws 2.0 built for iOS13. It u

Bamboots - Extension 4 Alamofire
Bamboots - Extension 4 Alamofire

Bamboots is a network request framework based on Alamofire , aiming at making network request easier for business development. Protocols Features Requ

Alamofire extension for serialize NSData to SwiftyJSON

Alamofire-SwiftyJSON An extension to make serializing Alamofire's response with SwiftyJSON easily. ⚠️ To use with Swift 3.x please ensure you are usin

An Alamofire extension which converts JSON response data into swift objects using EVReflection

AlamofireJsonToObjects 🚨 This is now a subspec of EVReflection and the code is maintained there. 🚨 You can install it as a subspec like this: use_fr

Comments
  • Bump cocoapods-downloader from 1.4.0 to 1.6.3

    Bump cocoapods-downloader from 1.4.0 to 1.6.3

    Bumps cocoapods-downloader from 1.4.0 to 1.6.3.

    Release notes

    Sourced from cocoapods-downloader's releases.

    1.6.3

    Enhancements
    • None.
    Bug Fixes
    • None.

    1.6.2

    Enhancements
    • None.
    Bug Fixes
    • None.

    1.6.1

    Enhancements
    • None.
    Bug Fixes
    • None.

    1.6.0

    Enhancements
    • None.
    Bug Fixes
    • Adds a check for command injections in the input for hg and git.
      orta #124

    1.5.1

    Enhancements
    • None.
    Bug Fixes
    • Fix "can't modify frozen string" errors when pods are integrated using the branch option
      buju77 #10920

    1.5.0

    ... (truncated)

    Changelog

    Sourced from cocoapods-downloader's changelog.

    1.6.3 (2022-04-01)

    Enhancements
    • None.
    Bug Fixes
    • None.

    1.6.2 (2022-03-28)

    Enhancements
    • None.
    Bug Fixes
    • None.

    1.6.1 (2022-03-23)

    Enhancements
    • None.
    Bug Fixes
    • None.

    1.6.0 (2022-03-22)

    Enhancements
    • None.
    Bug Fixes
    • Adds a check for command injections in the input for hg and git.
      orta #124

    1.5.1 (2021-09-07)

    Enhancements
    • None.

    ... (truncated)

    Commits
    • c03e2ed Release 1.6.3
    • f75bccc Disable Bazaar tests due to macOS 12.3 not including python2
    • 52a0d54 Merge pull request #128 from CocoaPods/validate_before_dl
    • d27c983 Ensure that the git pre-processor doesn't accidentally bail also
    • 3adfe1f [CHANGELOG] Add empty Master section
    • 591167a Release 1.6.2
    • d2564c3 Merge pull request #127 from CocoaPods/validate_before_dl
    • 99fec61 Switches where we check for invalid input, to move it inside the download fun...
    • 96679f2 [CHANGELOG] Add empty Master section
    • 3a7c54b Release 1.6.1
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Bump redcarpet from 3.5.0 to 3.5.1

    Bump redcarpet from 3.5.0 to 3.5.1

    Bumps redcarpet from 3.5.0 to 3.5.1.

    Release notes

    Sourced from redcarpet's releases.

    Redcarpet v3.5.1

    Fix a security vulnerability using :quote in combination with the :escape_html option.

    Reported by Johan Smits.

    Changelog

    Sourced from redcarpet's changelog.

    Version 3.5.1 (Security)

    • Fix a security vulnerability using :quote in combination with the :escape_html option.

      Reported by Johan Smits.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Improvements with parameters encoding

    Improvements with parameters encoding

    Renaming jsonEncoding option to bodyEncoding Renaming urlEncoding option to queryEncoding Removing delete request via array Using bodyEncoding from options for post, put, patch requests Using queryEncoding from options for get, delete requests Bumped version number to 1.3.0

    opened by hamtiko 0
Releases(3.0.0)
Owner
STDev
STDev is a full-stack web and mobile app design and development company founded about 10 years ago.
STDev
TheraForge's Client REST API framework to connect to TheraForge's secure CloudBox Backend-as-a-Service (BaaS)

OTFCloudClientAPI TheraForge's Client REST API Framework to Connect to TheraForg

TheraForge 0 Dec 23, 2021
Restofire is a protocol oriented networking client for Alamofire

Restofire is a protocol oriented networking client for Alamofire. Features Requirements Installation Usage License Features Global Configuration for h

Restofire 381 Sep 29, 2022
GitHub iOS client in RxSwift and MVVM-C clean architecture

GitHub iOS client in RxSwift and MVVM-C clean architecture. FlutterHub - Flutter version available at an early stage KotlinHub - Android version is co

Khoren Markosyan 2.7k Jan 7, 2023
A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS

A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS Built by Tijme Gommers – Buy me a coffee via P

Raivo OTP 770 Jan 8, 2023
Swift/Obj-C HTTP framework with a focus on REST and JSON

Now Archived and Forked PMHTTP will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork of PHMT

Postmates Inc. 509 Sep 4, 2022
Lightweight REST and JSON library for Swift.

RestEssentials is an extremely lightweight REST and JSON library for Swift and can be used on iOS, iPadOS, macOS, tvOS, and watchOS. Features Easily p

null 37 Nov 2, 2022
Lightweight REST library for iOS and watchOS. Available on cococapods

RMHttp RMHttp is a Lightweight REST library for iOS and watchOS. Features Chainable Request URL / JSON Parameter Encoding HTTP Methods GET/POST/DELETE

Roger Molas 7 Nov 19, 2022
The civilized way to write REST API clients for iOS / macOS

The elegant way to write iOS / macOS REST clients Drastically simplifies app code by providing a client-side cache of observable models for RESTful re

Bust Out 2.2k Nov 20, 2022
EasyImplementationAlamoFire - An iOS project to demonstrate the usage of Alamofire in an efficient and organised way.

EasyImplementationAlamoFire Tutorial to demonstrate an efficient way of handling the APIs structure for your iOS Applications. Prerequisites Swift 5 X

null 0 Jan 3, 2022
A frida tool that capture GET/POST HTTP requests of iOS Swift library 'Alamofire' and disable SSL Pinning.

FridaHookSwiftAlamofire A frida tool that capture GET/POST HTTP requests of iOS Swift library 'Alamofire' and disable SSL Pinning. 中文文档及过程 Features Ca

neilwu 69 Dec 16, 2022