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 3 years have passed since last update.

Nature Remo Cloud APIで400 Bad Requestが出る件

Posted at

通常、Nature APIで照明をオンにするには以下のようにPOSTする。

curl -X POST 'https://api.nature.global/1/appliances/{applianceID}/light' \
-H 'accept: application/json' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Authorization: Bearer {TOKEN}' \
-d 'button=on'

これをPythonで実行しようとした場合、urllib.error.HTTPError: HTTP Error 400: Bad Requestというエラーが出た。

from urllib.request import *
import json

token = 'XXXXXX'
headers = {
    'accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer {}'.format(token),
}
data = json.dumps({"button":"on"}).encode()
url = 'https://api.nature.global/1/appliances/902dee41-491c-4588-ba15-966e99c46c4b/light'

req = Request(url=url, data=data, headers=headers, method='POST')

with urlopen(req) as res:
    body = res.read().decode()
    print(body)

解決策

HTTPレスポンスの400とは、パラメーターに不正がある場合に生じる。
curlでは正常に動作したので、データの部分をJSON形式ではなく、クエリ文字列で指定したところ、うまく動作した。

data = b'button=on'

Nature APIのサーバー側がJSONに対応していないのか?

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?