-
Notifications
You must be signed in to change notification settings - Fork 125
HTTP POST Examples #829
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zamderax
wants to merge
4
commits into
swift-server:main
Choose a base branch
from
zamderax:ma/post-examples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
HTTP POST Examples #829
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
aae1d1b
Rename GetJSON to JSON and add POST example with request/response val…
zamderax 2c8d320
Add HttpBinResponse model and improve JSON example with proper respon…
zamderax 3a141d1
Add note about JSON examples with link to example file in README
zamderax d4a3354
Merge branch 'main' into ma/post-examples
zamderax File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the AsyncHTTPClient open source project | ||
// | ||
// Copyright (c) 2022 Apple Inc. and the AsyncHTTPClient project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import AsyncHTTPClient | ||
import Foundation | ||
import NIOCore | ||
import NIOFoundationCompat | ||
|
||
struct Comic: Codable { | ||
var num: Int | ||
var title: String | ||
var day: String | ||
var month: String | ||
var year: String | ||
var img: String | ||
var alt: String | ||
var news: String | ||
var link: String | ||
var transcript: String | ||
} | ||
|
||
// Structure to match httpbin.org response format | ||
struct HttpBinResponse: Codable { | ||
let json: Comic | ||
let url: String | ||
let headers: [String: String] | ||
let origin: String | ||
let data: String? | ||
let form: [String: String]? | ||
let files: [String: String]? | ||
} | ||
|
||
@main | ||
struct JSON { | ||
|
||
static func main() async throws { | ||
try await getJSON() | ||
try await postJSON() | ||
} | ||
|
||
static func getJSON() async throws { | ||
let httpClient = HTTPClient(eventLoopGroupProvider: .singleton) | ||
do { | ||
let request = HTTPClientRequest(url: "https://xkcd.com/info.0.json") | ||
let response = try await httpClient.execute(request, timeout: .seconds(30)) | ||
print("HTTP head", response) | ||
let body = try await response.body.collect(upTo: 1024 * 1024) // 1 MB | ||
// we use an overload defined in `NIOFoundationCompat` for `decode(_:from:)` to | ||
// efficiently decode from a `ByteBuffer` | ||
let comic = try JSONDecoder().decode(Comic.self, from: body) | ||
dump(comic) | ||
} 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() | ||
} | ||
|
||
static func postJSON() async throws { | ||
let httpClient = HTTPClient(eventLoopGroupProvider: .singleton) | ||
|
||
let comic: Comic = Comic( | ||
num: 0, | ||
title: "Adventures of Super Sally", | ||
day: "17", | ||
month: "4", | ||
year: "2025", | ||
img: "https://www.w3.org/Icons/w3c_main.png", | ||
alt: "Adventures of Super Sally, a super hero with many powers", | ||
news: "Today we learn about super heroes!", | ||
link: "http://comics.com/super-sally", | ||
transcript: "Once upon a time, there was a super hero named Super Sally. She had many powers and was a hero to many." | ||
) | ||
|
||
do { | ||
var request = HTTPClientRequest(url: "https://httpbin.org/post") | ||
request.headers.add(name: "Content-Type", value: "application/json") | ||
request.headers.add(name: "Accept", value: "application/json") | ||
request.method = .POST | ||
|
||
let jsonData = try JSONEncoder().encode(comic) | ||
request.body = .bytes(jsonData) | ||
|
||
let response = try await httpClient.execute(request, timeout: .seconds(30)) | ||
let responseBody = try await response.body.collect(upTo: 1024 * 1024) // 1 MB | ||
// we use an overload defined in `NIOFoundationCompat` for `decode(_:from:)` to | ||
// efficiently decode from a `ByteBuffer` | ||
|
||
// httpbin.org returns a JSON response that wraps our posted data in a "json" field | ||
let httpBinResponse = try JSONDecoder().decode(HttpBinResponse.self, from: responseBody) | ||
let returnedComic = httpBinResponse.json | ||
|
||
// Verify the data matches what we sent | ||
assert(comic.title == returnedComic.title) | ||
assert(comic.img == returnedComic.img) | ||
assert(comic.alt == returnedComic.alt) | ||
assert(comic.day == returnedComic.day) | ||
assert(comic.month == returnedComic.month) | ||
assert(comic.year == returnedComic.year) | ||
assert(comic.num == returnedComic.num) | ||
assert(comic.transcript == returnedComic.transcript) | ||
assert(comic.news == returnedComic.news) | ||
assert(comic.link == returnedComic.link) | ||
dump(returnedComic) | ||
} 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() | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the readme change here is probably unnecessary: it doesn't fit with the flow of the README. A small callout at the bottom is fine.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Alright I moved the link to the bottom
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doesn't look like you pushed any chance here.