Skip to content

nitinrajput16/code-execution

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Code Execution API πŸš€

A production-ready REST API for executing code in multiple programming languages without Docker. Built with Node.js, it provides secure, isolated code execution with timeout protection and resource limits.


✨ Features

  • βœ… 5 Languages Supported: Python, C++, Java, Go, C
  • βœ… No Docker Required: Native execution using installed compilers/interpreters
  • βœ… Security First: Timeout protection, resource limits, isolated workspaces
  • βœ… Fast Execution: No container overhead
  • βœ… Production Ready: Error handling, logging, API documentation
  • βœ… Easy Integration: Simple REST API, works anywhere
  • βœ… Batch Processing: Execute multiple programs simultaneously
  • βœ… Runtime Detection: Automatically detects installed compilers

πŸ“‹ Prerequisites

Install the languages you want to support:

Python

# Windows
winget install Python.Python.3.12

# Verify
python --version

C/C++ (MinGW)

# Windows - Install MinGW
# Download from: https://sourceforge.net/projects/mingw-w64/

# Verify
gcc --version
g++ --version

Java

# Windows
winget install Oracle.JDK.21

# Verify
java -version
javac -version

Go

# Windows
winget install GoLang.Go

# Verify
go version

πŸš€ Quick Start

1. Install Dependencies

cd backend
npm install

2. Start the API

npm start

You'll see:

╔════════════════════════════════════════════════════════╗
β•‘       Code Execution API v1.0.0                        β•‘
╠════════════════════════════════════════════════════════╣
β•‘  Server running on: http://localhost:3000              β•‘
β•‘  Documentation:     /api/docs                          β•‘
β•‘  Health Check:      /api/health                        β•‘
╠════════════════════════════════════════════════════════╣
β•‘  Supported Languages: Python, C++, Java, Go, C         β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

πŸ“Š Runtime Status:
   βœ… Python: Python 3.12.0
   βœ… C++: g++ (MinGW-W64 x86_64-ucrt-posix-seh) 13.1.0
   βœ… Java: Java 21.0.1
   βœ… Go: go version go1.21.5 windows/amd64
   βœ… C: gcc (MinGW-W64 x86_64-ucrt-posix-seh) 13.1.0

3. Test with cURL

# Execute Python code
curl -X POST http://localhost:3000/api/execute \
  -H "Content-Type: application/json" \
  -d "{\"language\": \"python\", \"code\": \"print('Hello, World!')\"}"

πŸ“– API Documentation

Base URL

http://localhost:3000

Endpoints

1. Health Check

GET /api/health

Response:

{
  "api": "Code Execution API",
  "version": "1.0.0",
  "status": "online",
  "runtimes": {
    "python": { "available": true, "version": "Python 3.12.0" },
    "cpp": { "available": true, "version": "g++ 13.1.0" },
    "java": { "available": true, "version": "Java 21.0.1" },
    "go": { "available": true, "version": "go1.21.5" },
    "c": { "available": true, "version": "gcc 13.1.0" }
  },
  "summary": "5/5 language runtimes available"
}

2. Get Supported Languages

GET /api/languages

Response:

{
  "languages": [
    { "id": "python", "name": "Python", "available": true, "version": "Python 3.12.0" },
    { "id": "cpp", "name": "C++", "available": true, "version": "g++ 13.1.0" },
    { "id": "java", "name": "Java", "available": true, "version": "Java 21.0.1" },
    { "id": "go", "name": "Go", "available": true, "version": "go1.21.5" },
    { "id": "c", "name": "C", "available": true, "version": "gcc 13.1.0" }
  ],
  "total": 5,
  "available": 5
}

3. Execute Code ⭐ Main Endpoint

POST /api/execute

Request Body:

{
  "language": "python",
  "code": "name = input()\nprint(f'Hello, {name}!')",
  "input": "Alice"
}

Response (Success):

{
  "success": true,
  "stdout": "Hello, Alice!\n",
  "stderr": "",
  "executionTime": 145,
  "language": "Python",
  "version": "Python 3.12.0",
  "timestamp": "2024-10-08T12:34:56.789Z",
  "totalTime": 156
}

Response (Error):

{
  "success": false,
  "error": "Time Limit Exceeded",
  "stdout": "",
  "stderr": "Execution timeout after 5000ms",
  "executionTime": 5000,
  "language": "Python"
}

4. Batch Execute

POST /api/execute/batch

Request Body:

{
  "executions": [
    { "language": "python", "code": "print(2 + 2)", "input": "" },
    { "language": "cpp", "code": "#include <iostream>\nint main() { std::cout << 2 + 2; }", "input": "" },
    { "language": "java", "code": "public class Main { public static void main(String[] args) { System.out.println(2 + 2); } }", "input": "" }
  ]
}

Response:

{
  "success": true,
  "results": [
    { "success": true, "stdout": "4\n", "language": "Python" },
    { "success": true, "stdout": "4", "language": "C++" },
    { "success": true, "stdout": "4\n", "language": "Java" }
  ],
  "total": 3
}

πŸ’‘ Usage Examples

Python

{
  "language": "python",
  "code": "numbers = [1, 2, 3, 4, 5]\nprint(sum(numbers))",
  "input": ""
}

C++

{
  "language": "cpp",
  "code": "#include <iostream>\nusing namespace std;\n\nint main() {\n    int a, b;\n    cin >> a >> b;\n    cout << a + b;\n    return 0;\n}",
  "input": "10 20"
}

Java

{
  "language": "java",
  "code": "import java.util.*;\npublic class Main {\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        int n = sc.nextInt();\n        System.out.println(n * n);\n    }\n}",
  "input": "5"
}

Go

{
  "language": "go",
  "code": "package main\nimport \"fmt\"\n\nfunc main() {\n    var name string\n    fmt.Scan(&name)\n    fmt.Printf(\"Hello, %s!\\n\", name)\n}",
  "input": "World"
}

C

{
  "language": "c",
  "code": "#include <stdio.h>\nint main() {\n    int n;\n    scanf(\"%d\", &n);\n    printf(\"%d\\n\", n * n);\n    return 0;\n}",
  "input": "7"
}

πŸ”’ Security Features

  1. Execution Timeout: Kills processes after 5 seconds
  2. Output Size Limit: Maximum 1MB output
  3. Isolated Workspaces: Each execution in separate temporary directory
  4. Automatic Cleanup: Temporary files deleted after execution
  5. Input Sanitization: Prevents shell injection
  6. Resource Limits: Prevents infinite loops and memory bombs

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Client App     β”‚
β”‚  (Frontend/API)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚ HTTP POST /api/execute
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Express REST API Server       β”‚
β”‚   (backend/app.js)              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Code Executor                 β”‚
β”‚   (backend/executors/index.js)  β”‚
β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
     β”‚    β”‚    β”‚    β”‚    β”‚
     β–Ό    β–Ό    β–Ό    β–Ό    β–Ό
   Python C++ Java Go  C
   Executor (Native Execution)
     β”‚    β”‚    β”‚    β”‚    β”‚
     β–Ό    β–Ό    β–Ό    β–Ό    β–Ό
   Temp Workspace (Isolated)
   - Write code to file
   - Execute with timeout
   - Capture output
   - Cleanup

πŸ“ Project Structure

backend/
β”œβ”€β”€ app.js                     # Main Express server
β”œβ”€β”€ package.json              # Dependencies
β”œβ”€β”€ executors/
β”‚   β”œβ”€β”€ index.js              # Main executor (routes to language)
β”‚   β”œβ”€β”€ base.js               # Base executor class
β”‚   β”œβ”€β”€ python.js             # Python executor
β”‚   β”œβ”€β”€ cpp.js                # C++ executor
β”‚   β”œβ”€β”€ java.js               # Java executor
β”‚   β”œβ”€β”€ go.js                 # Go executor
β”‚   └── c.js                  # C executor
└── temp/                     # Temporary execution workspaces (auto-created)

πŸ”§ Configuration

Edit the configuration in app.js:

const codeExecutor = new CodeExecutor({
    timeout: 5000,              // Execution timeout (ms)
    maxOutputSize: 1024 * 1024  // Max output size (bytes)
});

πŸ§ͺ Testing

Manual Testing with cURL

# Test Python
curl -X POST http://localhost:3000/api/execute \
  -H "Content-Type: application/json" \
  -d '{"language":"python","code":"print(\"Hello\")"}'

# Test C++
curl -X POST http://localhost:3000/api/execute \
  -H "Content-Type: application/json" \
  -d '{"language":"cpp","code":"#include <iostream>\nint main() { std::cout << \"Hello\"; }"}'

# Test with input
curl -X POST http://localhost:3000/api/execute \
  -H "Content-Type: application/json" \
  -d '{"language":"python","code":"name=input();print(f\"Hello, {name}\")","input":"World"}'

Testing with Postman

  1. Import the collection from /api/docs
  2. Create requests for each language
  3. Test with various inputs

🌐 Integration Example

JavaScript (Fetch API)

async function runCode(language, code, input = '') {
    const response = await fetch('http://localhost:3000/api/execute', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ language, code, input })
    });
    
    const result = await response.json();
    console.log(result.stdout);
}

// Usage
runCode('python', 'print("Hello, World!")');

React Component

function CodeEditor() {
    const [output, setOutput] = useState('');
    
    const executeCode = async (language, code) => {
        const response = await fetch('http://localhost:3000/api/execute', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ language, code })
        });
        
        const result = await response.json();
        setOutput(result.stdout || result.stderr);
    };
    
    return (
        <div>
            <button onClick={() => executeCode('python', 'print("Hi")')}>
                Run Code
            </button>
            <pre>{output}</pre>
        </div>
    );
}

πŸ› Troubleshooting

"Python Runtime Not Found"

# Install Python
winget install Python.Python.3.12

# Add to PATH (Windows)
# System Properties > Environment Variables > Path > Add Python path

"C++ Compiler Not Found"

# Install MinGW-w64
# Download: https://sourceforge.net/projects/mingw-w64/
# Add C:\mingw64\bin to PATH

"Java JDK Not Found"

# Install Java
winget install Oracle.JDK.21

# Verify installation
java -version
javac -version

Timeout Errors

  • Increase timeout in app.js
  • Check for infinite loops in code
  • Optimize algorithm

πŸ“Š Performance

Language Startup Time Execution Speed Memory Usage
Python ~100ms Fast Low
C++ ~500ms Very Fast Low
Java ~800ms Fast Medium
Go ~600ms Very Fast Low
C ~500ms Very Fast Low

πŸ›‘οΈ Production Deployment

Environment Variables

PORT=3000                    # API port
NODE_ENV=production         # Production mode

PM2 (Process Manager)

npm install -g pm2
pm2 start app.js --name code-api
pm2 save
pm2 startup

Nginx Reverse Proxy

server {
    listen 80;
    server_name api.yourdomain.com;
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

πŸ“ License

MIT License - Feel free to use in any project!


🀝 Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

πŸ“§ Support


πŸŽ‰ Success!

Your Code Execution API is now ready to use!

Next Steps:

  1. Install the compilers you need
  2. Start the server with npm start
  3. Test with curl or Postman
  4. Integrate into your application

Happy Coding! πŸš€

About

API for code execution with system usage

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published