0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HonoのRPCを用いたシンプルかつ型安全なAPI開発

Posted at

皆さん、こんにちは。

今回は【HonoのRPCを用いたシンプルかつ型安全なAPI開発】について紹介させていただきます。

近年、フロントエンドとバックエンドの境界が曖昧になり、型安全かつシンプルにAPIを実装・呼び出せる仕組みが求められています。
その中で軽量・高速なWebフレームワーク Hono が注目を集めています。特に @hono/rpc を利用することで、サーバーとクライアントの間で型情報を共有したRPC通信を実現できます。

環境準備

今回は Bun + TypeScriptを前提に進めますが、Node.jsやDenoでもほぼ同様に動作します。

bun init hono-rpc-example
cd hono-rpc-example
bun add hono @hono/rpc

サーバー側の実装

rpc.ts を作成し、エンドポイントを定義します。

// rpc.ts
import { createRpc } from '@hono/rpc'

export const rpc = createRpc({
  getUser: async (id: number) => {
    return { id, name: 'Taro Yamada' }
  },
  add: async (a: number, b: number) => {
    return a + b
  },
})

続いてindex.tsにHonoアプリを記述します。

// index.ts
import { Hono } from 'hono'
import { rpc } from './rpc'

const app = new Hono()

app.route('/rpc', rpc)

export default app

クライアント側の実装

サーバーで定義したRPCは、そのまま型安全にクライアントから呼び出せます。

// client.ts
import { hc } from 'hono/client'
import type { AppType } from './index'

const client = hc<AppType>('http://localhost:3000')

async function main() {
  const user = await client.rpc.getUser.$query(1)
  console.log(user) // { id: 1, name: "Taro Yamada" }

  const sum = await client.rpc.add.$query(3, 5)
  console.log(sum) // 8
}

main()

ここで注目すべきは、getUseraddの引数・戻り値がすべて型推論される点です。
API仕様のドキュメントを手で書かなくても、TypeScriptの型がそのまま「契約」として機能します。

Expressなど従来の開発との比較

  • 従来のREST API開発では以下のような課題がありました:
    • リクエスト・レスポンスの型定義を別途用意する必要がある
    • バックエンドとフロントエンドで型定義が乖離するリスクがある
    • API呼び出しコードが冗長になりがち
  • Hono RPCではこれらを解決し、
    • 型定義を共有できる
    • 短いコードで直感的に呼び出せる
    • 安全性と生産性を両立できる

というメリットがあります。

まとめ

HonoのRPC機能を使うことで、シンプルかつ型安全にAPIを構築できます。
特にフロントエンドとバックエンドを同一チームで開発する場合や、BFF(Backend For Frontend)用途において非常に有効です。

次のステップとしては、認証やDBとの連携を組み合わせることで、より実践的なアプリケーションを構築できます。

👉 Honoを使ったAPI開発を検討している方は、ぜひRPCを試してみてください!

今日は以上です。

ありがとうございました。
よろしくお願いいたします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?