APIとは?
「アプリケーション・プログラミング・インターフェース(Application Programing Interface)」の略称
一言でいうと...
「異なるアプリケーション間で情報を共有する機能」
実際にAPIをたたいてみる
今回必要なもの
node.js
axios(apiコールのためのライブラリ)
vscodeのプロンプト
npm install axios
ホットペッパーグルメのAPIキー(別途配布)
サンプルコード
api.js
const axios = require('axios');
const API_KEY = "xxxxxxxxxxx";
const ENDPOINT = "http://webservice.recruit.co.jp/hotpepper/shop/v1/"
//リクエストパラメータ
const params = {
key: API_KEY,
tel: "0662110071",
format: 'json',
};
const getdata = async () =>{
try {
const res = await axios.get(ENDPOINT,{params});
console.log(res.data.results.shop[0].name);
} catch(error){
console.error("失敗")
}
}
getdata();
解説
api.js
const axios = require('axios'); //インストールしたライブラリ使える状態にしてる
const API_KEY = "xxxxxxxxxxx"; //これがないと無力
const ENDPOINT = "http://webservice.recruit.co.jp/hotpepper/shop/v1/" //リクエストURL、URLによってとれるデータが違う
api.js
const params = {
key: API_KEY,
tel: "0662110071", //今回はこの電話番号のお店のデータをもってくる
format: 'json', //もらったデータの形式 基本jsonでいい
};
api.js
const getdata = async () =>{
try {
const res = await axios.get(ENDPOINT,{params}) //axiosを使って指定してるURLにこの情報(params)くださいしてる
console.log(res.data.results.shop[0].name);//返ってきたjson形式から抽出
} catch(error){
console.error("失敗")
}
}
返ってきた情報はres.data.resultsの中にあります。
名前以外の抽出はもちろん、リクエストパラメータを変えてみたり、エンドポイントを変えてみたりしながら遊んで見てください
APIを使用するときのポイント
リファレンスの熟読
https://webservice.recruit.co.jp/doc/hotpepper/reference.html
以上