WebSocket APIs
The JDoodle WebSocket API provides an interactive, real-time environment for running and compiling code, supporting 88 programming languages.
Unlike the REST API, which operates on a request-response model, the WebSocket API allows continuous, two-way communication, enabling users to send multiple inputs and receive outputs instantly.
Authentication
To use the JDoodle WebSocket API, you must authenticate your requests using a Client ID and Client Secret. The authentication process involves two main steps: obtaining an authentication token and using this token to establish a WebSocket connection.
Step 1: Get authentication token
First, you must obtain an authentication token by making a POST request to the JDoodle API endpoint. This token is valid for 180 seconds and must be included in your WebSocket requests.
Endpoint
Endpoint | Method |
---|---|
POST |
Input parameters
Parameter | Description | Type | Required |
---|---|---|---|
clientId | Your Client ID | String | Yes |
clientSecret | Your Client Secret | String | Yes |
Example request
curl -X POST "https://api.jdoodle.com/v1/auth-token" \
-H "Content-Type: application/json" \
-d '{
"clientId": "your_client_id_here",
"clientSecret": "your_client_secret_here"
}'
Response Fields
Parameter | Description | Type |
---|
Example response
{
"token": "your_generated_token_here"
}
Step 2: Use the authentication token
Once you have obtained the authentication token, you need to include it in the header of your WebSocket requests to authenticate your connection.
cURL Example to use the authentication token
# Replace these with your own Client ID, Client Secret, and the token obtained from the previous step
CLIENT_ID="your_client_id_here"
CLIENT_SECRET="your_client_secret_here"
TOKEN="your_generated_token_here"
curl -X POST "https://api.jdoodle.com/v1/execute" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{
"clientId": "'"$CLIENT_ID"'",
"clientSecret": "'"$CLIENT_SECRET"'",
"script": "print(\"Hello, World!\")",
"language": "python3",
"versionIndex": "0"
}'
In this cURL command:
- Replace
your_client_id_here
andyour_client_secret_here
with your actual Client ID and Client Secret. - Replace your_generated_token_here with the token obtained from the authentication step.
- The script to be executed is “print(“Hello, World!”)” in Python 3.
Endpoints
You can run or compile code using JDoodle API through the execute endpoint.
Endpoint | Description | Method |
---|
Input parameters
Parameter | Description | Type | Required |
---|---|---|---|
clientId | Your Client ID | String | Yes |
clientSecret | Your Client Secret | String | Yes |
script | Program to compile and/or execute | String | Yes |
stdin | Standard Input | String | No |
language | Language of the script | String | Yes |
versionIndex | Version index of the language | String | Yes |
compileOnly | Compile without executing (True/False) | Boolean | No |
Example request
curl -L \
-X POST \
-H 'Content-Type: application/json' \
'https://api.jdoodle.com/v1/execute' \
-d '{"clientId":"your_client_id_here","clientSecret":"your_client_secret_here","script":"print(\"Hello, World!\")","stdin":"","language":"python3","versionIndex":"0","compileOnly":False}'
Success response
Field | Description | Type |
---|
Success response example
{
"output": "sum of x+y = 35",
"error": None,
"statusCode": 200,
"memory": "8192",
"cpuTime": "0.01",
"compilationStatus": None,
"projectKey": None,
"isExecutionSuccess": True,
"isCompiled": True
}
WebSocket setup
To establish a WebSocket connection using SockJS and WebStomp, follow these step-by-step instructions:
Include required libraries
Add the SockJS and WebStomp libraries to your HTML file.
<script src="https://api.jdoodle.com/js/sockjs.js"></script>
<script src="https://api.jdoodle.com/js/webstomp.js"></script>
Initialize the WebSocket connection
Use the WebStomp library to create a WebSocket connection with the JDoodle API.
<script>
let socketClient = webstomp.over(new SockJS('https://api.jdoodle.com/v1/stomp'), { heartbeat: False, debug: True });
function onWsConnection() {
console.log('Connection succeeded');
socketClient.subscribe('/user/queue/execute-i', (message) => {
handleMessage(message);
});
sendInitialScript();
}
function onWsConnectionFailed(e) {
console.log('Connection failed');
console.log(e);
}
socketClient.connect({}, onWsConnection, onWsConnectionFailed);
</script>
Send initial script
Send the initial script to be executed when the WebSocket connection is established.
<script>
function sendInitialScript() {
let script = `public class MyClass { public static void main(String args[]) { System.out.println("Hello, World!"); } }`;
let data = JSON.stringify({
script: script,
language: "java",
versionIndex: 4
});
socketClient.send('/app/execute-ws-api-token', data, { message_type: 'execute', token: "your_generated_token_here" });
}
</script>
Sending messages
To interact with the WebSocket API, you can send messages (e.g., additional inputs) and handle responses in real-time.
Handle incoming messages
Define a function to handle incoming messages from the WebSocket connection.
<script>
function handleMessage(message) {
let statusCode = parseInt(message.headers.statusCode);
if (statusCode === 201) {
// Execution started
return;
}
if (statusCode === 500 || statusCode === 410) {
console.log("Server error");
} else if (statusCode === 429) {
console.log("Daily limit reached");
} else if (statusCode === 400) {
console.log("Invalid request");
} else if (statusCode === 401) {
console.log("Unauthorized request");
} else {
var txt = document.getElementById("result").value;
document.getElementById("result").value = txt + message.body;
}
}
</script>
Send additional inputs
Send additional inputs or commands as needed during the WebSocket session.
<script>
function onInput(event) {
let key = event.key;
if (event.key === 'Enter') {
key = '\n';
}
socketClient.send('/app/execute-ws-api-token', key, { message_type: 'input' });
}
</script>
HTML for user interaction
Provide an HTML element for user interaction, such as a textarea
to capture inputs.
<html>
<body>
Output <br>
<textarea rows="5" cols="100" id="result" onkeypress="onInput(event)"></textarea>
</body>
</html>
Example cURL Request
curl -X POST "https://api.jdoodle.com/v1/execute" \
-H "Content-Type: application/json" \
-d '{
"clientId": "your_client_id_here",
"clientSecret": "your_client_secret_here",
"script": "print(\"Hello, World!\")",
"language": "python3",
"versionIndex": "0"
}'
Success Response example
{
"output": "Hello, World!\n",
"statusCode": 200,
"memory": "1024",
"cpuTime": "0.01",
"compilationStatus": 0,
"isExecutionSuccess": True,
"isCompiled": True
}
WebSocket API code examples
Python example
import websocket
import json
def on_message(ws, message):
print("Received:", message)
def on_error(ws, error):
print("Error:", error)
def on_close(ws):
print("Connection closed")
def on_open(ws):
print("Connection opened")
script = "print('Hello, World!')"
data = {
"clientId": "your_client_id_here",
"clientSecret": "your_client_secret_here",
"script": script,
"language": "python3",
"versionIndex": "0"
}
ws.send(json.dumps(data))
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://api.jdoodle.com/v1/execute",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever()
Java example
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class JDoodleWebSocketClient extends WebSocketClient {
public JDoodleWebSocketClient(URI serverUri) {
super(serverUri);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("Connection opened");
String script = "print('Hello, World!')";
String data = String.format("{\"clientId\": \"your_client_id_here\", \"clientSecret\": \"your_client_secret_here\", \"script\": \"%s\", \"language\": \"python3\", \"versionIndex\": \"0\"}", script);
send(data);
}
@Override
public void onMessage(String message) {
System.out.println("Received: " + message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Connection closed");
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
}
public static void main(String[] args) throws Exception {
JDoodleWebSocketClient client = new JDoodleWebSocketClient(new URI("wss://api.jdoodle.com/v1/execute"));
client.connectBlocking();
}
}
Node.js example
const WebSocket = require('ws');
const ws = new WebSocket('wss://api.jdoodle.com/v1/execute');
ws.on('open', function open() {
console.log('Connection opened');
const data = JSON.stringify({
clientId: 'your_client_id_here',
clientSecret: 'your_client_secret_here',
script: "print('Hello, World!')",
language: 'python3',
versionIndex: '0'
});
ws.send(data);
});
ws.on('message', function incoming(message) {
console.log('Received:', message);
});
ws.on('error', function error(err) {
console.error('Error:', err);
});
ws.on('close', function close() {
console.log('Connection closed');
});
HTML example
<!DOCTYPE html>
<html>
<head>
<title>JDoodle WebSocket Example</title>
<script src="https://api.jdoodle.com/js/sockjs.js"></script>
<script src="https://api.jdoodle.com/js/webstomp.js"></script>
</head>
<body>
Output <br>
<textarea rows="5" cols="100" id="result" onkeypress="onInput(event)"></textarea>
<script>
let socketClient = webstomp.over(new SockJS('https://api.jdoodle.com/v1/stomp'), { heartbeat: False, debug: True });
function onWsConnection() {
console.log('Connection succeeded');
socketClient.subscribe('/user/queue/execute-i', (message) => {
document.getElementById("result").value += message.body;
});
let script = `public class MyClass { public static void main(String args[]) { System.out.println("Hello, World!"); } }`;
let data = JSON.stringify({
script: script,
language: "java",
versionIndex: 4
});
socketClient.send('/app/execute-ws-api-token', data, { message_type: 'execute', token: "your_generated_token_here" });
}
function onWsConnectionFailed(e) {
console.log('Connection failed');
console.log(e);
}
function onInput(e) {
let key = event.key;
if (event.key === 'Enter') {
key = '\n';
}
socketClient.send('/app/execute-ws-api-token', key, { message_type: 'input' });
}
socketClient.connect({}, onWsConnection, onWsConnectionFailed);
</script>
</body>
</html>