Spanish Total.js
English
Documentation For AI agents
Contents

Create a POST endpoint with validation

Accept JSON data, check it and answer with success or with a 400 error.

.md GitHub
On this page

This endpoint accepts an order at POST /api/orders/. It answers 200 with the order when a product is given, and 400 with an error when it is missing.

Route, a Code node with two outputs and two Response nodes, the second one with status 400

Build it

  1. Drag Route, Code and two Response nodes onto the canvas.
  2. Double-click Route. Set Method to POST, Relative URL address to /api/orders/ and Send to output to Payload. Select APPLY.
  3. Double-click Code. Set Name to Check order, Number of outputs to 2, and paste the code below. Select APPLY.
  4. Double-click the second Response. Set Type to JSON, Status code to 400, empty Path for reading value and select APPLY. Keep the first Response as it is.
  5. Connect Request of Route to Input of Code, Output #1 to the first Response and Output #2 to the second Response.
  6. Select APPLY in the toolbar, then Continue.

The Code settings with the validation code and two outputs

The code of the Code node:

if (!value.product) {
    $.send('output2', { error: 'The product is required.' });
    return;
}

send({ response: { success: true, product: value.product, quantity: value.quantity || 1 } });

With Send to output set to Payload, value is the JSON body of the request. send() uses the first output and $.send('output2', ...) the second one. The first Response keeps its default path response, so it sends the object inside response.

Try it

curl -X POST -H 'Content-Type: application/json' --data '{"product":"Demo product","quantity":2}' http://localhost:8000/api/orders/
{"success":true,"product":"Demo product","quantity":2}

Without a quantity, the answer uses 1:

{"success":true,"product":"Demo product","quantity":1}

Without a product, the status is 400:

curl -X POST -H 'Content-Type: application/json' --data '{"quantity":2}' http://localhost:8000/api/orders/
{"error":"The product is required."}
Made in Europe