Access WebAPI with Python and register / acquire IoT data (dweet.io, Requests, HTTPie)

Let's use WebAPI to use dweet.io, an IoT data messaging service. The image below is the Vegetable Condition Monitoring Dashboard created using the services of Raspberry Pi and dweet.io. (Details will be introduced in another article)

スクリーンショット 2017-05-08 12.44.21.png

Method 1. Access the Web API with the Terminal command

Even if you let python do it at the end, it is convenient if you can check the operation quickly with terminal.

Install HTTPie

mac


$ brew install httpie

It is an iron plate library with 30,000 Github Stars! The highlights make the Response header very easy to see.

httpie.png

Once installed, you can use HTTP methods with the http command. (Default is GET method)

Data registration

dweet.io can easily register data by throwing a query of ? Key = value to the URL ofhttps://dweet.io/dweet/for/ <id>. (You can also register JSON data using the POST method (described later))

# -v Optional request_header can also be output
$ http https://dweet.io/dweet/for/my-thing-name?hello=world

response by httpie_header output


HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json
Date: Mon, 08 May 2017 03:13:38 GMT
Transfer-Encoding: chunked

{
    "by": "dweeting",
    "the": "dweet",
    "this": "succeeded",
    "with": {
        "content": {
            "hello": "world"
        },
        "created": "2017-05-08T03:13:38.230Z",
        "thing": "my-thing-name",
        "transaction": "54f19ae4-3428-4ea3-8275-1a77d49a11a0"
    }
}

Data acquisition

dweet.io can get the data in JSON format by accessing the URL of https://dweet.io/get/latest/dweet/for/ <id> with the GET method.

$ http https://dweet.io/get/latest/dweet/for/my-thing-name

response by httpie_header output 2


HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json
Date: Mon, 08 May 2017 03:13:55 GMT
Transfer-Encoding: chunked

{
    "by": "getting",
    "the": "dweets",
    "this": "succeeded",
    "with": [
        {
            "content": {
                "hello": "world"
            },
            "created": "2017-05-08T03:13:38.230Z",
            "thing": "my-thing-name"
        }
    ]
}

Method 2. Access the Web API from Python

Install Requests

$ pip install requests

Requests is a human-friendly HTTP library for Python with a very intuitive API. This is also a library of 25000 and iron plates by GitHub Stars.

The usage of the Requests library is as follows. Official quickstart is a very cohesive document and is recommended.

import requests

#get
r = requests.get('url')
#get:With query
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('url', params=payload)

#post
r = requests.post('url', data = {'key':'value'})

#cookies
r = requests.get('url')
cookie = r.cookies['cookie_name']
r = requests.get('url', cookies=cookie)

#response
print(r.url) 
print(r.status_code)
print(r.headers)
print(r.text)
print(r.content)
print(r.json())

What happens if the url is wrong:

Data registration / acquisition

Data registration / acquisition to dweet.io using Requests can be done as follows

import requests
import pprint
import time

#Data registration: post
for i in range(10):
  r = requests.post('https://dweet.io/dweet/for/iot-data', data = {'temp':'23', 'humid':'40'})
  time.sleep(1)

#Data acquisition: get
r = requests.get("https://dweet.io/get/latest/dweet/for/iot-data")
pprint.pprint(r.json())

terminal output result


{u'by': u'getting',
 u'the': u'dweets',
 u'this': u'succeeded',
 u'with': [{u'content': {u'humid': 40, u'temp': 23},
            u'created': u'2017-05-08T04:04:18.887Z',
            u'thing': u'iot-data'}]}

Reference: http://qiita.com/ogawatachi/items/d178bce8a9e60b5d459b

Recommended Posts

Access WebAPI with Python and register / acquire IoT data (dweet.io, Requests, HTTPie)
Data pipeline construction with Python and Luigi
[Continued] Try PLC register access with Python
Register a ticket with redmine API using python requests
Investigate Java and python data exchange with Apache Arrow
Get data from database via ODBC with Python (Access)
Data analysis with python 2
Retry with python requests
Data analysis with Python
Create applications, register data, and share with a single email
Get rid of dirty data with Python and regular expressions
Solve the spiral book (algorithm and data structure) with python!
Get additional data to LDAP with python (Writer and Reader)
Send and receive data with MQTT via Watson IoT Platform
Sample data created with python
Programming with Python and Tkinter
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
Get Youtube data with python
python with pyenv and venv
Access Google Drive with Python
Works with Python and R
Read json data with python
[AWS] Search and acquire necessary data from S3 files with S3 Select
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
Https access via proxy with Python web scraping was easy with requests
Move data to LDAP with python Change / Delete (Writer and Reader)