How to use HTTPS API REST with python (httplib)


#1

MyQttHub REST API Introduction

MyQttHub provides a HTTPS REST API that among other features, allows to:

  • Do platform management (device administration, etc)
  • Sending and receiving messages (PUBLISH)

This way to can integrate pure MQTT devices with HTTP enable senders/receives.

Full REST API documentation can be found here: https://www.asplhosting.com/portal/en/rest-api-to-manage-mqtt-service

Connecting to MyQttHub using REST API and python httplib

First, we have to connect with a valid credential. Each credential is restricted to permissions associated to that device (regular device or administrator credentials):

  • In the case you want to do system administration/automation, then use admin credentials.
  • In the case you are integrating a HTTP producer/consumer (for example), use a regular device (a device without administration rights).

Make sure your system have python installed with httplib available.

To connect use the following working code:

import json
import httplib
import base64

def create_myqtthub_session (host, port, client_id, user_name, password):
    
    # get connection to the host configured
    print "MYQTT CONNECT: connecting to %s:%s (clientId=%s, userName=%s)" % (host, "443", client_id, user_name)
    conn = httplib.HTTPSConnection (host, port)

    # build login parameters do login
    params = {
        'clientId' : client_id,
        'userName' : user_name,
        'password' : password,
        'cleanSession' : True
    }
    # send request
    conn.request ("POST", "/login", json.dumps (params))
    result = conn.getresponse()
    body   = result.read ()
    # print "INFO: login request result: %s" % result
    if result.status != 200:
        # close connection
        conn.close ()
        return (False, "LOGIN ERROR: status=%d, reason=%s :: %s" % (result.status, result.reason, body), None)

    # Login ok
    login_data = json.loads (body)
    print "MYQTT CONNECT: login request: status=%d, reason=%s :: %s (token: %s)" % (result.status, result.reason, login_data, login_data['tokenId'])

    # return data from login
    session = {'login_data' : login_data, 'conn' : conn, 'client_id' : client_id, 'user_name' : user_name}
    return (True, "Login ok", session)

Now, to connect using this connect function do:

# connect to MyQttHub : REST API
(status, session) = create_myqtthub_session ("node02.myqtthub.com", "443", client_id, user_name, password)
if not status:
     print "ERROR: failed to connect to MyQttHub.com. Error was: %s" % session
     sys.exit (-1)
# Reached this point, session holds a session token that will be required for next steps

Headers preparation for invocations after login done

Now, also add the following code to your project. It will help you to prepare API invocation:

def __prepare_headers (session):

    # get login session and connection
    login_data = session['login_data']
    conn       = session['conn']

    # build login parameters do login
    params = { 'tokenId' : login_data['tokenId'] }
    headers = { 'Cookie' : "tokenId=%s" % login_data['tokenId'] }

    # return common headers
    return (conn, login_data, params, headers)

Sending a PUBLISH message using REST API

Assuming you have logged session, run the following code to PUBLISH your first message:

# get login session and connection 
(conn, login_data, params, headers) = __prepare_headers (session)

# params 
params['topic'] = topic_pub # String value 
params['qos'] = qos  # Int value, 0, 1, 2
params['payload'] = base64.b64encode (msg)  # Message base64 encoded
params['retain'] = False
params['dup'] = False

# send PUBLISH
print "PUBLISH :: (%s) by (clientId=%s, userName=%s).." % (topic_pub, session['client_id'], session['user_name'])
conn.request ("POST", "/publish", json.dumps (params), headers)

# print "INFO: publish request sent, waiting for response.."
result = conn.getresponse()
body   = result.read ()
# print "INFO: publish request result: %s" % result
if result.status != 200:
      print "PUBLISH ERROR: status=%d, reason=%s :: %s" % (result.status, result.reason, body)
      sys.exit (-1)

After this PUBLISH is completed, you can do other operations like SUBSCRIBE or send more PUBLISH requests. Once finished, you can close session (logout).

Logging out using REST API

Here is how you can logout, closing session:

# get login session and connection 
(conn, login_data, params, headers) = __prepare_headers (session)

# send request
conn.request ("POST", "/logout", json.dumps (params), headers)
result = conn.getresponse()
body   = result.read ()
print "LOGOUT :: response status=%d, reason=%s :: %s" % (result.status, result.reason, body)
conn.close ()
if result.status != 200:
     print "LOGOUT ERROR: status=%d, reason=%s :: %s" % (result.status, result.reason, body)
     sys.exit (-1)

print "INFO: logout request OK: status=%d, reason=%s :: %s" % (result.status, result.reason, body)
sys.exit (0)