uhooi/swift-http-client
Communicate via HTTP easily in Swift.
Table of Contents
System requirements
- Swift: 5.5+
- Xcode: 13.0+
- macOS: 11.3+
Installation
Swift Package Manager (Recommended)
Package
You can add this package to Package.swift, include it in your target dependencies.
let package = Package(
dependencies: [
.package(url: "https://github.com/uhooi/swift-http-client", .upToNextMajor(from: "0.6.0")),
],
targets: [
.target(
name: "<your-target-name>",
dependencies: ["HTTPClient"]),
]
)Xcode
You can add this package on Xcode. See documentation.
CocoaPods
This library is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'UHIHTTPClient', '~> 0.6.0'Carthage
This library is available through Carthage. To install it, simply add the following line to your Cartfile:
github "uhooi/swift-http-client" ~> 0.6.0How to use
You can just import HTTPClient to use it.
- Implement a request body structure that conforms to the
Encodableprotocol. (Optional)
``swift struct RegisterUserRequestBody: Encodable { let name: String let description: String } ``
- Implement a response body structure that conforms to the
Decodableprotocol.
```swift struct RegisterUserResponseBody: Decodable { let id: String }
extension RegisterUserResponseBody { func convertToUserID() -> UserID { .init(id: self.id) } } ```
- Implement a request structure that conforms to the
Requestprotocol.
```swift import HTTPClient
struct RegisterUserRequest: Request { typealias ResponseBody = RegisterUserResponseBody var path: String { "user/create_user" } var httpMethod: HTTPMethod { .post } var httpHeaders: [HTTPHeaderField: String]? { [.contentType: ContentType.applicationJson.rawValue] } } ```
- Create an instance of the
HTTPClientclass and call therequestmethod.
``swift struct UserID: Identifiable, Equatable { let id: String } ``
``swift protocol VersatileRepository { func registerUser(name: String, description: String) async throws -> UserID } ``
```swift import HTTPClient
final class VersatileAPIClient { static let shared = VersatileAPIClient()
private let httpClient = HTTPClient(baseURLString: "https://example.com/api/") }
extension VersatileAPIClient: VersatileRepository { func registerUser(name: String, description: String) async throws -> UserID { let requestBody = RegisterUserRequestBody(name: name, description: description) let responseBody = try await httpClient.request(RegisterUserRequest(), requestBody: requestBody) return responseBody.convertToUserID() } } ```
``swift do { let userID = try await VersatileAPIClient.shared.registerUser(name: "Uhooi", description: "Green monster.") // Do something. } catch { // Do error handling. print(error) } ``
Contribution
I would be happy if you contribute :)
Stats
[[Stats]](https://github.com/uhooi/swift-http-client)
Package Metadata
Repository: uhooi/swift-http-client
Default branch: main
README: README.md