• Stars
    star
    110
  • Rank 316,770 (Top 7 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

SwiftyRequest is an HTTP networking library built for Swift.

Kitura

APIDoc Build Status - Master macOS Linux Apache 2 Slack Status

SwiftyRequest

SwiftyRequest is an HTTP client built for Swift.

The latest release of SwiftyRequest is built upon the Swift-NIO based async-http-client.

Contents

Features

  • Several response methods (e.g. Data, Object, Array, String, etc.) to eliminate boilerplate code in your application.
  • Direct retrieval of Codable types.
  • JSON encoding and decoding.
  • Integration with the CircuitBreaker library.
  • Authentication tokens.
  • Client Certificate support (2-way SSL).
  • Multipart form data.

Swift version

The latest version of SwiftyRequest requires Swift 5 or later.

Swift 4 support is available in the 2.x release of SwiftyRequest.

Installation

To leverage the SwiftyRequest package in your Swift application, you should specify a dependency for it in your Package.swift file:

Add dependencies

Add SwiftyRequest to the dependencies within your application's Package.swift file. Substitute "x.x.x" with the latest SwiftyRequest release.

.package(url: "https://github.com/Kitura/SwiftyRequest.git", from: "x.x.x")

Add SwiftyRequest to your target's dependencies:

.target(name: "example", dependencies: ["SwiftyRequest"]),

Usage

Make Requests

To make outbound HTTP calls using SwiftyRequest, create a RestRequest instance. The method parameter is optional (it defaults to .get), the url parameter is required.

Example usage of RestRequest:

import SwiftyRequest

let request = RestRequest(method: .get, url: "http://myApiCall/hello")
request.credentials = .basicAuthentication(username: "John", password: "12345")

You can customize the following parameters in the HTTP request:

  • headerParameters : The HTTP header fields which form the header section of the request message.
  • credentials : The HTTP authentication credentials for the request.
  • acceptType : The HTTP Accept header, defaults to application/json.
  • messageBody : The HTTP message body of the request.
  • productInfo : The HTTP User-Agent header.
  • circuitParameters : A CircuitParameters object which includes a reference to a fallback function that will be invoked when the circuit is failing fast (see CircuitBreaker Integration).
  • contentType : The HTTP Content-Type header, defaults to application/json.
  • method : The HTTP method specified in the request, defaults to .GET.
  • queryItems: Any query parameters to be appended to the URL.

Invoke Response

The result object we get back is of type Result<RestResponse<String>, Error> so we can perform a switch to determine if the network call was successful:

request.responseString { result in
    switch result {
    case .success(let response):
        print("Success")
    case .failure(let error):
        print("Failure")
    }
}

Invoke Response with Template Parameters

URLs can be templated with the {keyName} syntax, allowing a single RestRequest instance to be reused with different parameters.

In this example, we invoke a response method with two template parameters to be used to replace the {state} and {city} values in the URL:

let request = RestRequest(url: "http://api.weather.com/api/123456/conditions/q/{state}/{city}.json")

request.responseData(templateParams: ["state": "TX", "city": "Austin"]) { result in
	// Handle response
}

Invoke Response with Query Parameters

In this example, we invoke a response method with a query parameter to be appended onto the url behind the scenes so that the RestRequest gets executed with the following url: http://api.weather.com/api/123456/conditions/q/CA/San_Francisco.json?hour=9. Any query items already specified in the request URL will be replaced:

let request = RestRequest(url: "http://api.weather.com/api/123456/conditions/q/CA/San_Francisco.json")

request.responseData(queryItems: [URLQueryItem(name: "hour", value: "9")]) { result in
	// Handle response
}

CircuitBreaker Integration

SwiftyRequest has built-in functionality for leveraging the CircuitBreaker library to increase your application's stability. To make use of this functionality, assign a CircuitParameters object to the circuitParameters property. This object will include a reference to a fallback function that will be invoked when the circuit is failing fast.

Fallback

Here is an example of a fallback closure:

let breakerFallback = { (error: BreakerError, msg: String) in
    print("Fallback closure invoked... circuit must be open.")
}

CircuitParameters

We initialize the CircuitParameters object and create a RestRequest instance. The only required value you need to set for CircuitParameters is the fallback (everything else has default values).

let circuitParameters = CircuitParameters(timeout: 2000,
                                          maxFailures: 2,
                                          fallback: breakerFallback)

let request = RestRequest(method: .GET, url: "http://myApiCall/hello")
request.circuitParameters = circuitParameters

At this point, you can use any of the response methods mentioned in the section below.

Response Methods

RestRequest provides a number of response functions that call back with a Result containing either a response or an error.

To invoke the request and receive a response, you can use the response function. The completion handler will be called back with a result of type Result<HTTPClient.Response, Error>.

RestRequest provides additional convenience methods you can use based on the type of the response body you expect:

  • responseData requires that the response contains a body, and calls back with a Result<RestResponse<Data>, Error>.
  • responseObject<T: Decodable> decodes the response body to the specified type, and calls back with a Result<RestResponse<T>, Error>.
  • responseString decodes the response body to a String, and calls back with a Result<RestResponse<String>, Error>.
  • responseDictionary decodes the response body as JSON, and calls back with a Result<RestResponse<[String: Any]>, Error>.
  • responseArray decodes the response body as a a JSON array, and calls back with a Result<RestResponse<[Any]>, Error>.
  • responseVoid does not expect a response body, and calls back with a Result<HTTPClient.Response, Error>.

Example of handling a response

let request = RestRequest(method: .get, url: "http://localhost:8080/users/{userid}")

request.responseObject(templateParams: ["userid": "1"]) { (result: Result<RestResponse<User>, RestError>) in
    switch result {
    case .success(let response):
        let user = response.body
        print("Successfully retrieved user \(user.name)")
    case .failure(let error):
        if let response = error.response {
            print("Request failed with status: \(response.status)")
        }
        if let responseData = error.responseData {
            // Handle error response body
        }
    }
}

Migration from v2 to v3

There are a number of changes to the API in SwiftyRequest v3 compared to the v2 release:

  • The RestRequest initializer parameter containsSelfSignedCert has been renamed insecure to better reflect its purpose (turning off SSL certificate verification). The old name has been deprecated and may be removed in a future release.
  • The completionHandler callback of responseData (et al) has changed from (RestResponse<Data>) -> Void to (Result<RestResponse<Data>, RestError>) -> Void.
  • The JSONDecodable and JSONEncodable types have been removed in favour of using Codable directly. The responseObject function allows you to receive a Codable object in a response.
  • Convenience functions for handling raw JSON have been added. responseDictionary and responseArray alow retrieval of JSON as [String: Any] and [Any] respectively, and sending of raw JSON can be performed by setting the request.messageBodyDictionary or request.messageBodyArray properties.
  • the RestError type is now returned explicitly in the .failure case. If the error pertains to a response with a non-success status code, you can access the response with error.response. If the response also contained body data, it can be retrieved via error.responseData.

Client Certificate support (2-way SSL)

Specify a ClientCertificate when creating a RestRequest to enable a client certificate to be presented upon a secure request (2-way SSL).

The certificate may be provided in PEM format - either from a file, a string or Data, and an optional passphrase. The PEM data should contain the certificate and its corresponding private key. If the private key is encrypted, the corresponding passphrase should be specified when constructing the ClientCertificate.

If you need to handle certificates in other formats, you may create a ClientCertificate directly from a NIOSSLCertificate and NIOSSLPrivateKey. For more information on these types, see the documentation for the async-http-client project.

API documentation

For more information visit our API reference.

Community

We love to talk server-side Swift, and Kitura. Join our Slack to meet the team!

License

This library is licensed under Apache 2.0. Full license text is available in LICENSE.

More Repositories

1

Kitura

A Swift web framework and HTTP server.
Swift
7,628
star
2

BlueSocket

Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.
Swift
1,407
star
3

Swift-JWT

JSON Web Tokens in Swift
Swift
559
star
4

Swift-Kuery

SQL database abstraction layer
Swift
426
star
5

Swift-SMTP

Swift SMTP client
Swift
261
star
6

Swift-Kuery-ORM

An ORM for Swift, built on Codable
Swift
212
star
7

BlueCryptor

Swift cross-platform crypto library using CommonCrypto/libcrypto
Swift
191
star
8

HeliumLogger

A lightweight logging framework for Swift
Swift
176
star
9

swift-html-entities

HTML5 spec-compliant character encoder/decoder for Swift
Swift
170
star
10

swift-ubuntu-docker

🚫 This repo is deprecated - please use the images here: https://hub.docker.com/_/swift
Vim Script
154
star
11

BlueRSA

RSA public/private key encryption, private key signing and public key verification in Swift using the Swift Package Manager. Works on iOS, macOS, and Linux (work in progress).
Swift
132
star
12

Kitura-net

Kitura networking
Swift
104
star
13

BlueSSLService

SSL/TLS Add-in for BlueSocket using Secure Transport and OpenSSL
Swift
97
star
14

Kitura-redis

Swift Redis library
Swift
95
star
15

BlueECC

Elliptic-curve cryptography for Swift
Swift
94
star
16

BlueSignals

Generic Cross Platform Signal Handler
Swift
94
star
17

Configuration

Hierarchical configuration manager for Swift applications
Swift
81
star
18

Kitura-Sample

A sample application that shows how to use various features of Kitura
Swift
81
star
19

Kitura-WebSocket

WebSocket support for Kitura
Swift
68
star
20

OpenSSL

Swift modulemaps for libSSL and libcrypto
C
61
star
21

Swift-Kuery-PostgreSQL

PostgreSQL plugin for Swift-Kuery framework
Swift
61
star
22

SwiftKafka

Swift SDK for Apache Kafka
Swift
60
star
23

KituraKit

Swift client library for using Codable routes with Kitura
Swift
59
star
24

Kitura-CouchDB

CouchDB adapter for Kitura
Swift
51
star
25

CircuitBreaker

A Swift Circuit Breaker library – Improves application stability and reliability.
Swift
47
star
26

Kitura-Credentials

A pluggable framework for validating user credentials in a Swift server using Kitura
Swift
41
star
27

Kitura-NIO

A networking library for Kitura, based on SwiftNIO
Swift
38
star
28

Kitura-OpenAPI

OpenAPI support for Kitura
Swift
37
star
29

TypeDecoder

A Swift library to allow the runtime inspection of Swift language native and complex types.
Swift
37
star
30

SwiftKueryMySQL

MySQL plugin for Swift-Kuery framework
Swift
35
star
31

Package-Builder

Build and utility scripts used for continuous integration builds for Swift Package Manager projects on the Travis CI environment
Shell
35
star
32

CCurl

Modulemap for the libcurl library
Objective-C
31
star
33

Kitura-StencilTemplateEngine

Stencil templating for Kitura
Swift
27
star
34

Kitura-Markdown

Templating engine for Kitura that uses Markdown based templates
C
26
star
35

LoggerAPI

Logger protocol
Swift
26
star
36

kitura.dev

http://www.kitura.dev
JavaScript
26
star
37

Health

An application health library for Swift.
Swift
22
star
38

Kitura-Session

A pluggable framework for managing user sessions in a Swift server using Kitura
Swift
19
star
39

Kitura-WebSocket-NIO

A SwiftNIO based implementation of WebSocket for Kitura
Swift
18
star
40

CommonCrypto

CommonCrypto Module Map
Swift
18
star
41

FileKit

Swift
17
star
42

Kitura-TemplateEngine

Kitura Template Engine protocol
Swift
16
star
43

Swift-Kuery-SQLite

An SQLite plugin for the Swift-Kuery framework
Swift
16
star
44

Kitura-CredentialsHTTP

A plugin for the Kitura-Credentials framework that authenticates using HTTP Basic and Digest authentication
Swift
16
star
45

kitura-cli

⌨️ Kitura command-line interface
Go
14
star
46

KituraContracts

A library containing type definitions shared by client and server Kitura code.
Swift
13
star
47

CZlib

Module map for Zlib library
Swift
12
star
48

CloudEnvironment

Convenience Swift package for accessing environment variables, credentials.
Swift
12
star
49

Kitura-CredentialsFacebook

A plugin for the Kitura-Credentials framework that authenticates using the Facebook web login
Swift
10
star
50

Kitura-CORS

Kitura CORS middleware
Swift
10
star
51

Kitura-Cache

Kitura cache
Swift
10
star
52

Kitura-CredentialsGoogle

A plugin for the Kitura-Credentials framework that authenticates using the Google web login
Swift
9
star
53

Swift-cfenv

Easy access to Cloud Foundry application environment for Swift Packages.
Swift
9
star
54

Kitura-Compression

Kitura compression middleware
Swift
7
star
55

CEpoll

A modulemap file and include to help Swift code use epoll on Linux
Swift
6
star
56

Kitura-WebSocket-Client

A WebSocket client based on SwiftNIO
Swift
6
star
57

Kitura-CredentialsGitHub

A plugin for the Kitura-Credentials framework that authenticates using the GitHub web login
Swift
6
star
58

Kitura-MustacheTemplateEngine

Adapter of GRMustache Template Engine to Kitura Template Engine
Swift
5
star
59

CHTTPParser

Modulemap for the http-parser library
C
5
star
60

Kitura-WebSocket-Compression

A WebSocket compression library based on SwiftNIO
Swift
4
star
61

generator-swiftserver-projects

Autogenerated Kitura projects
Shell
4
star
62

Kitura-Session-Redis

Kitura-Session store using Redis as the backing store
Swift
4
star
63

Kitura-Benchmarks

Benchmarks for Kitura
Swift
3
star
64

homebrew-kitura

Homebrew tap
Ruby
3
star
65

Kitura-CredentialsJWT

A plugin for the Kitura-Credentials framework that supports JWT authentication.
Swift
3
star
66

ShellToolKit

Utility classes to help with common system/shell actions in Swift
Swift
3
star
67

anapistula

Simple standalone web server in swift
Swift
2
star
68

CLibpq

PostgreSQL wrapper
Swift
2
star
69

CMySQL

Swift
1
star
70

Kitura-CI

Repository to hold the testing scripts for some Kitura repositories
Shell
1
star
71

Maintainers

Files relevant to Kitura project maintainers
Swift
1
star
72

StarterWebServer

A starter web server that can be used as a template for a new project
Swift
1
star