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?

More than 5 years have passed since last update.

NETATMOのクライアント認証APIをaxiosでよぶ

Last updated at Posted at 2019-01-07

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が表示されれば成功。

次はサーバーから温度/湿度/二酸化炭素の値をとる記事を書く。

参考url

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?