本日の目的・ゴール
目的
外部APIの利用方法を理解する。
ゴール
外部APIのレスポンスをPostmanで確認し、JSONの構造を理解する。
VS CodeでPythonスクリプトを作成し、外部APIを実際に呼び出す。
学んだこと
1.API確認ツールPOSTMANの利用方法
下記の記事を参考にGoogle books APIの動作確認をPOSTMANで行い、APIの具体的なレスポンスを確認した。
Postmanを使ったAPIリクエストとモックAPIの基本操作
https://www.googleapis.com/books/v1/volumes?q=AI
上記のリクエストパラメーターでAIに関連する本を検索
AIに関連する本のレスポンスが複数返ってきた。
一部抜粋👇
{
"kind": "books#volumes",
"totalItems": 1000000,
"items": [
{
"kind": "books#volume",
"id": "vjXVEAAAQBAJ",
"etag": "7JpRdP4Z9xk",
"selfLink": "https://www.googleapis.com/books/v1/volumes/vjXVEAAAQBAJ",
"volumeInfo": {
"title": "AI vs 法 世界で進むAI規制と遅れる日本",
"authors": [
"佐藤洸一"
],
"publisher": "マイナビ出版",
"publishedDate": "2023-08-29",
"description": "ChatGPT、画像生成AIが生み出すリスクは、どう規制されるべきか? ChatGPTや画像生成AIの登場で、AIは急速に日常に根を張りつつあり、各国政府は対策と支援の速度を増しながら、規制のメスを入れつつあります。日本では法制化が遅れている「AI法」について、各国の先駆的な取り組みを紹介し、日本におけるAI規制の今後について提言するとともに、著作権・個人情報・プライバシーなどへの不安、コンテンツ業界への影響などについて「法と倫理」の観点から切り込みます。 序 章 AI時代の幕開け 第1章 画像生成AIの誕生 第2章 画像生成AI vs 著作権 第3章 対話型AIが与えたインパクト 第4章 対話型AI vs 法 第5章 AI vs 倫理 第6章 AI法の誕生 第7章 AI vs プライバシー 東京都行政書士会所属。メル行政書士事務所代表。東京大学法学部第一類卒。行政書士として、 国際業務及び企業法務を中心とする業務の他、生成AIと法に関わる実務の最前線において、AIイラスト投稿掲示板「chichi-pui」をはじめとする新興AIサービスの企業法務サポートなども手掛けている。",
"industryIdentifiers": [
{
"type": "OTHER",
"identifier": "PKEY:BT000142034800100101900209"
}
],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 141,
"printType": "BOOK",
"categories": [
"Business & Economics"
],
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "0.2.2.0.preview.3",
"panelizationSummary": {
"containsEpubBubbles": false,
"containsImageBubbles": false
},
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=vjXVEAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=vjXVEAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "ja",
"previewLink": "http://books.google.co.jp/books?id=vjXVEAAAQBAJ&pg=PP9&dq=AI&hl=&cd=1&source=gbs_api",
"infoLink": "https://play.google.com/store/books/details?id=vjXVEAAAQBAJ&source=gbs_api",
"canonicalVolumeLink": "https://play.google.com/store/books/details?id=vjXVEAAAQBAJ"
},
"saleInfo": {
"country": "JP",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 990,
"currencyCode": "JPY"
},
"retailPrice": {
"amount": 891,
"currencyCode": "JPY"
},
"buyLink": "https://play.google.com/store/books/details?id=vjXVEAAAQBAJ&rdid=book-vjXVEAAAQBAJ&rdot=1&source=gbs_api",
"offers": [
{
"finskyOfferType": 1,
"listPrice": {
"amountInMicros": 990000000,
"currencyCode": "JPY"
},
"retailPrice": {
"amountInMicros": 891000000,
"currencyCode": "JPY"
}
}
]
},
"accessInfo": {
"country": "JP",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.jp/books/download/AI_vs_%E6%B3%95_%E4%B8%96%E7%95%8C%E3%81%A7%E9%80%B2%E3%82%80AI%E8%A6%8F%E5%88%B6%E3%81%A8%E9%81%85-sample-epub.acsm?id=vjXVEAAAQBAJ&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.jp/books/download/AI_vs_%E6%B3%95_%E4%B8%96%E7%95%8C%E3%81%A7%E9%80%B2%E3%82%80AI%E8%A6%8F%E5%88%B6%E3%81%A8%E9%81%85-sample-pdf.acsm?id=vjXVEAAAQBAJ&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://play.google.com/books/reader?id=vjXVEAAAQBAJ&hl=&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "... <b>AI</b> が内部的に実行している演算処理は人間の実際の脳活動のそれとは似ても似つかないにもかかわらず、そこから得られる結果すなわち外形は、人間によるものと見紛うものであることを意味します。たとえば ChatGPT に「 <b>AI</b> とは何か、簡潔に説明して下さい ..."
}
},
{
一見何のこと?意味の分からないキーも多かったが、googlebooksAPIの公式サイトを確認するとそれぞれの意味がきちんと記載されていた。
GoogleBooksAPI
中でも私が気になったこと
序盤の "totalItems": 1000000は公式サイトを見る限り検索で引っかかった結果の合計数だと思うのだが、どのキーに変更しても必ず1000000になっている。
私の生まれ地「Sagamihara」でキーを設定して検索👇
相模原に関する本が1000000件もあるわけがない・・・・
海外の開発者のGitHubリポジトリにもtotalitemsは不正確という記載があったため、あまり期待はしないようにする。
1.The totalItems value is an estimate of the number of items remaining from the current search index, not the total number of items. Theoretically, if the API returned 1000 totalItems for the first set of items, it would return 800 for the 200-220 set of items. I thought that this would be a simple adjustment to take into consideration, as the number of the last page could be recalculated after each request. In practice, however, this meant that the total number of pages was changing after each request. If an observant user was noting the total number of pages after each press of the "next page" button, they might notice erratic behavior (1/87, 2/86, 3/88, 4/55, etc).
2.The totalItems value seems to be very inaccurate at best. Once requests are made above the 200-item mark, it is very common for an API response to return a totalItems count without any items (example, example, example.
— evdhiggins/book-inquiry (GitHub)
2.VSコードのmain.pyでgooglebooksapiのjsonを呼び出す
下記のyoutubeを参考にgooglebooksapiを呼び出すコードを作成
【Python Web APIでデータ取得】requestsの使い方解説! 〜 初心者向け 〜 プログラミング入門 - YouTube
出典: YouTube
import requests
res = requests.get('https://www.googleapis.com/books/v1/volumes?q=python')
print("ステータスコード:", res.status_code)
result = res.json()
print(result)
実行成功!しかしjsonが繋がっていてかなり見づらかった。
下記サイトではjsonが見づらいとき、json.dumps()のindent引数を使うのが最も簡単と記載があったため、記事を参考に実装
PythonでJSONを美しく整形!json.dumps
のindent
引数で可読性UP
import requests
import json
res = requests.get('https://www.googleapis.com/books/v1/volumes?q=python')
print("ステータスコード:", res.status_code)
result = res.json()
print(result)
print(json.dumps(result, indent=4))
chatgptによるとjson.dumps() はensure_ascii=Trueがデフォルトのため、日本語など非ASCII文字をUnicodeエスケープしてしまう仕様とのこと
unicodeをエスケープとは:日本語などの非 ASCII 文字を機械が理解しやすい英数字に変換してしまうこと
下記でエスケープしないようにできる
import requests
import json
res = requests.get('https://www.googleapis.com/books/v1/volumes?q=python')
print("ステータスコード:", res.status_code)
result = res.json()
print(result)
print(json.dumps(result, indent=4,ensure_ascii=False))
躓いたところ
1.pythonスクリプトとしての実行方法
最近はFastAPIの起動コードばかり触っていたため、
ただのスクリプトを実行するときのコードを忘れていた。
uvicorn week3.main:app --reload
uvicorn week3.main:app --reload
↓
Pythonの week3/main.py を読み込み、
その中の `app` という変数(ASGIアプリ)を実行する
今回はpythonスクリプト実行すれば良いだけなので下記でOK
python main.py
所感
外部APIの呼び出しに成功し、大きな達成感を得た。
普段の業務でもKARTEのクエリを通してJSONデータを確認する機会はあったため、形式自体には馴染みがあったが、今回はツールに頼らず自分の手でAPIを叩き、JSONを取得できたことに喜びを感じた。
一方で、基礎的な理解がまだ十分ではないと感じる場面も多かった。
今後は「この値を変えるとどう挙動が変わるのか」「もっと簡潔に書ける方法はないか」といった探究心を持ちながら、コードの意味を理解して実装できるように学習を進めていきたい。
次はパラメータを変更してタイトルだけ抜き出すなど応用的に外部APIを呼び出してみたい。