🗾
RESAS APIを使って都道府県and市町村名取得
RESAS API
Nuxt3での実装
サーバー側
import { createRouter, defineEventHandler, useBase } from 'h3'
import axios from 'axios'
type Prefecture = {prefCode: string,prefName: string}
type City = {prefCode: string,cityfName: string, cityCode:string, bigCityFlag:"0"|"1"|"2"|"3"}
const resasApiKey = config.public.resasApiKey
const router = createRouter()
router.get('/prefectures',defineEventHandler(async()=>{
const {data}:{data:Prefecture} = await axios.get('https://opendata.resas-portal.go.jp/api/v1/prefectures',{headers:{'X-API-KEY':resasApiKey}})
return data
}))
router.get('/cities',defineEventHandler(async(event)=>{
const {prefCode} = getQuery(event)
const {data}:{data:City} = await axios.get('https://opendata.resas-portal.go.jp/api/v1/cities',{headers:{'X-API-KEY':resasApiKey},params:{prefCode:prefCode}})
return data
}))
export default useBase('/api/resas', router.handler)
フロント側
<script>
const sample = reactive({prefecture:null, city:null})
const prefectures = await (async()=>{
const res = await $fetch('/api/resas/prefectures')
return res.result
})()
const cities = ref([])
const getCitiesOfThePref = async(prefName:string)=>{
const pref = prefectures.find(p=>p.prefName === prefName)
if(!pref)return
const {result} = await $fetch('/api/resas/cities',{params:{prefCode:pref.prefCode}})
cities.value = result.map(city=>city.cityName)
}
</script>
<template>
<h2>都道府県を選択</h2>
<select @change="sample['prefecture']=$event.target.value;getCitiesOfThePref($event.target.value)">
<option v-for="p of prefectures.map(p=>p.prefName)">{{ p }}</option>
</select>
<h2>市町村を選択</h2>
<select @change="sample['city']=$event.target.value">
<option v-for="city of cities.map(c=>c.cityName)">{{ c }}</option>
</select>
</template>
Discussion