Python script within nodeJS app

Hi, I am working on a nodeJS application and I want to integrate a python script, as expected it works locally but returns an error as: {“error”:“Command failed: python3 fetch_stock_data.py AAPL 3mo 1d\n/bin/sh: line 1: python3: command not found\n”} for GET request to the backend.

It should rather give me a response from the python script and then display the data on the frontend.

This is the server code:
// Endpoint to fetch stock data
router.get(“/history”, async (req, res) => {
const { symbol = “AAPL”, period = “3mo”, interval = “1d” } = req.query;

try {
exec(
python3 fetch_stock_data.py ${symbol} ${period} ${interval},
(error, stdout, stderr) => {
if (error) {
console.error(Error: ${error.message});
return res.status(500).json({ error: error.message });
}
if (stderr) {
console.error(Stderr: ${stderr});
return res.status(500).json({ error: stderr });
}

    // Send the output as the response
    try {
      const parsedOutput = JSON.parse(stdout);
      res.json(parsedOutput);
    } catch (parseError) {
      res
        .status(500)
        .json({ error: "Failed to parse Python script output" });
    }
  }
);

} catch (error) {
console.error(“Error in /history route:”, error);
res.status(500).json({ error: “Internal Server Error” });
}
});

And the error is mentioned above.

The expected result should return a graph here.

App: https://wealthwatch-ui.vercel.app/

Hi @shivangraikar, thanks for sharing the details.

Vercel is a serverless platform, which unlike your computer system doesn’t have all Runtimes (Node.js, Python, etc) at the same time. Because you are using Node.js the Vercel deployment will only have the Node.js runtime available to use.

You can solve this issue by creating a Python application out of this script and deploy it on Vercel as an HTTP API. This way the frontend application can communicate with the Python script directly.

To get started, you can checkout the examples/python/hello-world at main · vercel/examples · GitHub.

1 Like

Hi @anshumanb, thanks for the answer. I was able to use flask API for my python script and built a workaround for the logic.

Also, I’d like to know if static files are also overlooked by vercel environment?

Following is the error I get on my backend API in spite of having the stocks.csv in the right folder/path. which runs correct locally.

My application backend API works fine for all other requests but for the functions where it uses another static file stocks.csv it encounters and INTERNAL error and the logs display it as FILE NOT FOUND.

Any idea about this?

Hi @shivangraikar, glad to know that you were able to solve the previous issue.

For the static files, have you tried using the includeFiles option from the Function | Project Configuration in your vercel.json?

I think including the file in your function code should resolve the issue.

Let me know if this helps.