Minimalist HTTP request library via async / await

Related tags

Networking Mu
Overview

Mu

CI Swift 5.0 Swift Package Manager compatible License

Minimalistic HTTP Requests library via async / await

What is this?

Making HTTP API requests in Swift using Foundation can be verbose and use a mix of types like URL, URLComponents and URLRequest to form a request and then handling all the encoding and decoding steps later. While this code is not very complicated in can become extremely repetitive especially when writing requests by hand.

The goal of this Swift Package is to provide an extremely minimaistic lightweight abstraction layer between the user and the repetitive and verbose nature of Foundation to write HTTP requests.

Mu allows the user to declare a request with it's body and headers up front along side its other details like endpoint to improve code readability and eliminate the boilerplate that comes with rolling HTTP requests send with URLSession.

Installation

Going forward Swift Package Manager seems like it will replace Carthage and CocoaPods and since SPM is baked into Xcode why not?

To install Mu via SPM in Xcode go to File -> Add Packages... and enter https://github.com/nirma/mu

Basic Usage

Mu is very simple as there are only two parts to it being a request that conforms to HTTPRequest and the Requester that is used to send the request.

GET Request

        let request = Request(
            scheme: .https,
            host: "api.github.com",
            path: "/users/nirma",
            method: .get,
            headers: ["Accept": "application/vnd.github.v3+json"]
        )
        
        let requester = Requester(decoder: JSONDecoder())

        Task {
            do {
                let (user, response) = try await requester.send(
                    request: request,
                    expect: ExpectedResponse.self // A `Decodable` type that is the expected response
                )
                ...
            } catch { ... }
        }

POST Request

POST requests specify the body in terms of HTTPBody. HTTPBody can either be raw Data or a type that conforms to Swifts Encodable`.

        let body = [
            "username": "foobar42",
            "email": "[email protected]",
            "password_hash": "34973274ccef6ab4dfaaf86599792fa9c3fe4689"
        ]
        
        let request = Request(
            scheme: .https,
            host: "example.com",
            path: "/user/create",
            method: .post,
            headers: ["Content-Type": "application/json"],
            body: HTTPBody(body)
        )
        
        let requester = Requester(decoder: JSONDecoder())

        Task {
            do {
                let (user, response) = try await requester.send(
                    request: request,
                    expect: ExpectedResponse.self // A `Decodable` type that is the expected response
                )
                ...
            } catch { ... }
        }
        

Making requests with HTTPRequest

HTTPRequest is a protocol that all requests in this library must confrom to. Included in this library is a simple class Request that implements this protocol and is purely included just for convenience please feel free to implement your own types conforming to HTTPRequest or use or subclass Request if it suits your needs.

Sending requests with HTTPRequester

Simply construct a type conforming to HTTPRequester and use the send(request:expect) method to send your request. The response will be converted to the type specified by the expect parameter and an exception will be thrown if conversion fails.

Requester comes out of the box and accepts any type for decoding that conforms to AbstractDecoder default conformance has been applied to JSONDecoder so for requests expecting JSON responses simply pass in JSONDecoder:

let requester = Requester(decoder: JSONDecoder())

If JSONDecoder is not the right tool to get the job done then simply confrom the type you wish to use to AbstractDecoder and pass it in!

License

This library is released under the MIT license. See LICENSE for details.

You might also like...
Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Embassy Super lightweight async HTTP server in pure Swift. Please read: Embedded web server for iOS UI testing. See also: Our lightweight web framewor

Communicate via HTTP easily in Swift.

swift-http-client Communicate via HTTP easily in Swift. Table of Contents Installation How to use Contribution Installation Swift Package Manager (Rec

Http - Demo for Http Layer

http Example To run the example project, clone the repo, and run pod install fro

An iOS library to route API paths to objects on client side with request, mapping, routing and auth layers

WANetworkRouting Developed and Maintained by ipodishima Founder & CTO at Wasappli Inc. Sponsored by Wisembly A routing library to fetch objects from a

Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Automatically sets the network activity indicator for any performed request.

BigBrother BIG BROTHER IS WATCHING YOU. BigBrother is a Swift library made for iOS that automatically watches for any performed request and sets the n

NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. ⚙️🚀
NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. ⚙️🚀

SONetworking NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. Project Folder and File Struc

YTKNetwork is a high level request util based on AFNetworking.

YTKNetwork What YTKNetwork is a high level request util based on AFNetworking. It's developed by the iOS Team of YuanTiKu. It provides a High Level AP

DBNetworkStack is a network abstraction for fetching request and mapping them to model objects

DBNetworkStack Main Features 🛡 Typed network resources 🏠 Value oriented architecture 🔀 Exchangeable implementations 🚄 Extendable API 🎹 Composable

Releases(0.2.0)
  • 0.2.0(Apr 7, 2022)

    This release expands the number of supported HTTP verbs to include PATCH as well as HEAD and others like CONNECT, TRACE and OPTIONS.

    tvOS Support is also enabled in this release.

    Source code(tar.gz)
    Source code(zip)
  • 0.1.0(Apr 6, 2022)

    Summary

    This is the initial alpha release of 'Mu'. I hope to increase test coverage and receive feedback a bit before releasing an official 1.0.0 release.

    Source code(tar.gz)
    Source code(zip)
Owner
Nicholas Maccharoli
Day job is iOS / Swift dev mostly, Python and Golang enthusiast. Coding with love since 2007.
Nicholas Maccharoli
AsyncHTTP - Generic networking library written using Swift async/await

Generic networking library written using Swift async/await

Laszlo Teveli 7 Aug 3, 2022
An Generic HTTP Request Library For Swift

GRequest An HTTP request library written in Swift. ##Basic Usage Be simple, as it should be: Request("https://api.github.com/repos/lingoer/SwiftyJSON/

Ruoyu Fu 114 Oct 18, 2022
A web API client in Swift built using Async/Await

Get A modern web API client in Swift built using Async/Await and Actors. let cli

Alexander Grebenyuk 745 Jan 3, 2023
iOS 15, MVVM, Async Await, Core Data, Abstract Network Layer, Repository & DAO design patterns, SwiftUI and Combine

iOS 15, MVVM, Async Await, Core Data, Abstract Network Layer, Repository & DAO design patterns, SwiftUI and Combine

Conrado Mateu Gisbert 18 Dec 23, 2022
Swift async/await based socket

Socket Swift async/await based socket library Introduction This library exposes an idiomatic Swift API for interacting with POSIX sockets via an async

null 89 Dec 29, 2022
This package is meant to make http request of an easy way inspiren in the architecture of Moya package

NetworkAgent This package is meant to make http request of an easy way inspiren in the architecture of Moya package. This package is 100% free of depe

Angel Rada 19 Sep 8, 2022
Minimalistic Swift HTTP request agent for iOS and OS X

Agent Table of Contents Introduction Usage HTTP Verbs Overloading Method Chaining Response Closure Verbs Methods NSMutableURLRequest Contributing Lice

null 589 Jun 29, 2022
Http Request wrapper written in Swift

Net Net is a HttpRequest wrapper written in Swift Features GET, POST, PUT, DELETE method Powerful request params: nested params, number, string, dic,

Le Van Nghia 304 Jun 29, 2022
iONess is HTTP Request Helper for iOS platform used by HCI iOS App

iONess iONess (iOS Network Session) is HTTP Request Helper for the iOS platform used by Home Credit Indonesia iOS App. It uses Ergo as a concurrent he

OSFE Homecredit Indonesia 1 Mar 28, 2022
Deal with query items, HTTP headers, request body and more in an easy, declarative way

Reusable system for complex URL requests with Swift. Deal with query items, HTTP headers, request body and more in an easy, declarative way. Check out our engineering blog to learn more!

Parable Health 19 Sep 5, 2022