Created
January 12, 2022 14:41
-
-
Save robertmryan/0432bc996a47eb89fd3b9fb1c685a0c4 to your computer and use it in GitHub Desktop.
This file contains 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
func fetchBook(id identifier: String) async throws -> GoogleBook { | |
var components = URLComponents(string: "https://www.googleapis.com/books/v1/volumes") | |
components?.queryItems = [URLQueryItem(name: "q", value: "{" + identifier + "}")] | |
guard let url = components?.url else { throw URLError(.badURL) } | |
let (data, _) = try await URLSession.shared.data(from: url) | |
return try JSONDecoder().decode(GoogleBook.self, from: data) | |
} |
(By the way, the inclusion of the {
and }
is very unusual. I copied this from your code snippet, but generally you would just do
components?.queryItems = [URLQueryItem(name: "q", value: identifier)]
Yep, I noticed that as well. I read the documentation again and realized this call works better: https://www.googleapis.com/books/v1/volumes?q=isbn=identifier
so I changed the queryitems to components?.queryItems = [URLQueryItem(name: "q", value: "isbn=\(identifier)")]
Or should it be as follows?
components?.queryItems = [URLQueryItem(name: "isbn", value: identifier)]
isbn=identifier
is a value of q so I think components?.queryItems = [URLQueryItem(name: "q", value: "isbn=\(identifier)")]
is correct
Yep, indeed. Very weird endpoint.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
URLComponents
is a more robust way to percent escape parameters in a URL.