Dowell Living Lab Scale API

Empowering Accuracy: Dowell Living Lab Scale API

Dowell Living Lab Scale API

Dowell
Living Lab Scale API

The Dowell Living Lab Scale API provides a comprehensive set of features and capabilities to help you effectively manage and analyze various types of statistical scales. With these features, you can easily create, configure, and analyze NPS scales, Likert scales, Staple scales, Percentage scales, Percent Sum scales, Guttman scales, and many more.

Key Features

1.Create and Configure Statistical Scales:

The API allows you to create statistical scales with specific settings tailored to your requirements. You can choose from 15 different types of scales, including NPS scales, Likert scales, Staple scales, Percentage scales, Percent Sum scales, Guttman scales, and more. By customizing the settings, you can define the scale’s appearance, labels, response options, and other visual elements.

2.Retrieve and Update Scale Settings:

You can modify existing statistical scales using the update scale end-points in the API. This allows you to adjust scale settings such as orientation, colors, and labels as needed.

3.Generate Scale Instances:

The API offers functionality to dynamically generate scale instances. You can specify the number of instances to create, and the API will generate unique instances of the selected statistical scale. This feature is useful when you need to distribute the scale to multiple users or gather feedback from a large number of respondents.

4.Collect Responses to Scale Instances:

With the LivingLab Scales API, you can collect responses to individual scale instances. When a user or respondent interacts with the statistical scale, you can capture their feedback and store it in the database. The API allows you to provide responses, including the instance ID, brand name, product name, and score.

5.Retrieve Scale Reports and Response Data:

The API enables you to fetch detailed reports and response data for your statistical scales. You can retrieve data for a particular scale using its template or scale name. Additionally, you can access response data for all scales of the same type or retrieve data for a specific scale instance using its unique ID.

6.Calculate Total Scores:

The LivingLab Scales API allows you to fetch and calculate total scores for all instances of a particular scale using the unique template name. This feature enables you to analyze and aggregate the responses across multiple instances and gain insights into the overall scores.

7.Custom Configurations:

The API provides functionality to create, retrieve, and update custom configurations for your statistical scales. You can define custom input groupings and scale labels to further customize and enhance the scales based on your specific requirements.

Getting Started

  • Review the API Postman Documentation mention below to understand the available endpoints, request parameters, and response formats.
  • Documentation and Support For detailed API documentation, including endpoint descriptions, request and response examples, and authentication details, please refer to the API Postman Documentation.

To start utilizing the robust features of the LivingLab API, follow these simple steps to consume the API effectively:

Step 1: Obtain the API key

Before diving into the API integration, make sure that you have the necessary API key. You can generate your API key through the DoWell API Key Software

Step 2: Set the base URL

To make requests to the API, set the base url as https://100035.pythonanywhere.com/api/scales/

Step 3: Attach the query string parameters to the base URL

The API expects two parameters in the base URL — scale_type and type based on the values of which you can avail the different functionalities offered by the API.

  • scale type : The scale_type query parameter is included to specify the fundamental type of statisical scale that the user wishes to work with. It allows users to choose from a variety of pre-defined scale types.

    Possible values for scale_type: nps, npslite, stapel, likert, percent, percent_sum

  • type: The type query parameter govers the functionalities or the actions to be taken for the chosen scale_type.

    Possible values for type :

    1. settings:

    Assign this value when you wish to create and customize a scale from scratch. With this option, one can define various parameters such as orientation, scale color, time, scale labels, and other attributes to create a scale according to their on will.

    1. response :

    Assign this value when you wish to provide a rating or response to an existing scale in the database. By specifying this option, you can easily submit numerical and textual responses within the defined range of the selected scale.

By expertly leveraging the scale_type and type query parameters, you can unlock the full potential of the LivingLab Scale API, effortlessly tailoring its capabilities to suit your unique requirements.

Step 4: Structure Your Requests

Craft your API requests by incorporating the chosen scale_type and type values into the URL and using the appropriate POST,PUT,GET request method along with the desired request body.

Step 5: Handle Errors Gracefully 

The API follows standard HTTP status codes for error handling. Be sure to implement error handling in your code to gracefully manage potential errors and informative error messages.

Step 6: Parse API Responses 

When you receive a response from the API, ensure you parse the data accurately to extract the relevant information you need.

Error Handling

The API follows standard HTTP status codes to indicate the success or failure of each request. If an error occurs, you will receive an appropriate status code along with a descriptive error message. Please refer to the API Documentation for detailed information on error handling and common error codes.

Data Privacy and Security

At LivingLab Scales, we prioritize the security and privacy of your data. All API requests and responses are transmitted over secure HTTPS connections to protect your information. We do not share your data with third parties, and we adhere to strict data protection policies to ensure the confidentiality and integrity of your data.

If you have any further questions or need assistance, please don’t hesitate to contact our support team. We are here to help you make the most of the LivingLab Scales API.


We hope this documentation provides you with the necessary information to get started with the LivingLab Scales API. If you have any feedback or suggestions, please let us know. We are committed to continuously improving our API to meet your needs and deliver a seamless experience.

Dowell Living Lab Scale API

Postman Documentation

For detailed API documentation, including endpoint descriptions, request and response examples, and authentication details, please refer to the API documentation

Dowell Living Lab Scale API Demonstrative Scenarios

In the following scenarios, Dowell will furnish comprehensive instructions on obtaining the Service key and guide you through the steps to use the API. You’ll find examples in various formats such as Python, PHP, React, Flutter, and WordPress in the tabs below. Feel free to explore the examples in each tab for practical insights.

Frequently Asked Questions (FAQs) about Dowell Living Lab Scale API

The Dowell Living Lab Scale API supports various statistical scales including NPS scales, Likert scales, Staple scales, Percentage scales, Percent Sum scales, and Guttman scales, among others.

To create a new scale, you need to send a POST request with the appropriate settings including orientation, colors, labels, and other parameters specific to the type of scale you want to create. Make sure to include the necessary API key and authentication details in your request.

Yes, you can customize an existing scale by sending a PUT request with the updated settings parameters. This allows you to modify aspects such as orientation, colors, labels, and other visual elements according to your preferences.

To collect ratings or responses for a scale, you need to send a POST request with the type set to “response.” This allows users or respondents to interact with the scale, providing their feedback, which is then captured and stored in the database.

You can retrieve scale information by sending GET requests to the API. These requests allow you to fetch details about existing statistical scales, including their configurations, response data, and other relevant information stored in the cloud database.

If you encounter any issues, have questions, or need assistance with Dowell Living Lab Scale API, you can contact the support team for prompt assistance. Contact us at Dowell@dowellresearch.uk 

Yes, LivingLab Scales prioritizes the security and privacy of your data. All API requests and responses are transmitted over secure HTTPS connections to protect your information. Additionally, the platform adheres to strict data protection policies to ensure the confidentiality and integrity of your data.

You can use the functionality provided by the API to dynamically generate scale instances. Simply specify the number of instances you need, and the API will generate unique instances of the selected statistical scale, which can then be distributed to users or respondents as needed.

You can choose between text, emoji, or image formats for the labels inside each button of a scale, depending on your preference and the type of scale being used.

Dowell UX Living Lab offers a wide range of APIs to enhance user experience and streamline various processes. To explore the full list of APIs available, including Dowell Email, Dowell Newsletter, Samanta Content Evaluator, and many more.

For more details and to explore the complete list of APIs provided by Dowell UX Living Lab, please visit our documentation page.

1. Create your scale from scratch

				
					REQUEST METHOD : POST
type = settings
				
			

For creating a scale from scratch you would need to provide the necessary ‘settings’ for the scale in the request body.

Note that the input parameters for creating a scale are subjective to a particular scale type.

An example of the request body for each scale is mentioned below.

  1. scale_type = nps, type = settings

    For creating a scale from scratch you would need to provide the necessary ‘settings’ for the scale in the request body.

    Note that the input parameters for creating a scale are subjective to a particular scale type.

    An example of the request body for each scale is mentioned below.

    1. scale_type = nps, type = settings
				
					{
    "api_key":<str: your-api-access-key>,       
    "username": <str: username>,# your username
    "orientation": "vertical",  # orientation of the scale-- "horizontal"/"vertical"
    "scalecolor": "#8f1e1e",    # scale background color
    "roundcolor": "#938585",    # colour of the buttons in the scale
    "fontcolor": "#000000",     # colour of the fonts
    "time": "60",               # time (in seconds) within which the respondent should provide an answer. Set "00" to disable time restrictions
    "name": "scalename",        # unique name identifier for the scale
    "left": "very good",        # textual label for the lowest score
    "right": "very good",       # textual label for the highest score
    "center":"neutral",         # textual label for a neutral score
    "fomat": "text",            # format of the labels inside each button-- text, emoji, image
    "label_images": {"0": "imagefile", "1": "imagefile", "2": "imagefile"},     # image file path for the images to be displayed if "image" format is selected 
    "custom_emoji_format": {"0": "😎", "1": "🤓", "2": "😊"}                   # emojis to be displayed if "emoji" format is selected
    "fontstyle": "Arial, Helvetica, sans-serif",    # font style for texts in the scale
    "no_of_scales":5,           # number of instances of the scales you wish to create with the same settings
    "user":"no",                # assign "yes" when the inputs are coming through an end user
    "allow_resp":"yes",         # set "no" when you wish to disable the scale at any position
    "show_total_score":"yes",   # decides if the repsondent should be able to see the total score after they have provided a response for all the instances
}
				
			
  1. scale type = npslite, type = settings
				
					{  
    "api_key":<str: your-api-access-key>,
    "username": <str: username>,# your username
    "orientation": "horizontal",# orientation of the scale-- "horizontal"/"vertical"  
    "scalecolor": "#CCCCCC",    # scale background color
    "roundcolor": "#938585",    # colour of the buttons in the scale
    "fontcolor": "#000000",     # colour of the fonts
    "fontstyle": "Arial, Helvetica, sans-serif",    # font style for texts in the scale
    "fomat": "text",            # format of the labels inside each button-- text, emoji
    "custom_emoji_format": {"0": "😎", "1": "🤓", "2": "😊"}     # emojis to be displayed if "emoji" format is selected
    "time": 60,                 # time (in seconds) within which the respondent should provide an answer. Set "00" to disable time restrictions
    "name": "My first scale",   # unique name identifier for the scale
    "left": "very good",        # textual label for the lowest score
    "right": "very good",       # textual label for the highest score
    "center":"neutral",         # textual label for a neutral score
    "no_of_scales": 5           # number of instances of the scales you wish to create with the same settings
    "user":"no",                # assign "yes" when the inputs are coming through an end user
    }
				
			
  1. scale type = stapel, type = settings
				
					{
    "api_key":<str: your-api-access-key>,
    "username": <str: username>,# your username
    "orientation": "horizontal",# orientation of the scale-- "horizontal"/"vertical"
    "spacing_unit": 3,          # intervals between two score values. Can be an integer between 1 and 5
    "scale_upper_limit": 10,    #highest score value in the scale
    "scalecolor": "#CCCCCC",    # scale background color
    "roundcolor": "#938585",    # colour of the buttons in the scale
    "fontcolor": "#000000",     # colour of the fonts
    "fomat": "text",            # format of the labels inside each button-- text, emoji, image    
    "label_images": {"0": "imagefile", "1": "imagefile", "2": "imagefile"},     # image file path for the images to be displayed if "image" format is selected
    "custom_emoji_format": {"0": "😎", "1": "🤓", "2": "😊"}                  # emojis to be displayed if "emoji" format is selected
    "time": "60",               # time (in seconds) within which the respondent should provide an answer. Set "00" to disable time restrictions
    "name": "scalename",        # unique name identifier for the scale
    "left": "very good",        # textual label for the lowest score
    "right": "very good",       # textual label for the highest score
    "fontstyle": "Arial, Helvetica, sans-serif",    # font style for texts in the scale
    "no_of_scales": 5           # number of instances of the scales you wish to create with the same settings
}
				
			
  1. scale type = likert, type = settings
				
					{
    "api_key":<str: your-api-access-key>,    
    "username" : <str: username,# your username
    "scale_name" : "test_scale",# unique name identifier for the scale
    "number_of_scales" : 5,     # number of instances of the scales you wish to create with the same settings
    "orientation" : "vertical", # orientation of the scale-- "horizontal"/"vertical"
    "font_color" : "#4a4a4a",   # colour of the fonts
    "round_color" : "fffff",    # colour of the buttons in the scale
    "fomat" : "text",           # format of the labels inside each button-- text, emoji, image
    "label_scale_selection" : 2,#sub type of the likert scale-- 2 point, 3 point, 4 point, 5 point, 7 point, 9 point
    "label_scale_input" : ["Agree", "Disagree"],    #textual labels for each button. Labels should be as many as the "label_scale_selection" value
    "time" : 100                # time (in seconds) within which the respondent should provide an answer. Set "00" to disable time restrictions
}
				
			
  1. scale type = percent_sum, type = settings
				
					{
    "api_key":<str: your-api-access-key>,    
    "username" : <str: username,# your username
    "time" : "00",              # time (in seconds) within which the respondent should provide an answer. Set "00" to disable time restrictions
    "scale_name" : "envue 2 scale",# unique name identifier for the scale
    "number_of_scales" : 10,    # number of instances of the scales you wish to create with the same settings
    "orientation" : "vertical", # orientation of the scale-- "horizontal"/"vertical"
    "scale_color" : "ffff",     # scale background color
    "product_count" : 3,        # total number of products you wish to rate
    "product_names" : ["brand2", "brand4", "brand5"],   #name of each product
    "user":"no",                # assign "yes" when the inputs are coming through an end user
}
				
			
  1. scale type = percent, type = settings
				
					{   
    "api_key":<str: your-api-access-key>,    
    "username" : <str: username,# your username
    "orientation": "horizontal",# orientation of the scale-- "horizontal"/"vertical"
    "scalecolor": "#1beb00",    # scale background color
    "time": 33,                 # time (in seconds) within which the respondent should provide an answer. Set "00" to disable time restrictions
    "number_of_scales": "99",   # number of instances of the scales you wish to create with the same settings
    "name": "Name",             # unique name identifier for the scale
    "product_count" : 3,        # total number of products you wish to rate
    "product_names" : ["brand2", "brand4", "brand5"],   #name of each product
}
				
			

2. Customize an existing scale

If you ever wish to customize a scale that was already created you can do it by updating the settings parameters.

				
					REQUEST METHOD : PUT
type = settingsREQUEST METHOD : PUT
type = settings
				
			

The request body and an example for scale customization are mentioned in the API Documentation

3. Collecting score/ rating for a scale

Now that you have created and customized a scale the last step would be to send responses (ratings) to the scale.

				
					REQUEST METHOD : POST
type = responseREQUEST METHOD : POST
type = response
				
			

The request body and an example for creating responses for an existing scale are mentioned in the API Documentation

4. Retrieve Scale Information

The LivingLab Scales API also supports GET requests for fetching scale information from our cloud database. You can use GET requests to retrieve details of existing statistical scales, including their configurations, response data, and other relevant information.

Examples of this can be found in the API Documentation

How To Get The API Key

Activate Dowell Topic Generation from Dowell API Key System

Python Example

1) CREATE A NEW SCALE

This Python script sends a POST request to a specified URL with a JSON payload, creating a resource with custom scale settings. The script handles the response, printing success confirmation and, optionally, processing the returned data.:

				
					import requests

url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b"

payload = {
    "orientation": "horizontal",
    "user": "yes",
    "username": "<your-username>",
    "scalecolor": "green",
    "numberrating": 10,
    "no_of_scales": 100,
    "roundcolor": "yellow",
    "fontcolor": "blue",
    "fomat": "numbers",
    "time": 0,
    "template_name": "testing5350",
    "name": "scale_label",
    "text": "good+neutral+best",
    "left": "good",
    "right": "best",
    "center": "neutral",
    "scale-category": "nps scale",
    "show_total_score": "true",
}

response = requests.post(url, json=payload)

if response.status_code == 201:
    print("Resource created successfully")
    # Optionally, you can also print or process the response data
    data = response.json()
    print(data)
else:
    print(f"Request failed with status code: {response.status_code}")

				
			

2) PROVIDE RESPONSE TO A SCALE

This Python script uses the `requests` library to send a POST request to a specified URL with a JSON payload. It checks the response status code, printing “Resource created successfully” and optionally processing the response data if the status code is 201. Otherwise, it prints the failure details, including the status code and response text. The script also handles exceptions and prints relevant error messages in case of request failure.

				
					import requests

url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b"

payload = {
    "username": "parth",
    "scale_id": "6571f93d24d47ca1b5e90b2e",
    "score": 5,
    "instance_id": 3,
    "process_id": "101",
    "brand_name": "my brand",
    "product_name": "my product",
}

try:
    response = requests.post(url, json=payload)

    if response.status_code == 201:
        print("Resource created successfully")
        # Optionally, you can also print or process the response data
        data = response.json()
        print(data)
    else:
        print(f"Request failed with status code: {response.status_code}")
        print(response.text)

except requests.exceptions.RequestException as e:
    print(f"Request failed with an exception: {e}")
import requests

url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b"

payload = {
    "username": "parth",
    "scale_id": "6571f93d24d47ca1b5e90b2e",
    "score": 5,
    "instance_id": 3,
    "process_id": "101",
    "brand_name": "my brand",
    "product_name": "my product",
}

try:
    response = requests.post(url, json=payload)

    if response.status_code == 201:
        print("Resource created successfully")
        # Optionally, you can also print or process the response data
        data = response.json()
        print(data)
    else:
        print(f"Request failed with status code: {response.status_code}")
        print(response.text)

except requests.exceptions.RequestException as e:
    print(f"Request failed with an exception: {e}")

				
			

3) UPDATE A SCALE SETTING

This Python script sends a POST request to a specified URL, creating a resource with custom scale settings. The payload includes parameters such as scale orientation, color preferences, labels, and custom emojis. The script checks for a successful creation response (status code 201) and prints the result; otherwise, it prints the failure status code and response text.

				
					import requests

url = "https://100035.pythonanywhere.com/api/scales/?scale_type=stapel&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b"

payload = {
    "scale_id": "64b520ab08bd29b87edbc889",
    "username": "HeenaK",
    "orientation": "vertical",
    "spacing_unit": 4,
    "scale_upper_limit": 10,
    "scalecolor": "#8f1e1e",
    "roundcolor": "#938585",
    "fontcolor": "#000000",
    "fomat": "text",
    "time": "60",
    "name": "scalename",
    "left": "very good",
    "right": "very good",
    "label_images": {"0": "imagefile", "1": "imagefile", "2": "imagefile"},
    "fontstyle": "Arial, Helvetica, sans-serif",
    "custom_emoji_format": {"0": "😎", "1": "🤓", "2": ",,,,😊"}
}

response = requests.post(url, json=payload)

if response.status_code == 201:
    print("Resource created successfully")
    # Optionally, you can also print or process the response data
    data = response.json()
    print(data)
else:
    print(f"Request failed with status code: {response.status_code}")

print(f"Request failed with status code: {response.status_code}")
print(response.text)

				
			

4) RETRIVE DATA FOR SCALE - FETCH ONE

This Python script sends a GET request to a specified URL and checks if the response status code is 201. If successful, it prints a success message and optionally processes and prints the response data. If the request fails, it prints the status code and the response text. Exception handling is in place to capture and print any request-related exceptions.

				
					import requests

url = "https://100035.pythonanywhere.com/api/scales/?scale_id=651c018c289d43c15c02788e&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b"

try:
    response = requests.get(url)

    if response.status_code == 201:
        print("Resource created successfully")
        # Optionally, you can also print or process the response data
        data = response.json()
        print(data)
    else:
        print(f"Request failed with status code: {response.status_code}")
        print(response.text)

except requests.exceptions.RequestException as e:
    print(f"Request failed with an exception: {e}")



				
			

5) RETRIEVE DATA FOR ALL SCALES - FETCH ALL

This Python script utilizes the `requests` library to make a GET request to a specified URL. It checks the response status code, printing a success message and optionally processing the JSON data if the status code is 201. If the request fails, it prints the status code and response text. Exception handling is in place to capture and print any request-related exceptions.

				
					import requests

url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b"

try:
    response = requests.get(url)

    if response.status_code == 201:
        print("Resource created successfully")
        # Optionally, you can also print or process the response data
        data = response.json()
        print(data)
    else:
        print(f"Request failed with status code: {response.status_code}")
        print(response.text)

except requests.exceptions.RequestException as e:
    print(f"Request failed with an exception: {e}")

				
			

PHP Example

1) CREATE A NEW SCALE

This PHP script sends a POST request to a specified URL with a JSON payload, creating a resource. The script then prints the success message along with the decoded response data if the request is successful, or an error message if it fails.

				
					<?php

$url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

$payload = [
    "orientation" => "horizontal",
    "user" => "yes",
    "username" => "<your-username>",
    "scalecolor" => "green",
    "numberrating" => 10,
    "no_of_scales" => 100,
    "roundcolor" => "yellow",
    "fontcolor" => "blue",
    "fomat" => "numbers",
    "time" => 0,
    "template_name" => "testing5350",
    "name" => "scale_label",
    "text" => "good+neutral+best",
    "left" => "good",
    "right" => "best",
    "center" => "neutral",
    "scale-category" => "nps scale",
    "show_total_score" => "true",
];

$options = [
    'http' => [
        'header'  => "Content-type: application/json",
        'method'  => 'POST',
        'content' => json_encode($payload),
    ],
];

$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response !== false) {
    $responseData = json_decode($response, true);
    echo "Resource created successfully\n";
    print_r($responseData);
} else {
    echo "Request failed\n";
}
?>

				
			

2) PROVIDE RESPONSE TO A SCALE

This PHP script sends a POST request to a specified URL with a JSON payload. It uses `file_get_contents` along with a stream context to include the payload and headers. The script then handles the response, printing either the successfully created resource or details of the request failure, including any exception messages.

				
					<?php

$url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

$payload = array(
    "username" => "parth",
    "scale_id" => "6571f93d24d47ca1b5e90b2e",
    "score" => 5,
    "instance_id" => 3,
    "process_id" => "101",
    "brand_name" => "my brand",
    "product_name" => "my product",
);

$options = array(
    'http' => array(
        'header' => "Content-type: application/json\r\n",
        'method' => 'POST',
        'content' => json_encode($payload),
    ),
);

$context = stream_context_create($options);
try {
    $response = file_get_contents($url, false, $context);

    if ($response) {
        $responseData = json_decode($response, true);
        if ($responseData && isset($responseData['status']) && $responseData['status'] == 201) {
            echo "Resource created successfully\n";
            print_r($responseData);
        } else {
            echo "Request failed with status code: {$http_response_header[0]}\n";
            echo $response;
        }
    } else {
        echo "Failed to receive a response from the server.\n";
    }
} catch (Exception $e) {
    echo "Request failed with an exception: {$e->getMessage()}\n";
}
?>

				
			

3) UPDATE A SCALE SETTING

This PHP script sends a POST request to a specified URL with a JSON payload. It configures the payload with various settings, including scale properties, labels, and custom emojis. The script then uses `file_get_contents` with a context created from HTTP options to make the request and prints the response data if successful, or an error message if the request fails.

				
					<?php
$url = "https://100035.pythonanywhere.com/api/scales/?scale_type=stapel&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

$payload = array(
    "scale_id" => "64b520ab08bd29b87edbc889",
    "username" => "HeenaK",
    "orientation" => "vertical",
    "spacing_unit" => 4,
    "scale_upper_limit" => 10,
    "scalecolor" => "#8f1e1e",
    "roundcolor" => "#938585",
    "fontcolor" => "#000000",
    "fomat" => "text",
    "time" => "60",
    "name" => "scalename",
    "left" => "very good",
    "right" => "very good",
    "label_images" => array("0" => "imagefile", "1" => "imagefile", "2" => "imagefile"),
    "fontstyle" => "Arial, Helvetica, sans-serif",
    "custom_emoji_format" => array("0" => "😎", "1" => "🤓", "2" => ",,,,😊")
);

$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n",
        'method'  => 'POST',
        'content' => json_encode($payload),
    ),
);

$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response !== FALSE) {
    $data = json_decode($response, true);
    echo "Resource created successfully\n";
    print_r($data);
} else {
    echo "Request failed\n";
}
?>

				
			

4) RETRIVE DATA FOR SCALE - FETCH ONE

This PHP script performs a GET request to a specified URL, retrieves the JSON response, and decodes it. If the request is successful and the JSON is successfully decoded, it prints a success message along with the decoded response data. Otherwise, it outputs an appropriate failure message, including handling exceptions.

				
					<?php
$url = "https://100035.pythonanywhere.com/api/scales/?scale_id=651c018c289d43c15c02788e&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

try {
    $response = file_get_contents($url);

    if ($response !== false) {
        $responseData = json_decode($response, true);
        if ($responseData !== null) {
            echo "Resource retrieved successfully\n";
            print_r($responseData);
        } else {
            echo "Failed to decode JSON response\n";
        }
    } else {
        echo "Request failed\n";
    }
} catch (Exception $e) {
    echo "Request failed with an exception: " . $e->getMessage() . "\n";
}
?>

				
			

5) RETRIEVE DATA FOR ALL SCALES - FETCH ALL

This PHP script makes a GET request to a specified URL using `file_get_contents`, checking if the response status indicates a successful creation (HTTP 201). It then prints a success message and optionally processes the response data. If the request fails, it outputs the status code and response content. Any exceptions during the request are caught and their messages are displayed.

				
					<?php
$url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

try {
    $response = file_get_contents($url);

    if ($http_response_header[0] === 'HTTP/1.1 201 Created') {
        echo "Resource created successfully\n";
        // Optionally, you can also print or process the response data
        $data = json_decode($response, true);
        print_r($data);
    } else {
        echo "Request failed with status code: " . $http_response_header[0] . "\n";
        echo $response;
    }

} catch (Exception $e) {
    echo "Request failed with an exception: " . $e->getMessage();
}
?>

				
			

React Example

1) CREATE A NEW SCALE

This React component, `MyComponent`, defines a stateful function that sends a POST request to a specified URL using the Fetch API. It includes a JSON payload for settings and updates the component state with the response, displaying the result or error details in a button-triggered UI.

				
					import React, { useState } from 'react';

const MyComponent = () => {
  const url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

  const payload = {
    "orientation": "horizontal",
    "user": "yes",
    "username": "<your-username>",
    // ... (other payload properties)
  };

  const [responseText, setResponseText] = useState('');

  const postData = async () => {
    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      if (response.status === 201) {
        const data = await response.json();
        setResponseText(`Resource created successfully\n${JSON.stringify(data, null, 2)}`);
      } else {
        setResponseText(`Request failed with status code: ${response.status}\n${await response.text()}`);
      }
    } catch (error) {
      setResponseText(`Request failed with an exception: ${error.message}`);
    }
  };

  return (
    <div>
      <button onClick={postData}>Make Request</button>
      <pre>{responseText}</pre>
    </div>
  );
};

export default MyComponent;

				
			

2) PROVIDE RESPONSE TO A SCALE

This React component, `MyComponent`, creates a button-triggered POST request to a specified URL with a JSON payload. It updates the component state with the response details, displaying either the successful creation of a resource or the error message along with the status code.

				
					import React, { useState } from 'react';

const MyComponent = () => {
const url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

    const payload = {
        username: "parth",
        scale_id: "6571f93d24d47ca1b5e90b2e",
        score: 5,
        instance_id: 3,
        process_id: "101",
        brand_name: "my brand",
        product_name: "my product",
    };

    const [responseText, setResponseText] = useState('');

    const postData = async () => {
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
            });

            if (response.ok) {
                const data = await response.json();
                setResponseText(`Resource created successfully\n${JSON.stringify(data, null, 2)}`);
            } else {
                setResponseText(`Request failed with status code: ${response.status}\n${await response.text()}`);
            }
        } catch (error) {
            setResponseText(`Request failed with an exception: ${error.message}`);
        }
    };

    return (
        <div>
            <button onClick={postData}>Make Request</button>
            <pre>{responseText}</pre>
        </div>
    );
};

export default MyComponent;

				
			

3) UPDATE A SCALE SETTING

This React functional component, `MyComponent`, performs a POST request to a specified URL using the Fetch API. The request includes a JSON payload for configuring a scale. The component provides a button-triggered UI for making the request, and the response is displayed, including success messages or error details.

				
					import React, { useState } from 'react';

const MyComponent = () => {
    const url = "https://100035.pythonanywhere.com/api/scales/?scale_type=stapel&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

    const payload = {
        scale_id: "64b520ab08bd29b87edbc889",
        username: "HeenaK",
        orientation: "vertical",
        spacing_unit: 4,
        scale_upper_limit: 10,
        scalecolor: "#8f1e1e",
        roundcolor: "#938585",
        fontcolor: "#000000",
        fomat: "text",
        time: "60",
        name: "scalename",
        left: "very good",
        right: "very good",
        label_images: { "0": "imagefile", "1": "imagefile", "2": "imagefile" },
        fontstyle: "Arial, Helvetica, sans-serif",
        custom_emoji_format: { "0": "😎", "1": "🤓", "2": ",,,,😊" }
    };

    const [responseText, setResponseText] = useState('');

    const postData = async () => {
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
            });

            if (response.status === 201) {
                const data = await response.json();
                setResponseText(`Resource created successfully\n${JSON.stringify(data, null, 2)}`);
            } else {
                setResponseText(`Request failed with status code: ${response.status}\n${await response.text()}`);
            }
        } catch (error) {
setResponseText(`Request failed with an exception: ${error.message}`);
        }
    };

    return (
        <div>
            <button onClick={postData}>Make Request</button>
            <pre>{responseText}</pre>
        </div>
    );
};

export default MyComponent;

				
			

4) RETRIVE DATA FOR SCALE - FETCH ONE

This React functional component, `MyComponent`, utilizes the Fetch API to make an asynchronous GET request to a specified URL. It logs the retrieved resource data to the console if the request is successful, and logs error details otherwise. The useEffect hook ensures the data fetching occurs when the component mounts.

				
					import React, { useEffect } from 'react';

const MyComponent = () => {
  const url = "https://100035.pythonanywhere.com/api/scales/?scale_id=651c018c289d43c15c02788e&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        if (response.ok) {
          const data = await response.json();
          console.log("Resource retrieved successfully");
          console.log(data);
        } else {
          console.log(`Request failed with status code: ${response.status}`);
          console.log(await response.text());
        }
      } catch (error) {
        console.log(`Request failed with an exception: ${error.message}`);
      }
    };

    fetchData();
  }, []);
import React, { useEffect } from 'react';

const MyComponent = () => {
  const url = "https://100035.pythonanywhere.com/api/scales/?scale_id=651c018c289d43c15c02788e&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        if (response.ok) {
          const data = await response.json();
          console.log("Resource retrieved successfully");
          console.log(data);
        } else {
          console.log(`Request failed with status code: ${response.status}`);
          console.log(await response.text());
        }
      } catch (error) {
        console.log(`Request failed with an exception: ${error.message}`);
      }
    };

    fetchData();
  }, []);
return (
    <div>
      {/* Your React component JSX goes here */}
    </div>
  );
};

export default MyComponent;

				
			

5) RETRIEVE DATA FOR ALL SCALES - FETCH ALL

This React functional component, `MyComponent`, utilizes the `useEffect` hook to make an asynchronous HTTP GET request to a specified URL upon component mount. It logs the success message and response data if the request returns a 201 status code; otherwise, it logs the failure details. The component structure includes a placeholder for additional React JSX content.

				
					import React, { useEffect } from 'react';

const MyComponent = () => {
  const url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        
        if (response.status === 201) {
          console.log("Resource created successfully");
          const data = await response.json();
          console.log(data);
        } else {
          console.log(`Request failed with status code: ${response.status}`);
          console.log(await response.text());
        }
      } catch (error) {
        console.log(`Request failed with an exception: ${error.message}`);
      }
    };

    fetchData();
  }, [url]);

  return (
    <div>
      {/* Your React component JSX here */}
  </div>
  );
};

export default MyComponent;

				
			

Flutter Example

1) CREATE A NEW SCALE

This Flutter app sends a POST request to a specified URL using the `http` package, including a JSON payload. The payload contains settings data, and the app handles the response, printing the result or error details based on the success or failure of the request. The UI includes a button triggering the HTTP request and displays a simple scaffold with an app bar.

				
					import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final String url = "https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

  final Map<String, dynamic> payload = {
    "orientation": "horizontal",
    "user": "yes",
    "username": "<your-username>",
    // ... (other payload properties)
  };

  Future<void> postData() async {
    try {
      final response = await http.post(
        Uri.parse(url),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode(payload),
      );

      if (response.statusCode == 201) {
        final data = jsonDecode(response.body);
        print("Resource created successfully");
        print(data);
      } else {
        print("Request failed with status code: ${response.statusCode}");
        print(response.body);
      }
    } catch (error) {
      print("Request failed with an exception: $error");
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter HTTP Request'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: postData,
          child: Text('Make Request'),
        ),
      ),
    );
  }
}

				
			

2) PROVIDE RESPONSE TO A SCALE

This Flutter app sends a POST request to a specified URL using the `http` package, including a JSON payload. The response is then processed, and the outcome is printed in the console. The UI consists of a button triggering the request and is displayed with a minimalistic Scaffold structure.

				
					import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final String url = "https://100035.pythonanywhere.com/api/scales/?scale_type=stapel&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

  final Map<String, dynamic> payload = {
    "scale_id": "64b520ab08bd29b87edbc889",
    "username": "HeenaK",
    "orientation": "vertical",
    "spacing_unit": 4,
    "scale_upper_limit": 10,
    "scalecolor": "#8f1e1e",
    "roundcolor": "#938585",
    "fontcolor": "#000000",
    "fomat": "text",
    "time": "60",
    "name": "scalename",
    "left": "very good",
    "right": "very good",
    "label_images": {"0": "imagefile", "1": "imagefile", "2": "imagefile"},
    "fontstyle": "Arial, Helvetica, sans-serif",
    "custom_emoji_format": {"0": "😎", "1": "🤓", "2": ",,,,😊"}
  };

  Future<void> postData() async {
    try {
      final response = await http.post(
        Uri.parse(url),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode(payload),
      );

      if (response.statusCode == 201) {
        final data = jsonDecode(response.body);
        print("Resource created successfully");
        print(data);
      } else {
        print("Request failed with status code: ${response.statusCode}");
        print(response.body);
      }
    } catch (error) {
      print("Request failed with an exception: $error");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter HTTP Request'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: postData,
          child: Text('Make Request'),
        ),
      ),
    );
  }
}

				
			

3) UPDATE A SCALE SETTING

This Flutter app performs a POST request to a specified URL using the `http` package, sending a JSON payload. The request aims to create a resource for scale settings, and the app displays the result or error details based on the success or failure of the request, triggered by a button press in the UI.

				
					import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final String url = "https://100035.pythonanywhere.com/api/scales/?scale_type=stapel&type=settings&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b";

  final Map<String, dynamic> payload = {
    "scale_id": "64b520ab08bd29b87edbc889",
    "username": "HeenaK",
    "orientation": "vertical",
    "spacing_unit": 4,
    "scale_upper_limit": 10,
    "scalecolor": "#8f1e1e",
    "roundcolor": "#938585",
    "fontcolor": "#000000",
    "fomat": "text",
    "time": "60",
    "name": "scalename",
    "left": "very good",
    "right": "very good",
    "label_images": {"0": "imagefile", "1": "imagefile", "2": "imagefile"},
    "fontstyle": "Arial, Helvetica, sans-serif",
    "custom_emoji_format": {"0": "😎", "1": "🤓", "2": ",,,,😊"}
  };

  Future<void> postData() async {
    try {
      final response = await http.post(
        Uri.parse(url),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode(payload),
      );

      if (response.statusCode == 201) {
        final data = jsonDecode(response.body);
        print("Resource created successfully");
        print(data);
      } else {
        print("Request failed with status code: ${response.statusCode}");
        print(response.body);
      }
    } catch (error) {
      print("Request failed with an exception: $error");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter HTTP Request'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: postData,
          child: Text('Make Request'),
        ),
      ),
    );
  }
}

				
			

4) RETRIVE DATA FOR SCALE - FETCH ONE

This Dart script utilizes the `http` package to make a GET request to a specified URL, retrieving data related to a scale. The script prints the response data if the request is successful (status code 200) and provides error details otherwise.

				
					import 'dart:convert';
import 'package:http/http.dart' as http;

void main() {
  fetchData();
}

void fetchData() async {
  final url = Uri.parse("https://100035.pythonanywhere.com/api/scales/?scale_id=651c018c289d43c15c02788e&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b");

  try {
    final response = await http.get(url);

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      print("Resource retrieved successfully");
      print(data);
    } else {
      print("Request failed with status code: ${response.statusCode}");
      print(response.body);
    }
  } catch (error) {
    print("Request failed with an exception: $error");
  }
}

				
			

5) RETRIEVE DATA FOR ALL SCALES - FETCH ALL

This Dart script utilizes the `http` package to make a GET request to a specified URL. It prints the success message and response data if the status code is 201; otherwise, it prints the failure message along with the status code and response body. The script provides simple error handling for both successful and unsuccessful HTTP requests.

				
					import 'dart:convert';
import 'package:http/http.dart' as http;

void main() {
  fetchData();
}

void fetchData() async {
  final url = Uri.parse("https://100035.pythonanywhere.com/api/scales/?scale_type=nps&type=response&api_key=c2636d98-4f43-4be1-9e3b-47cdfcbe832b");

  try {
    final response = await http.get(url);

    if (response.statusCode == 201) {
      print("Resource created successfully");
      final data = jsonDecode(response.body);
      print(data);
    } else {
      print("Request failed with status code: ${response.statusCode}");
      print(response.body);
    }
  } catch (error) {
    print("Request failed with an exception: $error");
  }
}

				
			

WordPress Example

Step 1: Set up the API name, unique ID and the base url(below). It’s a prerequisite to have WP-GET API plugin installed in your wordpress website

Dowell Living Lab Scale API

Step 2: Establish the API endpoint with the inclusion of the API key, and configure the request body to contain the required POST fields.

Dowell Living Lab Scale API
Dowell Living Lab Scale API

Step 3: Test the endpoint to obtain a jQuery response from the API. Ensure that the API is functioning correctly by sending a test request and examining the response.