📝Clojure API Client Development
主にサービスのAPIを叩くクライアントプログラムのノウハウまとめ.
ref: 📝Clojure Web Development から分離.
up: 📂Clojure tags: 🏷Clojure refs: 📝Clojure with Twitter Development
Clojure HTTP Client #
主なクライアントライブラリにhttp-kitとclj-httpがある.
httpリクエストに関してはどちらも同じことができる. 非同期発行も.
ただしポイントはwebsocketがt統合されているかどうか.
http-kitは2022年現在メンテナンス状況が怪しく見えた.
clj-http #
https://github.com/dakrone/clj-http
Ring の影響を受けているため Request Mapを入力としてResponse Mapを返す.
tips: debug 出力 #
{:debug true} をRequest Mapに含めると, 標準出力にRequest Mapの内容が表示される.
tips: clj-httpにおけるjsonの扱い #
ClojureでJSONを扱うライブラリである darkrone/cheshire をインストールすると, jsonとの連携が{:as :json} でできる. この指定がされると clj-httpはrepsonse dataをcheshire でjsonにパースする.
なお 単純に {:headers {:accept “application/json”}}を設定したいだけなら{:accept :json}を指定する.
ref: 💡Accept と Content-Typeの違い
howto: HTTPエラーの扱いと例外ハンドリング #
HTTP Responseが正常終了以外の場合はslingshotのインスタンスを返すため, slingshotに合わせたエラーハンドリングが期待される.
- Exceptions - GitHub - dakrone/clj-http
- clj-http READMEの説明.
- Simple error handling using slingshot and clj-http - Oskar Thorén
- シンプルなerror handling wrapper実装例.
- Handling Exceptions with Middleware in Clojure | 8th Light
- wrap-exceptionというカスタムwrapperと ring-json の組み合わせ.
howto: clj-httpのリクエストをproxy経由にするには? #
Request Mapに proxy-host, prox-port, proxy-user, proxy-passを含める.
ref: clj-http: Proxies
howto: clj-httpで WARN log: Invalid ‘expires’ attribute #
request mapのオプションに :cookie-policy :standard を追加.
ref: Invalid ‘expires’ attribute? - GitHub
howto: タイムアウト値を設定するには? #
Request Mapに 値をmillsecondで設定.
{:socket-timeout 1000
:connection-timeout 1000
:connection-request-timeout 1000}
clj-httpは JavaのApache HttpClentのWrapperであり仕様はこれに従う. 設定可能な3つの属性の意味はそれぞれ以下の通り.
- socket timeout: ソケット通信のスタートから終了まで.
- connection timeout: クライアントからサーバへの接続確立(3way-shake)まで
- connection-request-timeout: 接続確立後からレスポンスが返るまで.
ref. JavaのHttpClientにおける3つのTimeoutの違いに関して - Qiita
ページが存在するかチェックするには? #
スクレイピング用途で利用するときに404がかかるとわかっているならばgetを投げないほうがいい. こんなときはhead requestで事前に存在確認したい.
ただしclj-httpではエラーコードは自動で例外を上げるため, それを防止して自分で中身のコードをチェックするときはRequest Mapに {:throw-exceptions false} を設定する.
(defn page-exists? [url]
(if-let [resp (client/head url {:headers headers
:throw-exceptions false})]
(= (:status resp) 200)
false))
References #
勉強の参考に目を通したもののブックマーク.
- ClojureでQiita APIをたたく - Qiita
- https://github.com/akthrms/qiita-client-sample
- Qiitaを叩くだけだけど余計なものがないのでよい.
- Clojure tutorial - boot, basic functions and how to do REST requests
- とくにClojureのREST requestsに着目したチュートリアルWeb記事.
- example of clj-http
- https://github.com/joninvski/clojure-tutorial