Denoで動作するHTTPクライアントについて考える
#Denoモジュール(ライブラリ)の一覧
はじめに
Denoで使用できるHTTPクライアントにはいくつかの選択肢があります。
この記事では、それぞれのモジュールについて比較してみます。
HTTPクライアントの一覧
fetch API
Denoはfetch APIをサポートしています。(Denoにおけるfetch APIの拡張や独自仕様について)
使い方は、基本的にはブラウザとほぼ同様です:
code:typescript
const url = new URL("https://qiita.com/api/v2/users/uki00a/following_tags");
url.searchParams.append("page", "1");
url.searchParams.append("per_page", "20");
const res = await fetch(url);
const tags = await res.json();
console.log(tags);
ky
ブラウザとDenoの両方をサポートしています。
作者はsindresorhus氏です。
TypeScriptがサポートされており、Skypackなどからimportすると型チェックが効きます。
リトライやタイムアウト、フックの仕組みなどを提供しており、高機能
code:typescript
import ky from "https://cdn.skypack.dev/ky@0.28.1?dts";
const res = await ky.get("https://qiita.com/api/v2/users/uki00a/following_tags", {
searchParams: {
page: 1,
per_page: 20,
},
});
const tags = await res.json();
console.log(tags);
redaxios
Preactの作者であるJason Miller氏が開発している軽量なHTTPクライアントです。
AxiosのAPIと互換性があります。
TypeScriptがサポートされており、Skypackなどからimportすると型チェックが効きます🙆‍♂️
code:typescript
import axios from "https://cdn.skypack.dev/redaxios@0.4.1?dts";
interface QiitaTag {
followers_count: number;
icon_url: string;
id: string;
items_count: number;
}
const res = await axios.get<QiitaTag[]>("https://qiita.com/api/v2/users/uki00a/following_tags", {
params: {
page: 1,
per_page: 20,
},
});
console.log(res.data);
Servest
ServestはHTTPクライアントも提供しています(Agent API)
code:typescript
import { createAgent } from "https://deno.land/x/servest@v1.3.1/agent.ts";
const agent = createAgent("https://qiita.com/");
try {
const res = await agent.send({
method: "GET",
path: "/api/v2/users/uki00a/following_tags?page=1&per_page=20",
});
const tags = await res.json();
console.log(tags);
} finally {
agent.conn.close();
}
所感
使い捨てのスクリプトなどではfetch()をそのまま使うのがよさそう
ある程度の規模なアプリとかだとkyが多機能でよさそう