[Python] How to use JSON response from FastAPI backend to create a chart using Chart.js in the...

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo


    1. I have an HTML page being rendered with FastAPI:

      @app.get("/index", response_class=HTMLResponse)
      def write_home(request: Request):
      return templates.TemplateResponse("index.html", {"request": request})

    Rendered HTML: [​IMG]

    The above HTML has a Submit button for a Form, which will result in a POST request the endpoint \SWP

    <form id="generate" action="swp" method="post" enctype="multipart/form-data">

    1. It works like I'd need it to - it posts the data to my Python calculator app, which sends a JSON response back:

    Output from Py App: [​IMG]


    1. With a JSON file saved locally on the hard drive, I was able to code JavaScript which could read its data and create a Chart via Chart.js. I used Fetch API and then used the object array:

      const API_URL = "./Example_Response.json";
      async function createChartAndTable() {
      let ResponseFromAPI = await fetch(API_URL);
      let JSON_Res = await ResponseFromAPI.json();
      let JSON_Data1 = JSON.parse(JSON_Res.output.data);

    From locally saved JSON file: [​IMG]

    1. Now, Im completely puzzled as to how Im to use the Live JSON result from the Python app http://127.0.0.1:8000/swp (Step2) and then render it to the HTML generated in Step 1 to http://127.0.0.1:8000/index like I was able to with the locally stored JSON file as in Step 3.

    Note: there's no database involved.

    Continue reading...

Compartilhe esta Página