Running Python Automation from Next.js API Routes
3 min read
- nextjs
- python
- automation
- webdev
When you build a web app with Next.js you often need some heavy‑lifting that Python does best—like running a machine‑learning model or processing a CSV file. Instead of rewriting the logic in JavaScript, you can keep the Python code and invoke it from a Next.js API route. This post shows a clean, step‑by‑step way to do that, with a tiny example that anyone can run locally.
1. Set up the Next.js project
npx create-next-app@latest my-app
cd my-app
npm install
- Keep the default folder structure.
- All API routes live in
pages/api.
2. Write a simple Python script
Create a file scripts/summary.py at the project root:
# scripts/summary.py
import sys, json, pandas as pd
def main():
# Read JSON string from stdin
data = json.load(sys.stdin)
df = pd.DataFrame(data["rows"])
# Compute a quick summary
result = {
"rows": len(df),
"columns": list(df.columns),
"mean_first_col": df.iloc[:, 0].mean()
}
print(json.dumps(result))
if __name__ == "__main__":
main()
The script reads a JSON payload, builds a pandas DataFrame, and prints a small summary as JSON.
3. Create the API route
File: pages/api/summary.js
// pages/api/summary.js
import { spawn } from "child_process";
import path from "path";
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Only POST allowed" });
}
// 1️⃣ Get the data from the request body
const payload = req.body; // assume JSON { rows: [...] }
// 2️⃣ Build the absolute path to the Python script
const scriptPath = path.join(process.cwd(), "scripts", "summary.py");
// 3️⃣ Spawn a Python process
const py = spawn("python3", [scriptPath]);
let output = "";
let error = "";
// Capture stdout
py.stdout.on("data", (data) => (output += data));
// Capture stderr
py.stderr.on("data", (data) => (error += data));
// When the process ends, send the result back
py.on("close", (code) => {
if (code !== 0) {
return res.status(500).json({ error: error || "Python script failed" });
}
try {
const result = JSON.parse(output);
res.status(200).json(result);
} catch (e) {
res.status(500).json({ error: "Invalid JSON from Python" });
}
});
// Send the payload to Python via stdin
py.stdin.write(JSON.stringify(payload));
py.stdin.end();
}
What happens here?
- The route only accepts
POST. - It receives a JSON body (
payload). - It spawns a Python process, feeding the JSON through
stdin. - The Python script writes its JSON result to
stdout. - The route parses that output and returns it to the client.
4. Test the endpoint locally
You can use curl or any HTTP client:
curl -X POST http://localhost:3000/api/summary \
-H "Content-Type: application/json" \
-d '{"rows":[{"a":1,"b":2},{"a":3,"b":4}]}'
Expected response (values will differ with your data):
{
"rows": 2,
"columns": ["a", "b"],
"mean_first_col": 2
}
5. Deploy considerations
- Python environment – Make sure the server where you deploy (Vercel, Render, Railway, etc.) has Python and required packages (
pandas). You can add arequirements.txtin the repo and let the platform install it. - Security – Validate the incoming payload before passing it to Python. Never trust raw user input.
- Performance – Spawning a process for each request adds overhead. For frequent calls, consider keeping a long‑running Python service (FastAPI, Flask) and communicate over HTTP instead.
6. Extending the idea
- Replace
summary.pywith any script: an image classifier, a text summarizer, or a web‑scraper. - Pass arguments via command‑line flags if you prefer not to use
stdin. - Use
child_process.execFilefor simpler use‑cases where you only need to capture stdout.
Key takeaways
- Next.js API routes can act as a thin bridge to existing Python automation.
- Use
stdin/stdoutto exchange JSON; it keeps the interface language‑agnostic. - Always validate input, manage dependencies, and consider performance when scaling.