For builders
Programs that ask questions
The socket is the API's other interface, not a separate product. Same credentials, same languages, same allowance. A connection that stays open instead of a request that returns.
A single request suits a program that reads its input, runs, and prints an answer. Plenty of programs are not like that.
Anything that prompts the user, or produces output over time you want to show as it happens, needs a connection that stays open.
REST
Send the program, wait, get the output. Simple to call and simple to reason about.
Good for grading, tests with fixed input, and anything where you only want the final result.
WebSocket
Open a connection, send the program, and exchange messages while it runs.
Good for interactive programs, streaming output, and a terminal-like experience in your product.
Who talks to whom
The two protocols do not just differ in shape. They put your server in a different place.
- REST. Your page asks your server, your server calls JDoodle with your client ID and secret, and the result comes back the same way. Your server is in the middle of every run, which is what keeps the secret out of the browser.
- WebSocket. Your server asks JDoodle for a short-lived token and hands it to the browser. The browser then opens the socket to JDoodle itself, and everything after that travels between them directly: output as it appears, input as the user types it.
That directness is the point. An interactive program is a conversation, and relaying every line through your server would add a hop to each turn of it while giving you nothing.
Opening a connection
const socket = new WebSocket('wss://api.jdoodle.com/v1/execute')
socket.onopen = () => {
socket.send(JSON.stringify({
clientId: 'yourClientId',
clientSecret: 'yourClientSecret',
script: 'print("Hello, World!")',
language: 'python3',
versionIndex: '0'
}))
}Output arrives as messages rather than as one response, so your product can show it as it appears rather than after the program has finished.
Choosing between them
Start with REST. It is less to build and less to get wrong, and most products that think they need streaming actually want the result. One call from your server, one answer back.
Move to a socket when a user is waiting on output that arrives gradually, or when the program expects to be answered.
What next
Both draw on the same allowance, and knowing how that is counted is what stops a launch going quiet.
WebSocket has the full protocol, with a working sample you can download.