-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy pathPostJSON.swift
More file actions
35 lines (30 loc) · 1.06 KB
/
PostJSON.swift
File metadata and controls
35 lines (30 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import AsyncHTTPClient
import Foundation
import NIOCore
import NIOFoundationCompat
struct Todo: Codable {
var id: Int?
var userId: Int
var title: String
var completed: Bool
}
@main
struct PostJSON {
static func main() async throws {
let httpClient = HTTPClient(eventLoopGroupProvider: .singleton)
let payload = Todo(userId: 1, title: "Test Todo", completed: false)
do {
let jsonData = try JSONEncoder().encode(payload)
var request = HTTPClientRequest(url: "https://jsonplaceholder.typicode.com/todos")
request.method = .POST
request.headers.add(name: "Content-Type", value: "application/json")
request.body = .bytes(jsonData)
let response = try await httpClient.execute(request, timeout: .seconds(30))
print("HTTP head", response)
} catch {
print("request failed:", error)
}
// it is important to shutdown the httpClient after all requests are done, even if one failed
try await httpClient.shutdown()
}
}