AsyncHTTPClient
This package provides an HTTP Client library built on top of SwiftNIO.
This library provides the following:
- First class support for Swift Concurrency
- Asynchronous and non-blocking request methods
- Simple follow-redirects (cookie headers are dropped)
- Streaming body download
- TLS support
- Automatic HTTP/2 over HTTPS
- Cookie parsing (but not storage)
Getting Started
Adding the dependency
Add the following entry in your Package.swift to start using HTTPClient:
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.9.0")
and AsyncHTTPClient dependency to your target:
.target(name: "MyApp", dependencies: [.product(name: "AsyncHTTPClient", package: "async-http-client")]),
Request-Response API
The code snippet below illustrates how to make a simple GET request to a remote server.
import AsyncHTTPClient
/// MARK: - Using Swift Concurrency
let request = HTTPClientRequest(url: "https://apple.com/")
let response = try await HTTPClient.shared.execute(request, timeout: .seconds(30))
print("HTTP head", response)
if response.status == .ok {
let body = try await response.body.collect(upTo: 1024 * 1024) // 1 MB
// handle body
} else {
// handle remote error
}
/// MARK: - Using SwiftNIO EventLoopFuture
HTTPClient.shared.get(url: "https://apple.com/").whenComplete { result in
switch result {
case .failure(let error):
// process error
case .success(let response):
if response.status == .ok {
// handle response
} else {
// handle remote error
}
}
}
If you create your own HTTPClient instances, you should shut them down using httpClient.shutdown() when you're done using them. Failing to do so will leak resources.
Please note that you must not call httpClient.shutdown before all requests of the HTTP client have finished, or else the in-flight requests will likely fail because their network connections are interrupted.
async/await examples
Examples for the async/await API can be found in the Examples folder in this Repository.
Usage guide
The default HTTP Method is GET. In case you need to have more control over the method, or you want to add headers or body, use the HTTPClientRequest struct:
Using Swift Concurrency
import AsyncHTTPClient
do {
var request = HTTPClientRequest(url: "https://apple.com/")
request.method = .POST
request.headers.add(name: "User-Agent", value: "Swift HTTPClient")
request.body = .bytes(ByteBuffer(string: "some data"))
let response = try await HTTPClient.shared.execute(request, timeout: .seconds(30))
if response.status == .ok {
// handle response
} else {
// handle remote error
}
} catch {
// handle error
}
Using SwiftNIO EventLoopFuture
import AsyncHTTPClient
var request = try HTTPClient.Request(url: "https://apple.com/", method: .POST)
request.headers.add(name: "User-Agent", value: "Swift HTTPClient")
request.body = .string("some-body")
HTTPClient.shared.execute(request: request).whenComplete { result in
switch result {
case .failure(let error):
// process error
case .success(let response):
if response.status == .ok {
// handle response
} else {
// handle remote error
}
}
}
Redirects following
The globally shared instance HTTPClient.shared follows redirects by default. If you create your own HTTPClient, you can enable the follow-redirects behavior using the client configuration:
let httpClient = HTTPClient(eventLoopGroupProvider: .singleton,
configuration: HTTPClient.Configuration(followRedirects: true))
Timeouts
Timeouts (connect and read) can also be set using the client configuration:
let timeout = HTTPClient.Configuration.Timeout(connect: .seconds(1), read: .seconds(1))
let httpClient = HTTPClient(eventLoopGroupProvider: .singleton,
configuration: HTTPClient.Configuration(timeout: timeout))
or on a per-request basis:
httpClient.execute(request: request, deadline: .now() + .milliseconds(1))
Streaming
When dealing with larger amount of data, it's critical to stream the response body instead of aggregating in-memory.
The following example demonstrates how to count the number of bytes in a streaming response body:
Using Swift Concurrency
do {
let request = HTTPClientRequest(url: "https://apple.com/")
let response = try await HTTPClient.shared.execute(request, timeout: .seconds(30))
print("HTTP head", response)
// if defined, the content-length headers announces the size of the body
let expectedBytes = response.headers.first(name: "content-length").flatMap(Int.init)
var receivedBytes = 0
// asynchronously iterates over all body fragments
// this loop will automatically propagate backpressure correctly
for try await buffer in response.body {
// for this example, we are just interested in the size of the fragment
receivedBytes += buffer.readableBytes
if let expectedBytes = expectedBytes {
// if the body size is known, we calculate a progress indicator
let progress = Double(receivedBytes) / Double(expectedBytes)
print("progress: \(Int(progress * 100))%")
}
}
print("did receive \(receivedBytes) bytes")
} catch {
print("request failed:", error)
}
Using HTTPClientResponseDelegate and SwiftNIO EventLoopFuture