Quick start
Run your first command from your backend, then keep a session for the next one.
1 Add your API key#
Store your workspace key in your server’s environment to call your worlds.
Create an API key in Settings → API keys and replace swk_replace_with_your_key with its secret value.
SMALLWORLD_API_KEY="swk_replace_with_your_key"
2 Add the request to your backend#
Adapt this snippet in your application. Start with echo hello to check the connection.
Replace YOUR_WORLD_ID with your world’s ID, or open a world and choose Quick start for a prefilled example.
const apiKey = process.env.SMALLWORLD_API_KEY;
if (!apiKey) throw new Error("Set SMALLWORLD_API_KEY on your server.");
const userId = "quickstart-demo"; // Use your application's user ID.
const response = await fetch("https://api.smallworld.sh/api/v1/worlds/YOUR_WORLD_ID/execute", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ userId, command: "echo hello" }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
console.log(result);
3 Understand the response#
When your application sends the request, a successful echo hello returns this output in execution.stdout.
completedexitCode: 0hello
If execution.status is running, read the same execution again to get its result. Wait for completion before sending the next command.
Response fields#
session.id- Keep this for later commands in the same conversation.
execution.id- Use this to read the result of this command.
execution.exitCode- Once completed,
0means the command succeeded. Checkstderrif it failed.
4 Keep a session between commands#
Save session.id for each user and conversation to preserve files and shell state. Once the first execution completes successfully, send the next command using the same session.
if (result.execution.status !== "completed") {
throw new Error(`First execution is ${result.execution.status}. Read the same execution again before continuing.`);
}
if (result.execution.exitCode !== 0) throw new Error("Check the first execution's stderr before continuing.");
const sessionId = result.session.id; // Save with this user's conversation.
const nextResponse = await fetch("https://api.smallworld.sh/api/v1/worlds/YOUR_WORLD_ID/execute", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ userId, sessionId, command: "pwd" }),
});
if (!nextResponse.ok) throw new Error(`HTTP ${nextResponse.status}: ${await nextResponse.text()}`);
const nextResult = await nextResponse.json();
console.log(nextResult);