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?

Node.js — @staddress/client で住所解析する

0
Posted at

Node.js — @staddress/client で住所解析する

住所正規化・ジオコーディングAPI 「Staddress(スタドレス)」 開発チームです。

前回(Staddress CLIで住所解析する)は、ターミナルの staddress コマンドで API を呼び出す手順を紹介しました。

今回は、公式 Node.js / TypeScript SDK @staddress/client を使い、アプリやスクリプトから住所解析を呼び出します。HTTP の細部は SDK に任せつつ、型付きで parse / usage / エラー処理まで一気に通します。

この記事で扱う内容は次の通りです。

  1. @staddress/client をインストールする
  2. StaddressClient を初期化する
  3. parseAddress で単件解析する
  4. getUsage で利用状況を確認する
  5. StaddressError でエラーを扱う
  6. (任意)parseBatch で一括解析する

前提

  • Free アカウント登録が完了していること
  • アカウント管理画面で API Key を確認できること
  • Node.js 18+(ネイティブ fetch を使用)
  • npm / yarn / pnpm のいずれか

今回使う SDK はこちらです。

特徴:

  • 依存パッケージなし(Node.js 18+ の fetch
  • ESM / CommonJS デュアルパッケージ、型定義同梱
  • provenance(SLSA)署名付き公開

バージョン確認:

node -v   # v18 以上であること

Step 1. インストールする

作業用ディレクトリを作り、パッケージを入れます。

mkdir staddress-node-demo && cd staddress-node-demo
npm init -y
npm install @staddress/client

package.json で ESM を使う場合:

{
  "type": "module"
}

Step 2. クライアントを初期化する

import { StaddressClient, StaddressError } from '@staddress/client';

const client = new StaddressClient({
  apiKey: process.env.STADDRESS_API_KEY, // 省略時は環境変数 STADDRESS_API_KEY
  baseUrl: process.env.STADDRESS_BASE_URL, // 省略時は https://api.staddress.com
  timeout: 30_000, // 任意(ミリ秒、既定 30000)
});

実行前に API Key を環境変数へ設定します。

export STADDRESS_API_KEY="sk_xxxxxxxxxxxxxxxxxxxx"
# 必要なら(省略可)
export STADDRESS_BASE_URL="https://api.staddress.com"

コンストラクタに apiKey を直接渡すこともできますが、スクリプトやサーバーでは環境変数推奨です。


Step 3. parseAddress で単件解析する

demo.mjs(または demo.ts)を用意します。

// demo.mjs
import { StaddressClient, StaddressError } from '@staddress/client';

const client = new StaddressClient();

const { result } = await client.parseAddress({
  input: '六本木ヒルズ 森タワー 52F',
  // postalCode: '106-6100', // 分かっていれば任意で付与
});

console.log('normalized:', result.normalized);
console.log('components:', JSON.stringify(result.components, null, 2));
console.log('confidence:', result.confidence);

実行:

export STADDRESS_API_KEY="sk_xxxxxxxxxxxxxxxxxxxx"
node demo.mjs

parseAddress の実行結果例
parseAddress の実行例

内部的には POST /api/v1/addresses/parse を呼び出しています。
レスポンスの見方(normalized / components / confidence)は、curl 編の「レスポンスで見るべきポイント」 と同じです。

TypeScript でも同じです。

import { StaddressClient } from '@staddress/client';

const client = new StaddressClient();
const { result } = await client.parseAddress({
  input: '東京都渋谷区道玄坂1-2',
  postalCode: '150-0043',
});

Step 4. getUsage で利用状況を確認する

const usage = await client.getUsage();
console.log(usage);

getUsage の実行結果例
03-get-usage.png

成功すると、プランと月間利用状況が返ります。Free プランでは月間の解析上限を確認できます。
CLI の staddress usage と同じ情報を、アプリ側のヘルスチェックやダッシュボード表示にも使えます。


Step 5. StaddressError でエラーを扱う

API エラー・ネットワークエラー・タイムアウトは StaddressError として throw されます。

try {
  const { result } = await client.parseAddress({ input: '...' });
  console.log(result.normalized);
} catch (err) {
  if (err instanceof StaddressError) {
    console.error('code:', err.code);             // 例: unauthorized, quota_exceeded, unresolved
    console.error('httpStatus:', err.httpStatus); // ネットワークエラー時は 0
    console.error('requestId:', err.requestId);   // サポート問い合わせ用(あれば)
    console.error('retryAfter:', err.retryAfter); // 再試行可能日時(あれば)
    console.error('message:', err.message);
    return;
  }
  throw err;
}

エラーレスポンスの例

code(例) 典型的な状況
unauthorized API Key 未設定・無効
quota_exceeded 月間上限到達
unresolved 住所として解決できない
invalid_request パラメータ不足など
network_error / processing 通信失敗・タイムアウト

本番では requestId をログに残すと、問い合わせ時に追跡しやすくなります。


Step 6.(任意)parseBatch で一括解析する

一括解析は Standard プラン以上、1リクエスト最大100件です。

const { results } = await client.parseBatch({
  items: [
    { id: '1', address: '東京都渋谷区道玄坂1-2-3', postalCode: '150-0002' },
    { id: '2', address: '大阪府大阪市北区梅田1-1-1' },
  ],
});

for (const row of results) {
  console.log(row.id, row.result?.normalized ?? row.error);
}

PoC では単件の parseAddress で十分なことが多いです。一括はバッチジョブや CSV 取り込みと組み合わせる場面向けです(詳細は連載後半の一括クレンジング回でも扱います)。


最小の動くサンプル(まとめコード)

demo.mjs に usage → parse → エラー処理をまとめた例です。

import { StaddressClient, StaddressError } from '@staddress/client';

async function main() {
  const client = new StaddressClient();

  const usage = await client.getUsage();
  console.log('usage:', usage);

  const { result } = await client.parseAddress({
    input: '六本木ヒルズ 森タワー 52F',
  });
  console.log('normalized:', result.normalized);
  console.log('confidence:', result.confidence);
}

main().catch((err) => {
  if (err instanceof StaddressError) {
    console.error(`[${err.code}]`, err.message, err.requestId ?? '');
    process.exitCode = 1;
    return;
  }
  console.error(err);
  process.exitCode = 1;
});
export STADDRESS_API_KEY="sk_xxxxxxxxxxxxxxxxxxxx"
node demo.mjs

CLI / curl / SDK の使い分け

観点 curl / PowerShell Staddress CLI @staddress/client(今回)
主な用途 HTTP の素通し確認 手元検証・シェル自動化 Node / TypeScript アプリ組み込み
なし なし TypeScript 型あり
エラー HTTP ステータス 終了コード StaddressError
依存 curl / jq 等 bash / jq Node.js 18+ のみ
設定 環境変数 / ヘッダ staddress config 環境変数 / コンストラクタ

よくあるつまづき

API キーが設定されていません

echo "$STADDRESS_API_KEY"

空なら export し直すか、new StaddressClient({ apiKey: '...' }) を渡してください。

fetch が利用できません

Node.js 18 未満の可能性があります。

node -v

401 / unauthorized

Key のコピー漏れ、失効、テスト用と本番用の取り違えを確認してください。

quota_exceeded

Free の月間上限に達しています。getUsage() で残量を確認し、必要ならプランを見直してください。

ESM で require できない

"type": "module" のプロジェクトでは import を使ってください。CJS からも @staddress/client は利用できます(デュアルパッケージ)。


まとめ

今回は、公式 Node.js SDK @staddress/client で住所解析する手順を紹介しました。

  • npm install @staddress/client ですぐ使える(依存ゼロ)
  • parseAddress / getUsage / parseBatch で主要 API をカバー
  • StaddressErrorcode・HTTP ステータス・requestId を扱える
  • API Key は環境変数で渡し、リポジトリやフロントに載せない
  • レスポンスの見方は curl 編と同じ

Staddress ホームセット

Staddress に関する公式リンク一覧です。

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?