Skip to content

Web Service written in Python returning JSON

This page provides an example of a web service written in Python. The service supports the following requests:

  • Hotspot with response as JSON
  • Data with response as JSON

Script

When the script below is invoked, the handleResponse function is called (see last line). The function determines whether the request is for a hotspot or for data and calls a function to get that information as a Python object. The handleResponse function then emits a header for JSON, converts the Python object to a JSON string, and emits the string as its response to the request.

#!/usr/bin/python3

import cgi
import json

def emit_hotspot(hotspot_id):
    if hotspot_id:
         response = {"html": f"Request for hotspot Id '{hotspot_id}' received"}
    else:
        response = {"error": f"No hotspot Id parameter provided"}
    return response

def emit_data(data_id):
    response = []
    if data_id:
        for i in range(1, 4):
            data = {"id": f"{data_id}-{i}", "html": f"<div>Data {i}</div>"}
            response.append(data)
    else:
        error = "No data Id parameter provided"
        response = {"error": error}
    return response

def handle_response():
    args = cgi.FieldStorage()
    type_arg = args.getvalue('type')
    id_arg = args.getvalue('id')

    if type_arg == "hotspot":
        response = emit_hotspot(id_arg)
    elif type_arg == "data":
        response = emit_data(id_arg)
    else:
        error = f"Unsupported type parameter '{type_arg}' provided" if type_arg else "No type parameter provided"
        response = {"error": error}

    print("Content-Type: application/json\n")
    print(json.dumps(response))

handle_response()

Usage

Below are examples of requests that invoke the above web service called service.py.

function onEventRequestLiveData(event) {
   let url = "https://avantlogic.net/livedata/python/example/service.py";
   event.api.liveData.requestHotspot("json", 0, url, "type", "hotspot", "id", event.hotspot.id);
}
function onEventPageLoaded(event) {
   let url = "https://avantlogic.net/livedata/python/example/service.py";
   event.api.liveData.requestHotspot("json", 0, url, "type", "data", "id", "test");
}

Response

Below are responses from the web service. You can click the links to see the responses in a browser.

Hotspot HTML as JSON

https://avantlogic.net/livedata/python/example/service.py?type=hotspot&id=test

{
    "html": "Request for hotspot Id 'test' received"
}

Data as JSON

https://avantlogic.net/livedata/python/example/service.py?type=data&id=test

[
    {
        "id": "test-1",
        "html": "<div>Data 1</div>"
    },
    {
        "id": "test-2",
        "html": "<div>Data 2</div>"
    },
    {
        "id": "test-3",
        "html": "<div>Data 3</div>"
    }
]

Error as JSON

https://avantlogic.net/livedata/python/example/service.py

{
    "error":"No type parameter provided"
}