Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created January 12, 2022 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/0432bc996a47eb89fd3b9fb1c685a0c4 to your computer and use it in GitHub Desktop.
Save robertmryan/0432bc996a47eb89fd3b9fb1c685a0c4 to your computer and use it in GitHub Desktop.
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)
}
@robertmryan
Copy link
Author

URLComponents is a more robust way to percent escape parameters in a URL.

@robertmryan
Copy link
Author

(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)]

@ArnavMotwani
Copy link

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)")]

@robertmryan
Copy link
Author

Or should it be as follows?

components?.queryItems = [URLQueryItem(name: "isbn", value: identifier)]

@ArnavMotwani
Copy link

isbn=identifier is a value of q so I think components?.queryItems = [URLQueryItem(name: "q", value: "isbn=\(identifier)")] is correct

@robertmryan
Copy link
Author

Yep, indeed. Very weird endpoint.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment