api/searchcode.js
export async function GET(request) {
const body = JSON.stringify({
grant_type: 'client_credentials',
client_id: 'your-client_id',
secret_key: 'your-secret_key'
})
const headers = { 'Content-Type': 'application/json', 'x-forwarded-for': '127.0.0.1', 'User-Agent': 'Mozilla/5.0' }
const tokenRes = await fetch('https://api.da.pf.japanpost.jp/api/v1/j/token', { method: 'POST', headers, body })
const { token } = await tokenRes.json()
const search_code = new URL(request.url).searchParams.get('search_code')
const searchRes = await fetch('https://api.da.pf.japanpost.jp/api/v1/searchcode/' + search_code, { headers: { 'Authorization': 'Bearer ' + token, 'User-Agent': 'Mozilla/5.0' } })
const res = new Response(searchRes.body, searchRes)
res.headers.set('Access-Control-Allow-Origin', '*')
return res
}
vercel.json
{
"public": true,
"regions": ["hnd1"],
"rewrites": [
{ "source": "/:search_code", "destination": "/api/searchcode?search_code=:search_code" }
]
}
api.da.pf.japanpost.jpはap-northeast-1のEC2でExpressサーバーで実行されているので、hnd1を指定すると吉
システム登録の固定IPアドレスは127.0.0.1に設定しよう!
'x-forwarded-for': '127.0.0.1'
で実行するとAWSでもGCPでもGoogle Apps Scriptでも動く!
使い方
curl https://jp-chi.vercel.app/1000001
await fetch('https://jp-chi.vercel.app/1000001').then(r=>r.json())
{
"page": 1,
"limit": 1000,
"count": 1,
"searchtype": "zipcode",
"addresses": [
{
"dgacode": null,
"zip_code": "1000001",
"pref_code": "13",
"pref_name": "東京都",
"pref_kana": "トウキョウト",
"pref_roma": "TOKYO",
"city_code": "13101",
"city_name": "千代田区",
"city_kana": "チヨダク",
"city_roma": "CHIYODA-KU",
"town_name": "千代田",
"town_kana": "チヨダ",
"town_roma": "CHIYODA",
"biz_name": null,
"biz_kana": null,
"biz_roma": null,
"block_name": null,
"other_name": null,
"address": null,
"longitude": null,
"latitude": null
}
]
}