NETATMOウェザーステーションが届いた!
デバイスの初期設定して管理画面からデータが自動でアップされている事を確認。
楽でいいねー
サーバーに登録されたデータ(気温や湿度)を取得するためにはAPIでtoken
を取得しなければならない。
今回はそのtokenをaxiosの勉強も兼ねてjsで取得するコードを書いた。
ちなみに初めてaxiosを触ったけど、すごく手軽にAPIコールが書けて良いね!
公式のAPIリファレンス
クライアント認証
https://dev.netatmo.com/en-US/resources/technical/guides/authentication/clientcredentials
コード
シンプルなお手軽版
const axios = require('axios')
const qs = require('qs')
const axiosClient = axios.create({
baseURL: 'https://api.netatmo.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
const auth = {
client_id: 'xxxxx',
client_secret: 'xxxxxxxxxxxxxxxx',
username: 'xxx@xxxx,
password: 'xxxxxx',
grant_type: 'password'
}
axios({
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: 'https://api.netatmo.com/oauth2/token',
data: qs.stringify(auth)
})
.then(respons => {
console.log('Success')
console.log(respons.data)
})
.catch(error => {
console.log('Failure')
console.log(error.response.config)
console.log(error.response.data)
})
.then(() => {
console.log('Complete')
})
こんな書き方もできた。
const axiosClient = axios.create({
baseURL: 'https://api.netatmo.com',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
axiosClient
.post('/oauth2/token', qs.stringify(auth))
.then(respons => {
console.log('Success')
console.log(respons.data)
})
.catch(error => {
console.log('Failure')
console.log(error.response.config)
console.log(error.response.data)
})
.then(() => {
console.log('Complete')
})
インスタンス化した方が使い回せていいね。
ログにaccess_tokenが表示されれば成功。
次はサーバーから温度/湿度/二酸化炭素の値をとる記事を書く。