Skip to content

Commit 30888c2

Browse files
committed
First commit
0 parents  commit 30888c2

File tree

8 files changed

+236
-0
lines changed

8 files changed

+236
-0
lines changed

.gitignore

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
.DS_Store
2+
/.build
3+
/Packages
4+
xcuserdata/
5+
DerivedData/
6+
.swiftpm/configuration/registries.json
7+
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
8+
.netrc
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>IDEDidComputeMac32BitWarning</key>
6+
<true/>
7+
</dict>
8+
</plist>

Package.swift

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// swift-tools-version: 5.9
2+
// The swift-tools-version declares the minimum version of Swift required to build this package.
3+
4+
import PackageDescription
5+
6+
let package = Package(
7+
name: "JSONHTTPClient",
8+
platforms: [.iOS("13.0"), .macOS(.v12)],
9+
products: [
10+
// Products define the executables and libraries a package produces, making them visible to other packages.
11+
.library(
12+
name: "JSONHTTPClient",
13+
targets: ["JSONHTTPClient"]),
14+
],
15+
targets: [
16+
// Targets are the basic building blocks of a package, defining a module or a test suite.
17+
// Targets can depend on other targets in this package and products from dependencies.
18+
.target(
19+
name: "JSONHTTPClient"),
20+
.testTarget(
21+
name: "JSONHTTPClientTests",
22+
dependencies: ["JSONHTTPClient"]),
23+
]
24+
)

README.md

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
## Overview
2+
3+
This package is meant as a very simple HTTP client for use in HTTP connections that return JSON data. It only implements GET and POST URL methods.
4+
5+
Methods available:
6+
7+
```Swift
8+
func get<T: Decodable>(_ url: URL, headers httpHeaders: [String: String]?) async throws -> T
9+
10+
func postJSON<T: Decodable>(_ url: URL, body: Data, httpHeaders: [String: String]?) async throws -> T
11+
```
12+
13+
Note that the ```postJSON``` method automatically adds **{ "Content-Type": "application.json" }** to the URLRequest headers.
14+
15+
The POST method's ```Data``` parameter doesn't need to be JSON related, but the method expects that some serialized JSON data will be returned, which it will try to decode to the type specified on it's invocation.
16+
17+
### Usage examples:
18+
19+
```Swift
20+
public struct MovieSummary: Codable {
21+
public let id: Int
22+
public let overview: String
23+
public let posterPath: String
24+
public let releaseDate: String
25+
public let title: String
26+
public let voteAverage: Double
27+
}
28+
29+
final class MoviesAPI {
30+
func fetchPopularMovies() async throws -> [MovieSummary] {
31+
let popularMoviesPage: MovieSummariesPage = try await JSONHttpClient.shared.get(popularMoviesURL, headers: apiHeaders)
32+
return popularMoviesPage.movieSummaries
33+
}
34+
}
35+
36+
```
37+
*The example above uses the [The Movie Database](https://www.themoviedb.org/) free API to fetch popular movies and related info.
38+
39+
## Supported iOS Versions
40+
41+
This package is meant to work with iOS 13 onwards.
42+
43+
## Contact
44+
45+
otaviokz@gmail.com
46+
47+
[otaviokz.com](https://otaviokz.com)
48+
49+
[linkedin.com/in/otaviokz](http://www.linkedin.com/in/otaviokz)
50+
51+
## Licensing
52+
53+
#### <p>``` MIT Lisense ```</p>
54+
55+
Copyright (c) 2024 Otavio Zabaleta
56+
57+
Permission is hereby granted, free of charge, to any person obtaining a copy
58+
of this software and associated documentation files (the "Software"), to deal
59+
in the Software without restriction, including without limitation the rights
60+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
61+
copies of the Software, and to permit persons to whom the Software is
62+
furnished to do so, subject to the following conditions:
63+
64+
The above copyright notice and this permission notice shall be included in all
65+
copies or substantial portions of the Software.
66+
67+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
68+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
69+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
70+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
71+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
72+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
73+
SOFTWARE.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// The Swift Programming Language
2+
// https://docs.swift.org/swift-book
3+
4+
import Foundation
5+
6+
@available(iOS 13.0.0, *)
7+
public protocol JSONHTTPClientType {
8+
func get<T: Decodable>(_ url: URL, headers httpHeaders: [String: String]?) async throws -> T
9+
func postJSON<T: Decodable>(_ url: URL, body: Data, httpHeaders: [String: String]?) async throws -> T
10+
}
11+
12+
@available(iOS 13.0.0, *)
13+
public struct JSONHTTPClient: JSONHTTPClientType {
14+
public static let shared = JSONHTTPClient()
15+
16+
private init() {}
17+
18+
public func get<T: Decodable>(_ url: URL, headers httpHeaders: [String: String]?) async throws -> T {
19+
try await connect(.get(url).headers(httpHeaders))
20+
21+
}
22+
23+
public func postJSON<T: Decodable>(_ url: URL, body: Data, httpHeaders: [String: String]?) async throws -> T {
24+
try await connect(.postJSON(body, to: url).headers(httpHeaders))
25+
}
26+
}
27+
28+
@available(iOS 13.0.0, *)
29+
private extension JSONHTTPClient {
30+
func connect<T: Decodable>(_ request: URLRequest) async throws -> T {
31+
let (data, rulResponse) = try await URLSession.shared.data(for: request)
32+
if let httpUrlResponse = rulResponse as? HTTPURLResponse {
33+
guard httpUrlResponse.statusCode == 200 else {
34+
throw JSONHTTPClientError.http(code: httpUrlResponse.statusCode)
35+
}
36+
}
37+
38+
do {
39+
return try JSONDecoder().decode(T.self, from: data)
40+
} catch {
41+
throw JSONHTTPClientError.decode(error)
42+
}
43+
}
44+
}
45+
46+
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
//
2+
// JSONHTTPClientError.swift
3+
//
4+
//
5+
// Created by Otávio Zabaleta on 17/03/2024.
6+
//
7+
8+
import Foundation
9+
10+
public enum JSONHTTPClientError: Error {
11+
case decode(Error)
12+
case http(code: Int)
13+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//
2+
// URLRequests+Utils.swift
3+
//
4+
//
5+
// Created by Otávio Zabaleta on 17/03/2024.
6+
//
7+
8+
import Foundation
9+
10+
enum HTTPMethod: String {
11+
case post = "POST"
12+
case get = "GET"
13+
}
14+
15+
extension URLRequest {
16+
private func method(_ method: HTTPMethod) -> URLRequest {
17+
var request = self
18+
request.httpMethod = method.rawValue
19+
return request
20+
}
21+
22+
func body(_ body: Data) -> URLRequest {
23+
var request = self
24+
request.httpBody = body
25+
return request
26+
}
27+
28+
static func postData(_ body: Data, to url: URL) -> URLRequest {
29+
URLRequest(url: url).method(.post).body(body)
30+
}
31+
32+
static func postJSON(_ body: Data, to url: URL) -> URLRequest {
33+
postData(body, to: url).withJSONHeaders()
34+
}
35+
36+
@inlinable func headers(_ headers: [String: String]?) -> Self {
37+
guard let headers = headers else { return self }
38+
var new = self//editable()
39+
for (field, value) in headers {
40+
new.setValue(value, forHTTPHeaderField: field)
41+
}
42+
return new
43+
}
44+
45+
@inlinable func withJSONHeaders() -> Self {
46+
headers(["application.json": "Content-Type"])
47+
}
48+
49+
static func get(_ url: URL, cachePolicy: CachePolicy = .useProtocolCachePolicy) -> URLRequest {
50+
URLRequest(url: url, cachePolicy: cachePolicy).method(.get)
51+
}
52+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import XCTest
2+
@testable import JSONHTTPClient
3+
4+
final class JSONHTTPClientTests: XCTestCase {
5+
func testExample() throws {
6+
// XCTest Documentation
7+
// https://developer.apple.com/documentation/xctest
8+
9+
// Defining Test Cases and Test Methods
10+
// https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods
11+
}
12+
}

0 commit comments

Comments
 (0)