How christophetd/code-execution-api-demo works
Project type and purpose
• This is a small full-stack sample application exposing a “compile and run Python code” API and a static front-end that drives it.
• The back-end is a Node.js/Express service (in the api/ folder) that uses the Docker Python Sandbox library to spin up ephemeral Docker containers for code execution.
• The front-end (in www/) is a static HTML+JS UI (uses CodeMirror and jQuery) served by the same Node process.
File structure
• Top-level:
• api/ – contains app.js (Express app), handler.js (business logic), config.js.sample, and a set of middleware modules (rate limiter, IP whitelist, API key check, logger, favicon ignore).
• www/ – static assets (HTML, CSS, JS) for the in-browser code editor and UI.
• package.json – Node dependencies (Express, Docker Sandbox lib, PM2).
• pm2.json – PM2 process definition.
• No database folders; the primary external dependency is Docker (the Docker daemon/socket).
Key components
a. Front-end client (browser)
– Loads static files from www/index.html.
– Shows a CodeMirror editor (via codemirror.js, python.js).
– Issues HTTP POST compile requests with JSON payload.
b. API server (Node.js/Express)
– Entry point: api/app.js.
– Middleware chain:
• favicoIgnoreMiddleware (ignore favicon requests)
• loggerMiddleware (log incoming requests)
• rateLimiterMiddleware (throttle traffic)
• ipWhiteListMiddleware (restrict by IP)
• securityKeyMiddleware (enforce X-API-Key)
– Handler: api/handler.js parses { code }, invokes Docker Sandbox library.
– Configuration: api/config.js controls port, API key, rate limits, whitelisted IPs.
– Process managed by PM2 (pm2.json) or npm start.
c. Docker Python Sandbox library
– A Node wrapper around Docker Engine.
– Connects over /var/run/docker.sock.
– Spins up a fresh Python container per request, runs code, captures stdout/stderr.
d. Docker Engine (daemon)
– Underlying service that runs containers.
e. Optional external backend / client
– In production you’d likely have a private network where only your backend service (not the public internet) can call this API.
Relationships and data flow
1. Browser → HTTP(S) POST /compile on API
2. Express middleware authenticates, logs, rate-limits, etc.
3. Handler calls Docker Sandbox library → Docker daemon → new Python container
4. Container executes code → returns stdout/stderr
5. Handler formats response JSON → Express sends it back → Browser displays result
Architectural patterns and design principles
• Layered/middleware pattern in Express for separation of concerns (security, logging, rate-limiting).
• Stateless API: each request is independent; containers are ephemeral.
• Single-page/static front-end served by same HTTP server (no separate web server).
• Process management and zero-downtime restarts via PM2.
• Security best practices: API key, IP whitelist, rate limiting, private network.