I’m working on a web app where I need to create charts from data returned by my FastAPI backend. Here’s what I have set up:
Backend Setup:
My FastAPI server renders an HTML template:
@app.get("/home", response_class=HTMLResponse)
def render_page(req: Request):
return templates.TemplateResponse("home.html", {"request": req})
Form Submission:
The HTML page has a form that posts to my calculation endpoint:
<form id="dataForm" action="calculate" method="post" enctype="multipart/form-data">
Working Local Example:
I managed to create charts when reading from a local JSON file:
const LOCAL_FILE = "./sample_data.json";
async function buildChart() {
let response = await fetch(LOCAL_FILE);
let jsonData = await response.json();
let chartData = JSON.parse(jsonData.result.values);
}
The Problem:
I can successfully get JSON responses from my FastAPI calculation endpoint, but I’m stuck on how to pass this live data to my frontend Chart.js code. The form submits to one endpoint but I need the chart to appear on the original page. How do I connect these pieces without using a database?
You need to handle the form submission with JavaScript instead of letting it redirect. Prevent the default form submission behavior and use fetch to send the data to your calculate endpoint. Once you receive the JSON response, you can immediately use that data to build your chart on the same page. Here’s how I implemented it: capture the form submit event with event.preventDefault()
, send the form data via fetch to your FastAPI endpoint, then call your chart building function with the returned JSON data. This way the user stays on the same page and sees the chart populate with fresh data from your backend without any page refresh or redirection.
hmm interesting challenge! have you considred using websockets for this? i’m curious tho - when your form submits to the calculate endpoint, does it return json directly or does it redirect somewhere? also what happens after the calculation - do you want the chart to appear instantly or is there some processing time involved?
another approach is makeing your calculate endpoint return both the chart data AND the html template together. modify your fastapi route to accept GET requests too, then when form submits it can redirect back to same page but with chart data included in template context. this way you dont need complex javascript handling.