1

I'm pretty new to Flask and d3 but having some difficulty in loading json from an api into d3 functions using d3.json

I'm broadly trying to follow the steps here for an api I have access to: https://realpython.com/web-development-with-flask-fetching-data-with-requests/

here's my run.py file:

from flask import Flask, render_template, jsonify
from harvest_scraper import api_scraper

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/data')
def data():
    return jsonify(api_scraper())

I can confirm that when I run the app and go to the /data endpoint that I get valid json and the data that I want to use in my d3 visualisation.

Am I correct in thinking that I then can use this endpoint as a url to load the json into any d3 scripts on template pages?

Here's the index.html template I have at the moment:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>d3 api example</title>
    <script src="https://d3js.org/d3.v5.min.js"></script>

</head>
<body>

<script>

    d3.json('/data', function(data) {
        console.log(data);
        });

</script>




</body>
</html>

What I'm expecting here is for my / page to make a request to the /data page and console.log the json from the api call.

At the moment I can't see anything on the / page and cannot use this data in any d3 scripts in the index.html template. There are no errors being raised either that I can see.

I think there's something I'm either not understanding the format of the json that is returned or the way to access data from an endpoint.

crawshayi
  • 11
  • 4
  • Can you change to d3.json("/data", function(error, quotes) {...} and see what error and what quotes are printing ? Also check your Developers Network Tab (F12 if on chrome and go to Network tab). – Dinko Pehar Nov 03 '18 at 15:52
  • Nothing that I can see. Also nothing in the network tab, which would suggest that `d3.json` is not making a request to the `/data` endpoint... – crawshayi Nov 04 '18 at 08:12

1 Answers1

0

You can read more about your problem here.

In short, solution to your problem is:

d3.json('/data')
  .then(function(data){
       console.log(data);
   });
Dinko Pehar
  • 5,454
  • 4
  • 23
  • 57
  • 1
    Perfect! Thank you, works as expected! Thanks also for the link to the detailed solution. Obviously the danger of using old d3 books! – crawshayi Nov 05 '18 at 10:26
  • Good, if this helped you, please mark answer as solved. Good luck on your journey :) – Dinko Pehar Nov 05 '18 at 10:28