Free Code Execution API — Run Python, JavaScript, Bash Online
Need to run code on the server side without managing infrastructure? Agent Code Runner is a free API that executes Python, JavaScript, TypeScript, and Bash code in a sandboxed environment. No signup, no API key, no Docker setup. Send code, get results — with stdout, stderr, exit code, and execution time.
Try it right now — no API key, no signup:
# Run Python code via API
curl -X POST "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/execute" \
-H "Content-Type: application/json" \
-d '{"language":"python","code":"print(sum(range(100)))"}'
That's it. One HTTP call. You get back the output, exit code, execution time in milliseconds, and whether it timed out or was truncated.
What You Get Back
{
"id": "fd3c8879-3e59-4497-9325-922103324eb4",
"language": "python",
"exitCode": 0,
"stdout": "4950",
"stderr": "",
"duration": 12,
"timedOut": false,
"truncated": false
}
Clean, structured output. exitCode tells you if the code succeeded (0) or failed (non-zero). duration is wall-clock time in milliseconds. timedOut flags if the 30-second limit was hit.
4 Languages, One API
Python
Full Python 3 with standard library. Great for data processing, algorithms, and scripting.
JavaScript
Node.js runtime with full ES module support. Run any Node.js code including async/await.
TypeScript
TypeScript compiled and executed on the fly. Type-safe code execution without build steps.
Bash
Shell scripting with standard Unix tools. System commands, file operations, text processing.
Quick Execute via GET
For the simplest use case, there's a GET endpoint that takes code as a query parameter. Perfect for testing or bookmarking:
# Quick one-liner execution via GET
curl "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/run/python?code=print(2**100)"
# JavaScript
curl "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/run/javascript?code=console.log(Math.PI)"
# Bash
curl "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/run/bash?code=date"
Code Examples
curl
# Python: Fibonacci sequence
curl -X POST "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/execute" \
-H "Content-Type: application/json" \
-d '{"language":"python","code":"fib = lambda n: n if n <= 1 else fib(n-1)+fib(n-2)\nprint([fib(i) for i in range(10)])"}'
# JavaScript: Async fetch simulation
curl -X POST "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/execute" \
-H "Content-Type: application/json" \
-d '{"language":"javascript","code":"const arr = Array.from({length: 10}, (_, i) => i * i); console.log(arr);"}'
# Bash: System info
curl -X POST "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/execute" \
-H "Content-Type: application/json" \
-d '{"language":"bash","code":"echo Hello && date && uname -s"}'
Python
import requests
BASE = "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner"
# Execute Python code
result = requests.post(f"{BASE}/api/execute", json={
"language": "python",
"code": "import math\nfor i in range(1, 6):\n print(f'{i}! = {math.factorial(i)}')"
}).json()
print(f"Exit code: {result['exitCode']}")
print(f"Duration: {result['duration']}ms")
print(f"Output:\n{result['stdout']}")
if result["stderr"]:
print(f"Errors:\n{result['stderr']}")
# Test multiple languages
for lang, code in [
("python", "print('Python:', 2**10)"),
("javascript", "console.log('Node.js:', Math.pow(2, 10))"),
("bash", "echo Bash: $((2**10))"),
]:
r = requests.post(f"{BASE}/api/execute", json={"language": lang, "code": code}).json()
print(f" {r['stdout'].strip()} ({r['duration']}ms)")
Node.js
const BASE = "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner";
// Execute code and get results
const result = await fetch(`${BASE}/api/execute`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
language: "python",
code: "import json\ndata = {'primes': [2, 3, 5, 7, 11, 13]}\nprint(json.dumps(data))"
})
}).then(r => r.json());
// Parse the output as JSON
const output = JSON.parse(result.stdout);
console.log(output.primes); // [2, 3, 5, 7, 11, 13]
// Quick GET for one-liners
const quick = await fetch(
`${BASE}/api/run/python?code=${encodeURIComponent("print(42**42)")}`
).then(r => r.json());
console.log(quick.stdout); // "150130937545296572..."
Persistent Sessions
Need to run multiple commands that share state? Create a persistent session. Variables, files, and imported modules persist across executions within the same session.
import requests
BASE = "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner"
# Create a session
session = requests.post(f"{BASE}/api/sessions", json={
"language": "python"
}).json()
sid = session["id"]
print(f"Session created: {sid}")
# First execution: define a function
requests.post(f"{BASE}/api/sessions/{sid}/execute", json={
"code": "def greet(name): return f'Hello, {name}!'"
})
# Second execution: use the function (it persists!)
result = requests.post(f"{BASE}/api/sessions/{sid}/execute", json={
"code": "print(greet('World'))"
}).json()
print(result["stdout"]) # "Hello, World!"
# Upload a file to the session
requests.post(f"{BASE}/api/sessions/{sid}/files", json={
"filename": "data.txt",
"content": "line 1\nline 2\nline 3"
})
# Read the file in the next execution
result = requests.post(f"{BASE}/api/sessions/{sid}/execute", json={
"code": "with open('data.txt') as f: print(f.read())"
}).json()
print(result["stdout"]) # "line 1\nline 2\nline 3"
# Clean up
requests.delete(f"{BASE}/api/sessions/{sid}")
Real-World Use Cases
1. Code Playground Backend
Build an online code editor (like CodePen or Replit) with a simple frontend and this API as the backend. Users write code, you POST it, display the output.
// Frontend: send user code to the API
async function runCode(language, code) {
const res = await fetch(
"https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/execute",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ language, code })
}
);
const result = await res.json();
if (result.exitCode === 0) {
document.getElementById("output").textContent = result.stdout;
} else {
document.getElementById("output").textContent = result.stderr;
}
}
2. Coding Interview Platform
Use persistent sessions for multi-step interview problems where candidates build on previous answers.
import requests
BASE = "https://agent-gateway-kappa.vercel.app/v1/agent-coderunner"
def evaluate_submission(code, test_cases, language="python"):
"""Run candidate code against test cases."""
test_code = code + "\n\n# Test cases\n"
for i, (inp, expected) in enumerate(test_cases):
test_code += f"result = solution({inp})\n"
test_code += f"assert result == {expected}, f'Test {i+1} failed: got {{result}}'\n"
test_code += "print('All tests passed!')"
result = requests.post(f"{BASE}/api/execute", json={
"language": language,
"code": test_code
}).json()
return {
"passed": result["exitCode"] == 0,
"output": result["stdout"],
"error": result["stderr"],
"duration_ms": result["duration"]
}
3. AI Agent Tool
Give your AI agent the ability to write and execute code. LLM generates code, the API runs it, and the agent uses the output to continue reasoning.
import requests
def ai_code_tool(code, language="python"):
"""Tool for AI agents to execute code."""
result = requests.post(
"https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/execute",
json={"language": language, "code": code}
).json()
if result["exitCode"] == 0:
return f"Code executed successfully ({result['duration']}ms):\n{result['stdout']}"
else:
return f"Code failed (exit {result['exitCode']}):\n{result['stderr']}"
# Use with LangChain, CrewAI, or any agent framework
# agent.tools = [Tool(name="execute_code", func=ai_code_tool)]
4. Automated Testing Pipeline
Run test suites or validation scripts as part of a CI/CD pipeline without provisioning runners.
import requests
def run_validation(script, language="bash"):
result = requests.post(
"https://agent-gateway-kappa.vercel.app/v1/agent-coderunner/api/execute",
json={"language": language, "code": script}
).json()
return result["exitCode"] == 0, result["stdout"]
# Validate JSON schema
ok, out = run_validation("""
import json
data = {"name": "test", "value": 42}
assert isinstance(data["name"], str), "name must be string"
assert isinstance(data["value"], int), "value must be int"
print("Validation passed")
""", "python")
print(f"Valid: {ok}, Output: {out}")
API Reference
POST /api/execute
Execute code and return the result.
| Parameter | Type | Description |
|---|---|---|
language | string | One of: python, javascript, typescript, bash |
code | string | The code to execute |
Response Fields
| Field | Type | Description |
|---|---|---|
id | string | Unique execution ID |
language | string | Language that was executed |
exitCode | number | Process exit code (0 = success) |
stdout | string | Standard output from the code |
stderr | string | Standard error output |
duration | number | Execution time in milliseconds |
timedOut | boolean | Whether the 30-second timeout was reached |
truncated | boolean | Whether output was truncated due to size limits |
GET /api/run/:language
Quick execution via GET request. Pass code as a query parameter.
| Parameter | Type | Description |
|---|---|---|
:language | path | One of: python, javascript, typescript, bash |
code | query string | URL-encoded code to execute |
Sessions API
| Endpoint | Method | Description |
|---|---|---|
/api/sessions | POST | Create a new persistent session |
/api/sessions/:id/execute | POST | Execute code within a session (state persists) |
/api/sessions/:id/files | POST | Upload a file to the session's workspace |
/api/sessions/:id | GET | Get session info |
/api/sessions/:id | DELETE | Delete a session and clean up |
Comparison: Agent Code Runner vs Alternatives
| Feature | Agent Code Runner | Judge0 | Piston | Replit API |
|---|---|---|---|---|
| Free tier | 50 req/day | 50 req/day | Self-host only | Deprecated |
| Signup required | No | Yes (RapidAPI) | N/A | Yes |
| Languages | 4 | 60+ | 50+ | 50+ |
| Persistent sessions | Yes | No | No | Yes |
| File uploads | Yes | No | No | Yes |
| Quick GET endpoint | Yes | No | No | No |
| Self-hostable | No | Yes | Yes | No |
| Timeout | 30s | 15s (free) | Configurable | Varies |
| Starting price | Free / $0.002 | $0 (basic) | Free (self-host) | N/A |
Where Agent Code Runner wins: Zero-friction start (no signup, no API key), persistent sessions with file uploads, and a quick GET endpoint for one-liners. Great for prototyping, AI agent integration, and small-scale applications.
Where alternatives win: Judge0 and Piston support 50+ languages vs our 4. Judge0 has battle-tested infrastructure for high-volume competitive programming platforms. Piston is fully self-hostable for maximum control.
Rate Limits & Pricing
- Free tier: 30 requests/minute, no API key needed
- With API key: 120 requests/minute, 50 free credits
- Paid: $0.002 per execution (top up with USDC on Base)
- Timeout: 30 seconds per execution
Get an API key for higher limits:
curl -X POST "https://agent-gateway-kappa.vercel.app/api/keys/create"
# Response:
{
"key": "gw_abc123...",
"credits": 200,
"docs": "https://agent-gateway-kappa.vercel.app/docs"
}
FAQ
Is it really free?
Yes. You get 30 requests/minute without any API key. Create a free key for 50 credits and 120 req/min. After that, credits cost $0.002 each.
Is code execution sandboxed?
Yes. Each execution runs in an isolated environment with a 30-second timeout and output size limits. Code cannot access the network, filesystem (outside its sandbox), or other executions.
Can I install pip/npm packages?
Standard library modules are available. For Python, common packages like json, math, datetime, re, collections, etc. are all included. Third-party packages (numpy, pandas) are not currently available.
What's the maximum execution time?
30 seconds. If your code exceeds this, it's terminated and the response includes "timedOut": true. For most use cases (algorithms, data processing, scripting), 30 seconds is more than enough.
How do persistent sessions work?
Create a session with POST /api/sessions. All subsequent executions within that session share the same working directory and process state. Variables, functions, and files persist across calls. Sessions are cleaned up automatically after inactivity.
Can I use this for AI agents?
Yes — this is one of the primary use cases. LLM agents can generate code, execute it via this API, and use the output to inform their next reasoning step. Works with LangChain, CrewAI, AutoGPT, and any framework that supports custom tools. See also our Free AI Agent APIs guide.