Meet the Developer

Developer Avatar

Loading...

Fetching developer profile from GitHub...

Introduction

The Python Sandbox API provides a sandboxed environment to run Python code remotely. Each request is executed in a temporary, isolated environment with strict resource limits and security policies. You can upload files, execute code that processes them, and retrieve the generated output files, all in a single API call.

Base URL & Rate Limits

All API requests are made to the base URL, which is dynamically detected below. The public API is open and does not require an API key, but is rate-limited by IP address to ensure fair usage and server stability.

Limit Type Value Description
Requests Per Minute (RPM) 5 Maximum requests allowed in a 60-second window.
Requests Per Day (RPD) 30 Total daily request quota, resetting at UTC midnight.
Server Concurrency 5 Maximum number of simultaneous code executions allowed on the server. If this limit is reached, you will receive a 503 Service Unavailable error.

Execution & Resource Limits

To maintain a secure and stable environment, the following resource limits are enforced on every execution:

Resource Limit Description
Execution Timeout 10 seconds Your script will be terminated if it runs longer than 10 seconds.
Max Code Length 2000 characters The code field in your JSON payload cannot exceed this length.
Max Attachments 2 files You can upload a maximum of two files per request.
Max File Size 8 MB per file Each attached file cannot exceed 8 megabytes in size.
Max Child Processes 10 Your script is prevented from forking more than 10 child processes to protect against "fork bomb" attacks.

Security & Sandbox Model

Every code execution is heavily sandboxed with the following restrictions:

  • No Network Access: Scripts cannot make outbound network requests.
  • Filesystem Isolation: Code runs in a temporary directory and has no access to the underlying server filesystem.
  • Import Restrictions: Only a curated list of safe libraries is available. Modules that could compromise security (e.g., os, sys) are forbidden.
  • Resource Limits: Each execution is constrained by the time, process, and memory limits detailed above.
  • Ephemeral Environment: The execution directory and all its contents are permanently deleted immediately after the request is completed.

Making Requests

All requests to the /execute endpoint must be a POST request with a JSON body.

Using cURL

curl -X POST  \
-H "Content-Type: application/json" \
-d '{
  "code": "print(\"Hello from the sandbox!\")"
}'

Using Python requests

import requests
import json

api_url = ''
payload = {
    'code': 'for i in range(5): print(f"Count: {i}")'
}

response = requests.post(api_url, json=payload)

print("Status Code:", response.status_code)
print("Response JSON:", json.dumps(response.json(), indent=2))

Endpoint Details: POST /execute

Request Body Schema

Field Type Required Description
code String Yes The Python code to execute (max 2000 characters).
stdin_data String No Text data passed to the script's standard input.
attachments Array of Objects No Files to be made available. Max 2 files, 8MB each. Each object needs filename and content_base_64 keys.
return_files Array of Strings No A list of filenames generated by the script to be returned in the response.

Allowed Libraries

Your code can import from a curated list of standard library and third-party modules. Attempts to import any module not on this list will result in a ForbiddenImportError.

Category Allowed Modules
Key Third-Party Libraries numpy
Media & Document Generation PIL (Pillow), reportlab, fpdf
Data & Math math, statistics, decimal, fractions, numbers, random
Date & Time datetime, time, calendar
Text & Regex string, re, textwrap, unicodedata
Data Structures & Iteration collections, itertools, functools, operator, bisect, heapq, array
Security & Encoding hashlib, base64, uuid, secrets
Data Serialization json, ast
General Utilities typing, enum, dataclasses, copy, pprint

Error Responses

Errors are returned with a descriptive JSON body and an appropriate HTTP status code.

Status Code Error Type Reason
400 Bad Request ValidationError The request JSON is malformed, a file is too large, etc.
400 Bad Request ForbiddenImportError The script attempts to import a disallowed module.
400 Bad Request TimeoutError Execution exceeded the 10-second time limit.
429 Too Many Requests RateLimitExceeded The per-minute or daily request limit has been reached.
503 Service Unavailable ServerBusy The server has reached its maximum concurrent execution limit.

Complete Example: Image Grayscaling

This example demonstrates a complete workflow: uploading an image, using the Pillow library to convert it to grayscale, and receiving the processed image back.

Note: To run the client script, you need the requests library (pip install requests) and a local image file named my_photo.jpg.

1. The Sandbox Script

This is the code that will run on the server. It opens the attached file by its given name, processes it, and saves a new file which we will ask the API to return.

# This script is sent in the 'code' field
from PIL import Image

try:
    # 'input_photo.jpg' is the filename we specify in the attachment
    with Image.open('input_photo.jpg') as img:
        grayscale_img = img.convert('L')
        grayscale_img.save('output_grayscale.png')
        print("Image successfully converted to grayscale.")
except FileNotFoundError:
    print("Error: 'input_photo.jpg' not found in attachments.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

2. The Client-Side Request

This Python script runs on your local machine. It reads your image, constructs the API payload, sends the request, and saves the result.

# This script runs on your local machine
import requests
import base64
import json

API_URL = ''
LOCAL_IMAGE_PATH = 'my_photo.jpg' # Make sure this file exists
RESULT_IMAGE_PATH = 'result_grayscale.png'

# The sandbox script from above
sandbox_code = """
from PIL import Image
try:
    with Image.open('input_photo.jpg') as img:
        grayscale_img = img.convert('L')
        grayscale_img.save('output_grayscale.png')
        print("Image successfully converted to grayscale.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
"""

# 1. Read local image and Base64 encode it
try:
    with open(LOCAL_IMAGE_PATH, "rb") as image_file:
        b64_content = base64.b64encode(image_file.read()).decode('utf-8')
except FileNotFoundError:
    print(f"Error: Please create a file named '{LOCAL_IMAGE_PATH}' to run this.")
    exit()

# 2. Construct the API payload
payload = {
    "code": sandbox_code,
    "attachments": [{
        "filename": "input_photo.jpg",
        "content_base_64": b64_content
    }],
    "return_files": ["output_grayscale.png"]
}

# 3. Send the request
print(f"Sending request to {API_URL}...")
response = requests.post(API_URL, json=payload)

# 4. Process the response
if response.status_code == 200:
    data = response.json().get('execution_details', {})
    print("API Call Successful!")
    print(f"  > Stdout: {data.get('stdout', '').strip()}")
    
    output_files = data.get('output_files', {})
    if 'output_grayscale.png' in output_files:
        grayscale_data = base64.b64decode(output_files['output_grayscale.png']['content_base64'])
        with open(RESULT_IMAGE_PATH, "wb") as f:
            f.write(grayscale_data)
        print(f"> Success! Grayscale image saved to '{RESULT_IMAGE_PATH}'")
    else:
        print("> Error: The API did not return the processed image.")
else:
    print(f"API Error: {response.status_code}")
    print(json.dumps(response.json(), indent=2))