Web APIを使ったウェブサービス連携
電算倶楽部定例会でWebAPIについて扱ったので、ブログでもまとめておきます。 WebAPIって何?という人を対象にしています。
Web APIについて
APIとは
Application Programming Interfaceの略。 アプリケーションを外部のプログラムから操作できるようにするインターフェース(つなげる窓口)のこと。厳格な定義はなさそう(概念的)。 仕事で以下のような仕組みを使っていますが、これらもAPIの一つと言えそうです。
Web APIとは
ざっくりですが、インターネット等のWebの技術を使って異なるコンピュータのソフトウェア同士でデータのやり取りしたり機能を実行したりする仕組みのこと。 広い意味を表すようだが、今回は(私の知る限り)よく使われるHTTPを使ったものに限定する。
- HTTP(ウェブサイトを見たりするための取り決め)の技術を使用。
- インターネット上のアプリケーションを操作する仕組み。
- データについては規定はないが、最近はJSONを使うことが多い。
代表的なサービスと機能の例
以下は電算倶楽部で使っているアプリケーションです。
例1. ISBNから書籍情報を検索する
ブラウザから例を見てみる
認証が不要なものはブラウザから見ることができるものもある。 OpenBDというサービス。
https://api.openbd.jp/v1/get?isbn=(ISBN)にアクセスすると、その書籍情報が取得できる。認証不要。
例: https://api.openbd.jp/v1/get?isbn=9784479795827
プログラムから使う
ブラウザで見た情報をプログラムで取得し、JSONを処理してタイトルと著者のみ取り出す。
import requests import json def get_bookinfo(isbn:str): url = f'https://api.openbd.jp/v1/get?isbn={isbn}' response = requests.get(url) if response.ok: return response.json() else: return none def main(): res = get_bookinfo('9784479795827') if res is none: exit() print('========取得データ========') print(json.dumps(res, indent=2, ensure_ascii=false)) print('========データを取得========') summary = res[0]['summary'] title = summary['title'] author = summary['author'] print(f'[{author}] : {title}') if __name__ == '__main__': main()
例2. Twitterのトレンドを取得する
TwitterのAPIを使うには、開発者登録をしてAPIキーを取得することが必要。
import requests import json import os bearerToken = "(秘密)" def get_twittertrend(location_id: int): url = f'https://api.twitter.com/1.1/trends/place.json' headers = {'Authorization' : f'Bearer {bearerToken}'} params = {'id': location_id} response = requests.get(url, params=params, headers=headers) if response.ok: return response.json() else: errors = response.json()['errors'] for e in errors: print(f'{e["code"]} : {e["message"]}') return None # 日本のWOEID一覧 # https://qiita.com/hogeta_/items/8e3224c4960e19b7a33a def main(): woeid = 1117881 # 新潟 res = get_twittertrend(woeid) if res is None: exit() print('========取得データ========') print(json.dumps(res, indent=2, ensure_ascii=False)) print('========データを取得========') for r in res: for i, trend in enumerate(r['trends']): print(f'{i} : {trend["name"]}') if __name__ == '__main__': main()
APIを作ってみる
Google App Scriptを使えばかんたんにWeb APIを作ることができる。 https://script.google.com/home
Google翻訳する
Web API提供側(Typescript)
function doGet(e: { parameter: any } | undefined) { const p = e.parameter const translatedText = LanguageApp.translate(p.text, p.source, p.target) return ContentService.createTextOutput(translatedText) }
import requests id = '(秘密)' dep_id = '(アプリのID)' source = 'en' target = 'ja' text = 'hello' params = { 'target': target, 'text': text, 'source':source, } url = f'https://script.google.com/macros/s/{dep_id}/exec' print(url) response = requests.get(url, params = params) print(response.ok) print(response.text)
終わりに
勉強会で一部のWebAPIを取り上げて、WebAPIでどんなことができるかを説明しました。 プログラムを作ることまではしませんでしたが、勉強のきっかけにはなったかなと思います。
プログラム内ではHTTPリクエストやJSONの作成・解析を行っていますが、これらはOpenBDやTwitter以外の多くのサービスで使われています。 一つ勉強しておくと様々な応用ができそうです。
ところで
最近この本買いました。これから読んでみます。