/ docs / docs / documentation / developing / tutorials / rest-gateway.md
rest-gateway.md
  1  ---
  2  title: REST Gateway
  3  sidebar_position: 15
  4  ---
  5  
  6  
  7  Agent Mesh REST API Gateway provides a standard, robust, and secure HTTP-based entry point for programmatic and system-to-system integrations. It allows external clients to submit tasks to Agent Mesh agents, manage files, and discover agent capabilities using a familiar RESTful interface.
  8  
  9  The gateway is designed to be highly configurable and supports two distinct operational modes to cater to both modern, asynchronous workflows and legacy, synchronous systems.
 10  
 11  ## Key Features
 12  
 13  *   **Dual API Versions**: Supports both a modern asynchronous API (v2) and a deprecated synchronous API (v1) for backward compatibility.
 14  *   **Asynchronous by Default**: The v2 API uses a "202 Accepted + Poll" pattern, ideal for long-running agent tasks.
 15  *   **Delegated Authentication**: Integrates with an external authentication service via bearer tokens for secure access.
 16  *   **File Handling**: Supports file uploads for tasks and provides download URLs for generated artifacts.
 17  *   **Dynamic Configuration**: All gateway behaviors, including server settings and authentication, are configured via the main Agent Mesh Host YAML file.
 18  
 19  ## Setting Up the Environment
 20  
 21  First, you need to [install Agent Mesh and the Agent Mesh CLI](../../installing-and-configuring/installation.md), and then [create a new Agent Mesh project](../../installing-and-configuring/run-project.md).
 22  
 23  ## Adding the REST Gateway Plugin
 24  
 25  Once you have your project set up, add the REST Gateway plugin:
 26  
 27  ```sh
 28  sam plugin add my-http-rest --plugin sam-rest-gateway
 29  ```
 30  
 31  You can use any name for your agent, in this tutorial we use `my-http-rest`.
 32  
 33  This command:
 34  1. Installs the `sam-rest-gateway` plugin
 35  2. Creates a new gateway configuration named `my-http-rest` in your `configs/gateways/` directory
 36  
 37  
 38  ### Configuring the REST Gateway
 39  
 40  For further configuration, you can edit the `configs/gateways/my-http-rest.yaml` file. This file contains the gateway configuration that can be customized for your use case.
 41  
 42  :::info[Using a local Solace Broker container]
 43  The Solace broker container uses port 8080. You need to edit the `rest_api_server_port` field and `external_auth_service_url` field in the `configs/gateways/my-http-rest.yaml` file to a free port other than 8080 (for example: 8081).
 44  
 45  You can edit the YAML file directly or add environment variables `REST_API_PORT=8081` and `EXTERNAL_AUTH_SERVICE_URL=http://localhost:8081`.
 46  
 47  Make sure you change the REST API gateway to your new port in the following request examples.
 48  :::
 49  
 50  ## Running the REST Gateway
 51  
 52  To run the REST Gateway, use the following command:
 53  
 54  ```sh
 55  sam run configs/gateways/my-http-rest.yaml
 56  ```
 57  
 58  ## REST API Reference
 59  
 60  This section provides detailed curl commands for interacting with the Solace Agent Mesh v2 REST API.
 61  
 62  ### Setup
 63  
 64  Set the required environment variables:
 65  
 66  ```sh
 67  export SAM_TOKEN="your-access-token"
 68  export SAM_HOST="http://localhost:8000"  # adjust for your environment
 69  ```
 70  
 71  :::note[Getting Your Access Token]
 72  You can retrieve your access token from the WebUI gateway by opening the browser developer console and entering:
 73  
 74  ```javascript
 75  console.log(window.localStorage.access_token)
 76  ```
 77  
 78  Copy the displayed token and use it as your `SAM_TOKEN` value.
 79  :::
 80  
 81  ### API Operations
 82  
 83  #### 1. Create Task
 84  
 85  Create a new task with a prompt.
 86  
 87  ```sh
 88  curl -s -X POST "${SAM_HOST}/api/v2/tasks" \
 89      -H "Authorization: Bearer ${SAM_TOKEN}" \
 90      -F "agent_name=OrchestratorAgent" \
 91      -F "prompt=Hi!"
 92  ```
 93  
 94  **Parameters:**
 95  - `agent_name` - The agent to handle the task (e.g., OrchestratorAgent)
 96  - `prompt` - The task prompt/question
 97  
 98  **Response:**
 99  
100  ```json
101  {
102    "taskId": "abc123-def456",
103    ...
104  }
105  ```
106  
107  #### 2. Create Task with Artifact Generation
108  
109  Create a task that generates an artifact (file).
110  
111  ```sh
112  curl -s -X POST "${SAM_HOST}/api/v2/tasks" \
113      -H "Authorization: Bearer ${SAM_TOKEN}" \
114      -F "agent_name=OrchestratorAgent" \
115      -F "prompt=Create a csv file with 10 mock employees. Make sure to provide the created artifact."
116  ```
117  
118  #### 3. Create Task with File Input
119  
120  Create a task with a file attachment.
121  
122  ```sh
123  curl -s -X POST "${SAM_HOST}/api/v2/tasks" \
124      -H "Authorization: Bearer ${SAM_TOKEN}" \
125      -F "agent_name=OrchestratorAgent" \
126      -F "prompt=Give a summary of the attached file" \
127      -F "files=@/path/to/your/file.pdf"
128  ```
129  
130  **Parameters:**
131  - `files` - File attachment (use @ prefix for file path)
132  
133  #### 4. Poll Task Status
134  
135  Poll the status of a task until completion.
136  
137  ```sh
138  curl -s -X GET "${SAM_HOST}/api/v2/tasks/${TASK_ID}" \
139      -H "Authorization: Bearer ${SAM_TOKEN}"
140  ```
141  
142  **Response includes:**
143  - `taskId` - The task identifier
144  - `contextId` - Context ID (use this value for the `session_id` parameter in artifact operations)
145  - `status` - Task status (e.g., `completed`, `in_progress`)
146  
147  :::warning
148  It might take a while for the system to respond. See the [observability](../../deploying/observability.md) page for more information about monitoring the system while it processes the request.
149  :::
150  
151  #### 5. List Artifacts
152  
153  List all artifacts for a context.
154  
155  ```sh
156  curl -s -X GET "${SAM_HOST}/api/v2/artifacts/?session_id=${CONTEXT_ID}" \
157      -H "Authorization: Bearer ${SAM_TOKEN}"
158  ```
159  
160  :::info
161  The query parameter is `session_id`, but the value comes from `contextId` in the poll response.
162  :::
163  
164  **Response:**
165  
166  ```json
167  [
168    {
169      "filename": "employees.csv",
170      ...
171    }
172  ]
173  ```
174  
175  #### 6. Get Artifact
176  
177  Download a specific artifact and save to a file.
178  
179  ```sh
180  # Save to file (works for binary files like images)
181  curl -s -X GET "${SAM_HOST}/api/v2/artifacts/${FILENAME}?session_id=${CONTEXT_ID}" \
182      -H "Authorization: Bearer ${SAM_TOKEN}" \
183      -o "${FILENAME}"
184  ```
185  
186  **Examples:**
187  
188  ```sh
189  # Download a CSV file
190  curl -s -X GET "${SAM_HOST}/api/v2/artifacts/report.csv?session_id=${CONTEXT_ID}" \
191      -H "Authorization: Bearer ${SAM_TOKEN}" \
192      -o "report.csv"
193  
194  # Download a PNG image
195  curl -s -X GET "${SAM_HOST}/api/v2/artifacts/chart.png?session_id=${CONTEXT_ID}" \
196      -H "Authorization: Bearer ${SAM_TOKEN}" \
197      -o "chart.png"
198  
199  # Output text file to stdout (for piping)
200  curl -s -X GET "${SAM_HOST}/api/v2/artifacts/data.json?session_id=${CONTEXT_ID}" \
201      -H "Authorization: Bearer ${SAM_TOKEN}"
202  ```
203  
204  #### 7. Refresh Token
205  
206  Refresh an access token.
207  
208  ```sh
209  curl -s -X POST "${SAM_HOST}/refresh_token" \
210      -H "Authorization: Bearer ${SAM_TOKEN}" \
211      -H "Content-Type: application/json" \
212      -d '{
213          "provider": "azure",
214          "refresh_token": "your-refresh-token"
215      }'
216  ```
217  
218  **Response:**
219  
220  ```json
221  {
222    "access_token": "new-access-token",
223    "refresh_token": "new-refresh-token"
224  }
225  ```
226  
227  ### Typical Workflow
228  
229  ```sh
230  # 1. Set your token
231  export SAM_TOKEN="your-token"
232  export SAM_HOST="http://localhost:8000"
233  
234  # 2. Create a task
235  RESPONSE=$(curl -s -X POST "${SAM_HOST}/api/v2/tasks" \
236      -H "Authorization: Bearer ${SAM_TOKEN}" \
237      -F "agent_name=OrchestratorAgent" \
238      -F "prompt=Create a CSV with 5 products")
239  
240  TASK_ID=$(echo $RESPONSE | jq -r '.taskId')
241  echo "Task ID: $TASK_ID"
242  
243  # 3. Poll until complete
244  POLL_RESPONSE=$(curl -s -X GET "${SAM_HOST}/api/v2/tasks/${TASK_ID}" \
245      -H "Authorization: Bearer ${SAM_TOKEN}")
246  
247  echo $POLL_RESPONSE | jq .
248  
249  # 4. Get context ID from poll response, then list artifacts
250  CONTEXT_ID=$(echo $POLL_RESPONSE | jq -r '.contextId')
251  
252  curl -s -X GET "${SAM_HOST}/api/v2/artifacts/?session_id=${CONTEXT_ID}" \
253      -H "Authorization: Bearer ${SAM_TOKEN}" | jq .
254  
255  # 5. Download artifact
256  FILENAME="products.csv"
257  curl -s -X GET "${SAM_HOST}/api/v2/artifacts/${FILENAME}?session_id=${CONTEXT_ID}" \
258      -H "Authorization: Bearer ${SAM_TOKEN}" \
259      -o "${FILENAME}"
260  
261  echo "Saved to: ${FILENAME}"
262  ```
263  
264  ### API Endpoints Summary
265  
266  | Operation | Method | Endpoint |
267  |-----------|--------|----------|
268  | Create Task | POST | `/api/v2/tasks` |
269  | Poll Task | GET | `/api/v2/tasks/{taskId}` |
270  | List Artifacts | GET | `/api/v2/artifacts/?session_id={contextId}` |
271  | Get Artifact | GET | `/api/v2/artifacts/{filename}?session_id={contextId}` |
272  | Refresh Token | POST | `/refresh_token` |
273  
274  ## Legacy API (v1) - Synchronous
275  
276  :::warning[Deprecated]
277  The v1 API is deprecated. Please use the v2 API for new integrations.
278  :::
279  
280  ```sh
281  curl --location 'http://localhost:8080/api/v1/invoke' \
282  --header 'Authorization: Bearer None' \
283  --form 'prompt="Suggest some good outdoor activities in London given the season and current weather conditions."' \
284  --form 'agent_name="OrchestratorAgent"' \
285  --form 'stream="false"'
286  ```
287  
288  **Sample output:**
289  
290  ```json
291  {
292    "id": "task-9f7d5f465f5a4f1ca799e8e5ecb35a43",
293    "sessionId": "rest-session-36b36eeb69b04da7b67708f90e5512dc",
294    "status": {
295      "state": "completed",
296      "message": {
297        "role": "agent",
298        "parts": [
299          { "type": "text", "text": "Outdoor Activities in London: Spring Edition. Today's Perfect Activities (13°C, Light Cloud): - Royal Parks Exploration : Hyde Park and Kensington Gardens..." }
300        ]
301      },
302      "timestamp": "2025-07-03T16:59:37.486480"
303    },
304    "artifacts": [],
305    "metadata": { "agent_name": "OrchestratorAgent" }
306  }
307  ```