Swift HTTP for Humans

Overview

Supported Flatform CocoaPods Carthage compatible Build Status

Just is a client-side HTTP library inspired by python-requests - HTTP for Humans.

Features

Just lets you to the following effortlessly:

  • URL queries
  • custom headers
  • form (x-www-form-encoded) / JSON HTTP body
  • redirect control
  • multipart file upload along with form values.
  • basic/digest authentication
  • cookies
  • timeouts
  • synchronous / asynchronous requests
  • upload / download progress tracking for asynchronous requests
  • link headers
  • friendly accessible results

Use

The simplest request with Just looks like this:

//  A simple get request
Just.get("http://httpbin.org/get")

The next example shows how to upload a file along with some data:

//  talk to registration end point
let r = Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .url(fileURLWithPath:"flash.jpeg", nil)]
)

if r.ok { /* success! */ }

Here's the same example done asynchronously:

//  talk to registration end point
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .url(fileURLWithPath:"flash.jpeg", nil)]
) { r in
    if r.ok { /* success! */ }
}

Read Getting Started on the web or in this playground to learn more!

Install

Here are some ways to leverage Just.

Xcode

Add https://github.com/dduan/Just.git the usual way.

Swift Package Manager

Add the following to your dependencies:

.package(url: "https://github.com/dduan/Just.git",  from: "0.8.0")

… and "Just" to your target dependencies.

Carthage

Include the following in your Cartfile:

github "dduan/Just"

Just includes dynamic framework targets for both iOS and OS X.

CocoaPods

The usual way:

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
  pod 'Just'
end

Manual

Drop Just.xcodeproj into your project navigator. Under the General tab of your project settings, use the plus sign to add Just.framework to Linked Framework and Libraries. Make sure to include the correct version for your target's platform.

It's also common to add Just as a git submodule to your projects repository:

cd path/to/your/project
git submodule add https://github.com/dduan/Just.git

Source File

Put Just.swift directly into your project. Alternately, put it in the Sources folder of a playground. (The latter makes a fun way to explore the web.)

Contribute

Pull requests are welcome. Here are some tips for code contributors:

Work in Just.xcworkspace.

The tests for link headers relies on Github APIs, which has a low per-hour limit. To overcome this, you can edit the Xcode build schemes and add environment variables GITHUB_TOKEN. Learn more about personal tokens here.

For Xcode rebels, checkout Makefile.

HTML documentation pages are generated by literate programmin tool docco

License

MIT, see LICENSE.md.

Comments
  • Custom headers?

    Custom headers?

    Hey 😬 I can see through the code that indeed the library support custom headers, anywhere you can point me in the docs for it? Can't seem to find anything

    opened by raulriera 7
  • swift4, xcode 9.2 errors

    swift4, xcode 9.2 errors

    hi, i get the following errors

    Cannot convert return expression of type 'Dictionary<Key, Value>.Values' to return type 'LazyMapCollection<[Key : Value], Value>'

    lines 330-333

      public var keys: LazyMapCollection<[Key : Value], Key> {
        return _data.keys
      }
      public var values: LazyMapCollection<[Key : Value], Value> {
        return _data.values
      }
    

    i didn't see the "values" being used anywhere?? i commented out the lines and checked a couple of files and servers and got back the correct GET/POST

    opened by gaming-hacker 6
  • Can't get asyncProgressHandler to work with UI components

    Can't get asyncProgressHandler to work with UI components

    Hi, First of all, great library. thanks. I'm updating UI components in the main thread as recommended but still can't get the UIprogressView work although console print works fine.

    What is wrong here?

     Just.post("https://httpbin.org/post",
                       files:["sample": .url(sampleFile, nil)],
                       asyncProgressHandler:{ p in
                           print(p.percent)
                           DispatchQueue.main.async(execute: {
                                   self.progressView.setProgress(p.percent, animated: false)
                            })
              })
    
    
    opened by alperkal 5
  • Asynchronous Callback

    Asynchronous Callback

    My app crashing using asynchronous callback but works fine when switching to synchronous mode. I dont know why.

    Pseudo Sample: APP CRASHING: Just.post( "http://justiceleauge.org/member/register", data: ["username": "barryallen", "password":"ReverseF1ashSucks"], files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)] ) { r in if r.ok { /* SOME CODE HERE! */ } }

    THIS WORKS: let r = Just.post( "http://justiceleauge.org/member/register", data: ["username": "barryallen", "password":"ReverseF1ashSucks"], files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)] )

    if r.ok { /* SOME CODE HERE! */ }

    opened by aguel 5
  • Xcode 9 beta 3 error

    Xcode 9 beta 3 error

    When I run, these error occurs:

    Cannot convert return expression of type 'Dictionary<Key, Value>.Keys' to return type 'LazyMapCollection<[Key : Value], Key>'

    Cannot convert return expression of type 'Dictionary<Key, Value>.Values' to return type 'LazyMapCollection<[Key : Value], Value>'

    opened by raffaelps 4
  • File Upload issue on PHP Handler (Swift 3 / XCode 8)

    File Upload issue on PHP Handler (Swift 3 / XCode 8)

    Im currently on XCode 8 with Swift 3 and i have a PHP file upload handler in the server side. Using the provided playground file, and basically just changing the POST URL to my PHP handler, upload doesnt work (file not reaching the server) but no error whatsoever. Fyi, i used another swift HTTP client (Swift 2.x version compatible) with the same PHP handler and it is working fine.

    From playground: let elonPhotoURL = Bundle.main.url(forResource: "elon", withExtension: "jpg")! let uploadResult = Just.post("**http://xxxx.com/uploader.php**", files:["elon": .url(elonPhotoURL, "image/jpeg")]) // <== that's it print(uploadResult.text ?? "")

    Not sure if this log info will help? "iSignature[10575:3106978] bool _WebTryThreadLock(bool), 0x7960e950: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now..."

    opened by aguel 4
  • Can't build with Xcode 8 Beta 6

    Can't build with Xcode 8 Beta 6

    I'm trying to use Just in an iOS 10 message extension. Due to various issues, Cocoapods isn't working for me, so I've tried dropping in Just.swift, but I get a whole mess of compile errors, some I don't feel confident about fixing.

    Has Swift 3 syntax changed since your last build?

    opened by randyhill 4
  • Modified to match latest Swift 3 syntax

    Modified to match latest Swift 3 syntax

    I modified the following (These were causing compilation issues):

    in line 698: Before:

    for key in Array(parameters.keys).sorted(isOrderedBefore: <) {
                let value: AnyObject! = parameters[key]
                components += self.queryComponents(key, value)
    }
    

    After:

    for key in Array(parameters.keys).sorted(by: <){
                let value: AnyObject! = parameters[key]
                components += self.queryComponents(key, value)
    }
    

    in line 739: Before:

    if let component = URL.lastPathComponent {
                        partFilename = component
    }
    

    After:

    if let component:String = URL.lastPathComponent {
                        partFilename = component
    }
    
    opened by Minitour 4
  • [Fixes #30] Ensure threads are not left hanging, if the request times out

    [Fixes #30] Ensure threads are not left hanging, if the request times out

    Sorry for jumping the gun, but we are in a bit of a hurry to get the app out for testing and this is a blocker for us.

    Happy to make whatever changes deemed necessary to the patch; in particular, I'm not sure anything should be done in case of timeouts, maybe return nil instead of the response?

    opened by massenz 4
  • Timeouts leave threads hanging

    Timeouts leave threads hanging

    I believe I've come across an issue when running requests in many threads (one thread per request) and some (but not all) of them time out.

    The timeouts seem to be "honored" but the thread that initiated the request is left waiting for a semaphore: doing some debugging in Xcode's thread view, I noticed all the threads were stuck on this line:

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
    

    when I changed it to something like:

                            let NSEC: Int64 = {
                                var base: Int64 = 1
                                for _ in 1...9 {
                                    base *= 10
                                }
                                return base
                            }()
    
                            let tint: Int64 = Int64(timeout ?? 10.0)
                            let how_long = dispatch_time(DISPATCH_TIME_NOW, tint * NSEC)
    
                            dispatch_semaphore_wait(semaphore, how_long)
    

    my code now runs without problem, I can see threads being created then destroyed, and it's now been running for > 1 hour without any issue (it used to just crash and die with a hundred or so of hung threads in a couple of minutes).

    If you want, I'd be happy to polish the fix and push a PR?

    opened by massenz 4
  • Targeted iOS v8.0

    Targeted iOS v8.0

    There's no reason I can see that Just needs to target 8.3, so I've flipped it to 8.0, we have a 40% non 8.3 userbase and I imagine that number is reflected in other codebases.

    opened by zdavison 4
  • Utilizing r.json response?

    Utilizing r.json response?

    Apologies if this is a dumb question, but I am relatively new to Swift. I've implemented this in a little sandbox and can properly make a post call to my end point and get a proper response.

    I'm very familiar with Python requests, so I was hoping that I would be able to address the r.json object similarly in Swift, but no matter what I do, I can't seem to figure out how to actually get key out of the r.json object. I can print it and see it is valid, but when I try to something simple (in my mind) like print(r.json["my_key"]) I can't.

    This is probably more of a lack of understanding of the object type that r.json returns in swift and how to get info out of it, but I figured I'd ask because I love the idea of just using my familiarity with Python requests to start my voyage into Swift programming.

    opened by szumlins 2
  • It seems like `asyncCompletionHandler` is executed before download task is done

    It seems like `asyncCompletionHandler` is executed before download task is done

    i tried this

    Just.get(url, params: params, headers: headers) { response in
           if response.status.code == 200 {
                  let json = JSON(response.json!) 
                  .......
          }
    }
    

    we managed, to log the content. response.json returns nil because it is not in full response. sample:

    {
        order: {
             'id':  1,
             'notes': ''
        }
    

    swift 5 xcode 11.2.1 we can't reproduce this. Only happens in production Thanks

    opened by marsha97 1
  • Just.get() crash when `makeTask`

    Just.get() crash when `makeTask`

    syncBookingCrash

    just_get_crash

    make_task_crash

    Crashed: com.apple.main-thread
    0  libswiftCore.dylib             0x1977b1138 swift_isUniquelyReferenced_nonNull_native + 28
    1  Just                           0x105372530 specialized Dictionary._Variant.setValue(_:forKey:) + 44 (<compiler-generated>:44)
    2  Just                           0x10536d83c HTTP.makeTask(_:configuration:) + 420 (<compiler-generated>:420)
    3  Just                           0x105370c9c HTTP.request(_:url:params:data:json:headers:files:auth:cookies:redirects:timeout:urlQuery:requestBody:asyncProgressHandler:asyncCompletionHandler:) + 1009 (Just.swift:1009)
    4  Just                           0x1053715d0 protocol witness for JustAdaptor.request(_:url:params:data:json:headers:files:auth:cookies:redirects:timeout:urlQuery:requestBody:asyncProgressHandler:asyncCompletionHandler:) in conformance HTTP + 96 (<compiler-generated>:96)
    5  Just                           0x10536c71c JustOf.delete(_:params:data:json:headers:files:auth:cookies:allowRedirects:timeout:urlQuery:requestBody:asyncProgressHandler:asyncCompletionHandler:) + 364
    6  Just                           0x10536c39c JustOf.get(_:params:data:json:headers:files:auth:cookies:allowRedirects:timeout:urlQuery:requestBody:asyncProgressHandler:asyncCompletionHandler:) + 92
    7  Houzcall                       0x104490fc4 showRateBookingControllerIfNeeded(_:) + 387 (Utils.swift:387)
    8  Houzcall                       0x1044c0134 partial apply for closure #1 in closure #1 in closure #1 in BookingDetailsViewController.syncBookings(_:) + 130 (BookingDetailsViewController.swift:130)
    9  Houzcall                       0x1045289c4 thunk for @escaping @callee_guaranteed () -> () + 4376988100 (<compiler-generated>:4376988100)
    10 libdispatch.dylib              0x18a075610 _dispatch_call_block_and_release + 24
    11 libdispatch.dylib              0x18a076184 _dispatch_client_callout + 16
    12 libdispatch.dylib              0x18a05935c _dispatch_main_queue_callback_4CF$VARIANT$armv81 + 996
    13 CoreFoundation                 0x18a3263c4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
    14 CoreFoundation                 0x18a3213b8 __CFRunLoopRun + 2004
    15 CoreFoundation                 0x18a3208bc CFRunLoopRunSpecific + 464
    16 GraphicsServices               0x19418c328 GSEventRunModal + 104
    17 UIKitCore                      0x18e3b66d4 UIApplicationMain + 1936
    18 Houzcall                       0x104424764 main + 21 (AppDelegate.swift:21)
    19 libdyld.dylib                  0x18a1ab460 start + 4
    

    Hi @dduan currently I found a problem when trying to do Just.get(). from what I see, there is a possibility when doing Just.get() the request is nil when trying to makeTask

    // Just.swift
    ...
    public func synthesizeRequest(...) -> URLRequest?
    ...
    func makeTask(_ request: URLRequest, configuration: TaskConfiguration)
        -> URLSessionDataTask?
    ...
    guard let request = synthesizeRequest()
    ...
    // variabel `request` below can be `nil`
    if let task = makeTask(request, configuration: config) {
        task.resume()
    }
    

    isn't synthesizeRequest() supposed return URLRequest without nil?

    This only happens in production build and I can't reproduce the crash. Xcode 11.1 Swift 5

    opened by j-elmer123 2
  • Does Just follow redirect links?

    Does Just follow redirect links?

    I want to get the real link of a page from a link that redirects, such as this: https://apple.news/AQZXxg8mUQfKrEaM9MRBpxw . However, when I do

        Just.get("https://apple.news/AQZXxg8mUQfKrEaM9MRBpxw")
        { r in
            
            print(r.statusCode)
            print(r.url)
        }
    

    it still prints the same link. Does Just not get real redirect links or am I doing it wrong?

    opened by tetrahed 0
Releases(0.8.0)
Owner
Daniel Duan
https://duan.ca
Daniel Duan
Http - Demo for Http Layer

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

null 0 Jan 24, 2022
Elegant HTTP Networking in Swift

Alamofire is an HTTP networking library written in Swift. Features Component Libraries Requirements Migration Guides Communication Installation Usage

Alamofire 38.7k Jan 8, 2023
Versatile HTTP Networking in Swift

Net is a versatile HTTP networking library written in Swift. ?? Features URL / JSON / Property List Parameter Encoding Upload File / Data / Stream / M

Intelygenz 124 Dec 6, 2022
🏇 A Swift HTTP / HTTPS networking library just incidentally execute on machines

Thus, programs must be written for people to read, and only incidentally for machines to execute. Harold Abelson, "Structure and Interpretation of Com

John Lui 845 Oct 30, 2022
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
Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.

SwiftHTTP SwiftHTTP is a thin wrapper around NSURLSession in Swift to simplify HTTP requests. Features Convenient Closure APIs Simple Queue Support Pa

Dalton 1.9k Dec 7, 2022
A barebones Swift HTTP client with automatic JSON response parsing.

HTTP Client A barebones Swift HTTP client with automatic JSON response parsing. Installation Add HTTP Client as a dependency through Xcode or directly

Joe Masilotti 30 Oct 11, 2022
A Swift web framework and HTTP server.

A Swift Web Framework and HTTP Server Summary Kitura is a web framework and web server that is created for web services written in Swift. For more inf

Kitura 7.6k Jan 6, 2023
Tiny http server engine written in Swift programming language.

What is Swifter? Tiny http server engine written in Swift programming language. Branches * stable - lands on CocoaPods and others. Supports the latest

null 3.6k Dec 31, 2022
A lightweight library for writing HTTP web servers with Swift

Taylor Disclaimer: Not actively working on it anymore. You can check out some alternatives Swift 2.0 required. Working with Xcode 7.1. Disclaimer: It

Jorge Izquierdo 925 Nov 17, 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
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

Envoy 540 Dec 15, 2022
Swift HTTP server using the pre-fork worker model

Curassow Curassow is a Swift Nest HTTP Server. It uses the pre-fork worker model and it's similar to Python's Gunicorn and Ruby's Unicorn. It exposes

Kyle Fuller Archive 397 Oct 30, 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
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

Always Right Institute 116 Aug 6, 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
Simple asynchronous HTTP networking class for Swift

YYHRequest YYHRequest is a simple and lightweight class for loading asynchronous HTTP requests in Swift. Built on NSURLConnection and NSOperationQueue

yayuhh 77 May 18, 2022
libuv base Swift web HTTP server framework

Notice Trevi now open a Trevi Community. Yoseob/Trevi project split up into respective Trevi, lime, middlewares and sys packages at our community. If

leeyoseob 46 Jan 29, 2022
A very basic proof-of-concept Swift HTTP server that does not require Foundation

Swift Server Introduction This is very rough and basic HTTP server written in Swift without using Foundation. This is partially based on the Swifter r

Cezary Wojcik 55 Apr 27, 2022