Skip to main content

SSE Debugging

This article introduces you how to debug SSE (Server-Sent Events) in Apidog.

SSE (Server-Sent Events) is a real-time communication technology based on the HTTP protocol. It allows for the establishment of a persistent, one-way connection between the client and the server, enabling the server to send asynchronous messages to the client.

Initiating SSE Connection

To initiate an SSE connection, create a new API in your HTTP project. After sending the request, if the response Content-Type includes text/event-stream, Apidog will automatically parse the returned data as SSE events and update the response content in real-time on a new timeline view, without waiting for the server to close the connection.

Extracting Message Content through Post-Request Scripts

Add a custom script in the post-request script of the current API to extract a specific field value from each SSE event and concatenate it into a complete string.

Taking the API shown in the above diagram as an example, each message returned by this API contains a JSON structure. We want to extract the answer field from the response and concatenate its parameter contents into a complete text.

Write the following example code in the custom script:

// Get the response text
const text = pm.response.text()
// Split the text into lines
var lines = text.split('\n');
// Create an empty array to store the "content" parameter
var contents = [];
// Iterate through each line
for (var i = 0; i < lines.length; i++) {
const line = lines[i];
// Skip lines that do not start with "data:"
if (!line.startsWith('data:')) {
// Try to parse the JSON data
try {
var data = JSON.parse(line.substring(5).trim()); // Remove the leading "data: "
// Get the "content" parameter from the "choices" array and add it to the array
} catch (e) {
// Ignore the current line if it is not valid JSON data
// Join the "content" parameters using the join() method
var result = contents.join('');
// Display the result in the "Visualize" tab of the body
// Print the result to the console

After sending the request, the concatenated text will be displayed in the Visualize section of the Body.