先日、JavaScriptの「fetch API」の基本的な使い方について記事をまとめました。

今回は、より実践的な使い方として「郵便番号から住所を取得する」というよくあるシチュエーションを実装してみたので、こちらの実装方法を公開します。
fetch API・郵便番号検索 デザイン見本
JavaScript の fetch API を使って外部データを取得する実装デモです。then / catch チェーンの基本構文から、zipcloud API を使った郵便番号検索フォームの完全実装までのコードを掲載しています。
① fetch API の基本フロー — then / catch チェーン
レスポンスデータ
ボタンをクリックするとデータが表示されます
<button id="fetch-btn">データを取得</button>
<pre id="result"></pre>
var btn = document['getElementById']('fetch-btn');
var output = document['getElementById']('result');
btn.addEventListener('click', function() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(function(resp) {
if (!resp.ok) {
throw new Error('Network error');
}
return resp.json();
})
.then(function(obj) {
output.textContent = JSON.stringify(obj, null, 2);
})
.catch(function(err) {
output.textContent = 'Error: ' + err.message;
});
});
fetch(url) はリクエストを送信し Promise を返します。1つ目の .then() でレスポンスを受け取り、response.ok が false(404 / 500 など)の場合は手動で例外を投げます。response.json() 自体も非同期なため、2つ目の .then() でデータを受け取ります。.catch() はネットワーク障害など全ての例外を捕捉します。
このデモでは JSONPlaceholder(jsonplaceholder.typicode.com)というダミーデータ提供サービスに接続しています。fetch API の動作確認用として世界中の開発者が使う有名なサービスです。取得しているのは「Todoリストの1番目」で、返ってくるデータの意味は次のとおりです。userId: このTodoを作ったユーザーのID / id: Todo項目自体のID / title: Todoのタイトル(ラテン語のダミーテキスト)/ completed: 完了しているか(false = 未完了)。実際のアプリには使わず、あくまで「fetch がちゃんと動くか確認する」目的で利用しています。
② 郵便番号検索フォーム — zipcloud API の実装
郵便番号から住所を検索
郵便番号を入力して検索ボタンを押してください
<div class="zip-container">
<div class="zip-row">
<input type="text" id="zipcode1" maxlength="3" placeholder="123">
<span>-</span>
<input type="text" id="zipcode2" maxlength="4" placeholder="4567">
<button id="zip-search-btn">検索</button>
</div>
<div id="zip-result"></div>
</div>
.zip-container {
text-align: center;
padding: 24px;
}
.zip-row {
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
margin-bottom: 16px;
flex-wrap: wrap;
}
.zip-row input[type="text"] {
width: 80px;
padding: 10px;
text-align: center;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 16px;
}
.zip-row button {
padding: 10px 20px;
background: #3b82f6;
color: #fff;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 15px;
font-weight: 700;
}
#zip-result {
font-size: 18px;
color: #333;
min-height: 28px;
}
document['getElementById']('zip-search-btn').addEventListener('click', function() {
var v1 = document['getElementById']('zipcode1').value;
var v2 = document['getElementById']('zipcode2').value;
var output = document['getElementById']('zip-result');
if (v1.length !== 3 || v2.length !== 4) {
output.textContent = '正しい郵便番号を入力してください。';
return;
}
var zipStr = v1 + v2;
var apiUrl = 'https://zipcloud.ibsnet.co.jp/api/search?zipcode=' + zipStr;
output.textContent = '検索中...';
fetch(apiUrl)
.then(function(resp) {
if (!resp.ok) {
throw new Error('ネットワークエラー');
}
return resp.json();
})
.then(function(obj) {
if (obj.status !== 200 || !obj.results) {
output.textContent = '該当する住所が見つかりません。';
return;
}
var info = obj.results[0];
output.textContent = info.address1 + ' ' + info.address2 + ' ' + info.address3;
})
.catch(function() {
output.textContent = 'エラーが発生しました。';
});
});
ベース URL: https://zipcloud.ibsnet.co.jp/api/search
郵便番号 7 桁を ?zipcode=1234567 の形式でクエリパラメータに付加してリクエストします。レスポンスの results[0] に address1(都道府県)・address2(市区町村)・address3(町域名)が含まれます。商用利用も可能ですが、利用規約を事前に確認してください。
status: 成功時は 200、該当なしやエラー時は別の値。results: 住所情報の配列(該当なし時は null)。address1: 都道府県 / address2: 市区町村 / address3: 町域名。
当サイトで公開しているWebデザインやUIの実装例は、一覧として以下記事に纏めています。

