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?

郵便番号・デジタルアドレスAPIを10行で実装し、Vercel Functionsにデプロイする

Posted at
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を指定すると吉

image.png

image.png

システム登録の固定IPアドレスは127.0.0.1に設定しよう!

'x-forwarded-for': '127.0.0.1'で実行するとAWSでもGCPでもGoogle Apps Scriptでも動く!

image.png

使い方

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
        }
    ]
}
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?