Skip to content

Instantly share code, notes, and snippets.

@shuuji3
Created February 4, 2022 01:18
Show Gist options
  • Save shuuji3/99a41b608ad9b1ca13d2e1b88af6118c to your computer and use it in GitHub Desktop.
Save shuuji3/99a41b608ad9b1ca13d2e1b88af6118c to your computer and use it in GitHub Desktop.
Google Books API を使って書籍情報の JSON を取得するスクリプト
/**
* Google Books API を使って書籍情報の JSON を取得する。
*
* @param {string} isbn - 書籍の ISBN
* @return {object}
*
* @see Using the API  |  Google Books APIs  |  Google Developers
* - https://developers.google.com/books/docs/v1/using#PerformingSearch
* @see Error: "Cannot determine user location for geographically restricted operation."
* - Google プロダクト フォーラム - https://productforums.google.com/forum/#!msg/books-api/cK8VJUhRl9w/rx-8HPDy8FIJ
* @see Google Apps ScriptでWeb上にあるJsonデータを取得してSpreadSheetに入力する - Qiita
* - https://qiita.com/tentatsu/items/8ec2766361e70db2429a#googleappscript%E3%81%A7json%E3%83%87%E3%83%BC%E3%82%BF%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B
*/
function getBookInfo(isbn) {
// ISBN に '-' などが含まれているとエラーになるので、数字以外を削除する。
const url = 'https://www.googleapis.com/books/v1/volumes?country=JP&q=isbn:' + String(isbn).replace(/\D/g, '');
const data = JSON.parse(UrlFetchApp.fetch(url).getContentText());
const books = data.items;
if (books === undefined) {
return '';
}
return JSON.stringify(books[0].volumeInfo);
}
/**
* 書影の URL を取得する。
*
* @param {string} data - getBookInfo() で取得した書籍データ
* @return {string} 書籍の書影の URL
*/
function getBookThumbnailURL(bookInfoJsonString) {
const bookInfo = JSON.parse(bookInfoJsonString);
// ref: File:No image available 450 x 600.svg - Wikimedia Commons - https://commons.wikimedia.org/wiki/File:No_image_available_450_x_600.svg
const noImageURL = 'https://upload.wikimedia.org/wikipedia/commons/1/16/No_image_available_450_x_600.svg';
// Google Book API でヒットしなかった場合は「No Iamge Available」画像を返す。
if (bookInfo === '') {
return noImageURL;
}
// サムネイルが存在しない場合も「No Iamge Available」画像を返す。
const imageLinks = bookInfo.imageLinks;
if (imageLinks === undefined) {
return noImageURL;
}
const thumbnailURL = imageLinks.smallThumbnail;
Logger.log(thumbnailURL);
return thumbnailURL;
}
function getJsonValueFromString(jsonString, key) {
const json = JSON.parse(jsonString);
return json[key];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment