Back to 12 Factor Agents

Chapter 8 - Adding API Endpoints

workshops/2025-05/sections/08-api-endpoints/README.md

latest1.6 KB
Original Source

Chapter 8 - Adding API Endpoints

Add an Express server to expose the agent via HTTP.

for this section, we'll disable the baml logs. You can optionally enable them if you want to see more details.

export BAML_LOG=off

Install Express and types

npm install express && npm install --save-dev @types/express supertest

Add the server implementation

cp ./walkthrough/08-server.ts src/server.ts
<details> <summary>show file</summary>
ts
// ./walkthrough/08-server.ts
import express from 'express';
import { Thread, agentLoop } from '../src/agent';

const app = express();
app.use(express.json());
app.set('json spaces', 2);

// POST /thread - Start new thread
app.post('/thread', async (req, res) => {
    const thread = new Thread([{
        type: "user_input",
        data: req.body.message
    }]);
    const result = await agentLoop(thread);
    res.json(result);
});

// GET /thread/:id - Get thread status 
app.get('/thread/:id', (req, res) => {
    // optional - add state
    res.status(404).json({ error: "Not implemented yet" });
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

export { app };
</details>

Start the server

npx tsx src/server.ts

Test with curl (in another terminal)

curl -X POST http://localhost:3000/thread \

-H "Content-Type: application/json"
-d '{"message":"can you add 3 and 4"}'

You should get an answer from the agent which includes the agentic trace, ending in a message like:

{"intent":"done_for_now","message":"The sum of 3 and 4 is 7."}