1

I currently have an HTML file and a python file. The python file uses YELP's API and returns JSON data. How do I display that data onto my webpage through HTML? Is there a function like document.getElementById("id").innerHTML = JSONDATA from JavaScript?

Please let me know if you need any more details; this is my first time posting and first time using an API/making a website. I understand the JSON data is not going to look nice but I will put it into a dictionary and sort it later, basically right now I am just wondering how to display data from a Python file into a HTML file. Also, feel free to link any helpful tutorials.

Found the following Node.js code as it was suggested to use Javascript instead, where in this would I put my tokens/secrets? And then how would I call it in my html file... Thank you.

/* require the modules needed */
var oauthSignature = require('oauth-signature');  
var n = require('nonce')();  
var request = require('request');  
var qs = require('querystring');  
var _ = require('lodash');

/* Function for yelp call
 * ------------------------
 * set_parameters: object with params to search
 * callback: callback(error, response, body)
 */
var request_yelp = function(set_parameters, callback) {

  /* The type of request */
 var httpMethod = 'GET';
/* The url we are using for the request */
var url = 'http://api.yelp.com/v2/search';

/* We can setup default parameters here */
var default_parameters = {
location: 'San+Francisco',
sort: '2'
};

/* We set the require parameters here */
var required_parameters = {
oauth_consumer_key : process.env.oauth_consumer_key,
oauth_token : process.env.oauth_token,
oauth_nonce : n(),
oauth_timestamp : n().toString().substr(0,10),
oauth_signature_method : 'HMAC-SHA1',
oauth_version : '1.0'
};

/* We combine all the parameters in order of importance */ 
var parameters = _.assign(default_parameters, set_parameters,      required_parameters);

/* We set our secrets here */
var consumerSecret = process.env.consumerSecret;
var tokenSecret = process.env.tokenSecret;

/* Then we call Yelp's Oauth 1.0a server, and it returns a signature */
/* Note: This signature is only good for 300 seconds after the     oauth_timestamp */
var signature = oauthSignature.generate(httpMethod, url, parameters,      consumerSecret, tokenSecret, { encodeSignature: false});

/* We add the signature to the list of paramters */
parameters.oauth_signature = signature;

/* Then we turn the paramters object, to a query string */
var paramURL = qs.stringify(parameters);

/* Add the query string to the url */
var apiURL = url+'?'+paramURL;

/* Then we use request to send make the API Request */
request(apiURL, function(error, response, body){
return callback(error, response, body);
});

};
3
  • The answer could go multiple ways depending on what you are trying to do/ how. If you are just trying to load the json dynamically, I would suggest loading it with jquery jQuery.getJSON (obviously you would have to load jquery and use it in your code Commented Mar 20, 2017 at 2:38
  • It might be easier to just use JavaScript or a JavaScript library to access the API. Commented Mar 20, 2017 at 3:29
  • That's what I wanted to do originally but Yelp doesn't have an example JavaScript call to the API and being that I don't know how to do it myself I was looking for a working example in a language I knew, so the python one seemed to be a good fit. Commented Mar 20, 2017 at 14:44

2 Answers 2

2

I had a similar situation. I had to show the IAM users of AWS account in a HTML page. I used AWS boto3 Python client to grab all IAM users and write a JSON file. Then from HTML file I read that JSON file and showed all users in a table.

Here is the Python code IAM.PY:

import boto3
import os
import subprocess
import json
iam_client = boto3.client('iam')

def list_user_cli():
    list_cmd = "aws iam list-users"
    output = subprocess.check_output(list_cmd, shell = True)
    output = str(output.decode('ascii'))
    return output

def write_json_file(filename, data):
    try:
        with open(filename, "w") as f:
            f.writelines(data)
        print(filename + " has been created.")
    except Exception as e:
        print(str(e))

if __name__ == "__main__":
    filename = "iam.json"
    data = list_user_cli()
    write_json_file(filename, data)

Here is the HTML file IAM.HTML:

<!DOCTYPE html>
<html>
    <head>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <title>IAM User List</title>
        <style type="text/css">
            body{
                margin: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <table class="table table-responsive table-hover table-bordered">
                <thead>
                    <tr>
                        <th>User ID</th>
                        <th>User Name</th>
                        <th>Path</th>
                        <th>Create Date</th>
                        <th>Arn</th>                    
                    </tr>                   
                </thead>
                <tbody id="iam_tbody">

                </tbody>
            </table>
        </div>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $.ajax({
                    method: "GET",
                    url: "http://localhost/iam/iam.json",
                }).done(function(response){
                    user_list = response.Users;
                    for(i = 0; i<user_list.length; i++){
                        tr = "<tr>";
                        tr += "<td>";
                        tr += user_list[i]["UserId"];
                        tr += "</td>";
                        tr += "<td>";
                        tr += user_list[i]["UserName"];
                        tr += "</td>";
                        tr += "<td>";
                        tr += user_list[i]["Path"];
                        tr += "</td>";
                        tr += "<td>";
                        tr += user_list[i]["CreateDate"];
                        tr += "</td>";
                        tr += "<td>";
                        tr += user_list[i]["Arn"];
                        tr += "</td>";
                        tr += "<tr>";
                        $("#iam_tbody").append(tr);
                    }
                });
            });
        </script>
    </body>
</html>

Output

IAM DEMO OUTPUT

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Jquery Ajax to call your API, include Jquery in your html file.

$.ajax({
  method: "GET",
  url: "api_url",
}).done(function( response ) {
    $('#divId').append(response);
  });

In Your Html File

<div id="divId"></div>

Jquery Ajax Documentation

1 Comment

Would I use the JQuery Ajax in tangent with Python? I need a way to authenticate the API by using my token key, secret, consumer key, consumer secret, and then sign it, which the python code I have does all that, now I just want to call that python code within my HTML file and then display it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.