DEV Community

hediyeh kianmehr
hediyeh kianmehr

Posted on • Edited on

API

Overview

This guide provides step-by-step instructions to understand and practice using APIs with different HTTP methods (GET, POST, PUT, DELETE) in Node-RED.


In this document we cover these topics:

1. What is an API?
-1.1 HTTP Methods (verbs)

2. What’s the Difference Between a Method and an API?

3. Node-RED Setup & Practice Flows


1. What is an API?

API stands for Application Programming Interface.

An API is like a method that takes a request as input and returns a response as output.

Note:
Each API supports its own methods, such as GET, POST, PUT, and DELETE, which are used to perform different actions.

1.1 HTTP Methods (verbs)

They describe what you want to do:

Method Meaning Example Use
GET Read something GET is used to retrieve data from the server and return it to the client
POST Create POST is used to perform an action and save new data to the server.
PUT Update PUT is used to change or update data on the server.
DELETE Remove DELETE sends a request to the server to delete a specific resource or piece of data.

API Request

When you want to interact with an API, you send a request.
This request usually includes:

  • URL (endpoint): Where you want to send the request
  • Method: What action you want to perform (GET, POST, PUT, DELETE)
  • Headers: Extra info like authentication or content type
  • Body (optional): Data you send, mostly for POST or PUT

Note:
In Node-RED, the body of an API request or response is usually found in the msg.payload property.

Example of a GET request to get user data:

GET https://api.example.com/users/1
Headers: Authorization: Bearer TOKEN123
Enter fullscreen mode Exit fullscreen mode

API Response

After the server gets your request, it sends back a response.
This response usually includes:

  • Status code: Shows if the request was successful (200), or if there was an error (404, 500, etc.)
  • Headers: Info about the response
  • Body: The actual data you requested or a message

Example response for the GET request:

Status: 200 OK
Body: {
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com"
}
Enter fullscreen mode Exit fullscreen mode

2. What’s the Difference Between a Method and an API?

Feature Method API
Scope Inside a program Between different programs/systems
Usage Called directly in code Called over network (HTTP, etc.)
Interface for Internal developers External or internal systems
Input/Output Parameters → Return value Request → Response
Example function add(x, y) GET /api/add?x=1&y=2

3. Node-RED Setup & Practice Flows

To better understand how APIs work and how to call them, let's explore some hands-on practice examples.

GET

Practice 1: Basic GET route that returns text

HTTPIn Node

  • Method:GET
  • URL:/hello

This node creates an HTTP GET endpoint at:
http://<your-node-red-host>:<port>/hello

When this endpoint is hit, it triggers two nodes:

  • A function node (which prepares the response).
  • A debug node (which logs the request).

Function Node

msg.payload="hello from hed node red";
return msg;
Enter fullscreen mode Exit fullscreen mode

This sets the message's payload to a simple text:
hello from hed node red

Then passes it to the HTTP response node.

Debug Node

Note:
payload field is left empty (the Inject Node is only used to trigger the flow).

HTTP Response Node

This sends the response back to the client who called /hello.
So, the complete response to calling /hello is:

hello from hed node red
Enter fullscreen mode Exit fullscreen mode

Inject Node

This is a manual trigger. You can click it to start a flow.
It sends an empty JSON payload ({}) to the HTTP request node.

HTTP Request Node

This node sends a GET request to:
https://codenxa.leanea.com/hediyeh//hello

That URL likely proxies or connects to your local /hello endpoint

Debug Node

Displays the response from the HTTP GET request to the external URL.


Practice 2: Basic GET route that returns personalized text

HTTPIn Node

  • Method:GET
  • URL:/greet

This sets up an HTTP GET endpoint:
http://<your-host>:<port>/greet?name=YourName

It accepts a query string, like ?name=Hediyeh.
When hit, it triggers:

  • A function (to handle the response logic).
  • A debug node (to inspect the request).

Function Node

let name = msg.req.query.name;
msg.payload = `bello dear ${name}`;
return msg;
Enter fullscreen mode Exit fullscreen mode

Extracts the name from the query string (e.g. ?name=Hediyeh)

Constructs a response:
bello dear Hediyeh
Sends this string in msg.payload.

HTTP Response Node

Sends the final response back to the client.
So, visiting this URL in a browser or using curl:

https://codenxa.leanea.com/hediyeh//greet?name=Hediyeh
Enter fullscreen mode Exit fullscreen mode

Debug Node

Shows the incoming msg.payload in the debug sidebar.
Helpful for seeing the raw query or payload when testing.

Note:
payload field is left empty (the Inject Node is only used to trigger the flow).

Inject Node

This is a manual trigger. You can click it to start a flow.
It sends an empty JSON payload ({}) to the HTTP request node.

HTTP Request Node

https://codenxa.leanea.com/hediyeh//greet?name=Hediyeh

Sends a GET request to the /greet endpoint.

So you get:

Debug Node

Shows the result of the HTTP request in the debug sidebar.

Purpose Nodes Used
Expose /greet API http in + function + http response + debug
Create test trigger injecthttp requestdebug
Uses query string ?name=Someone extracted via msg.req.query.name in the Function node

Practice 3: Basic GET route that returns personalized text

Description:
Create an HTTP GET route /age that takes two query parameters: name and age. Based on the age, return one of the following responses:

If age < 18: return "child"

If age = 18: return "teen"

If age > 18: return "adult"

Inject Node

Sends a request every time you click it.

{
    "users": [
        {
            "name": "Sara",
            "age": 17
        },
        {
            "name": "Ali",
            "age": 20
        },
        {
            "name": "Maryam",
            "age": 18
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Triggers an HTTP GET request to:

https://codenxa.leanea.com/hediyeh//age
Enter fullscreen mode Exit fullscreen mode

HTTP Request Node

Performs a GET request to the above URL.

The response is shown using the next node.

Debug Node

Shows the HTTP response received from /age in the debug sidebar.

HTTPIn Node

  • Method:GET
  • URL:/age

Defines the GET route /age.
Expects query params: name, age

GET /age?name=Hediyeh&age=25
Enter fullscreen mode Exit fullscreen mode

Function Node

let Userage = parseInt(msg.req.query.age);
let Username= msg.req.query.name;

msg.payload = { name: Username, age: Userage };
return msg;
Enter fullscreen mode Exit fullscreen mode

Extracts and parses query params.

Outputs an object like:

{
  "name": "Hediyeh",
  "age": 25
}
Enter fullscreen mode Exit fullscreen mode

Switch Node

Checks payload.age

<18 → child

==18 → teen

>18 → adult

Change Node

If age < 18
Change node sets:
msg.payload = "child"
Sends to HTTP response.

If age == 18
Change node sets:
msg.payload.age = "teen"
Sends to HTTP response.

If age > 18
Change node uses experession:
msg.payload.name & " is " & msg.payload.age & " years old and is an adult."

Example result:
Ali is 25 years old and is an adult.
Sends to HTTP response.

DELETE

Practice 1:

  • Creating a list of users
  • Retrieving all users
  • Deleting a user by ID
Action Endpoint Method Description
Create users (via Inject) (internal) Injects dummy users into flow context
Get all users /users GET Returns all users stored in memory
Delete user by ID /user/:id DELETE Deletes a user by matching their ID

Creating a list of users

Inject Node

[
  {"id":"1", "name":"hediyeh"},
  {"id":"2", "name":"helia"},
  {"id":"3", "name":"sare"}
]
Enter fullscreen mode Exit fullscreen mode

When triggered, this sends the list to the function node.

Function Node

flow.set("users", msg.payload);  
msg.payload = { message: "Users created", users: msg.payload };
return msg;
Enter fullscreen mode Exit fullscreen mode
  • Saves the users in flow memory (flow.set)
  • Sends a confirmation message with the user list

Debug Node

Shows the confirmation message in the debug panel:

Get All Users

HTTPIn Node

  • Method:GET
  • URL:/users
https://codenxa.leanea.com/hediyeh//users
Enter fullscreen mode Exit fullscreen mode

Function Node

msg.payload = flow.get("users") || [];
return msg;
Enter fullscreen mode Exit fullscreen mode
  • Fetches the user list from memory
  • Sends it as the response

HTTP Response Node

Sends the list as a JSON response.

Delete a User by ID

HTTPIn Node

  • Method:DELETE
  • URL:/user/:id


let users = flow.get("users") || [];
const userId = msg.req.params.id;

const originalLength = users.length;
users = users.filter(u => u.id !== userId);

if (users.length === originalLength) {
    msg.payload = { message: `User ${userId} not found.` };
} else {
    msg.payload = { message: `User ${userId} deleted.`, users };
    flow.set("users", users);
}
return msg;
Enter fullscreen mode Exit fullscreen mode
  • Retrieves the current list from flow memory
  • Filters out the user by ID
  • Checks if deletion was successful (i.e., user existed)
  • Updates the stored list
  • Responds with a success or not found message

Debug Node

Shows the result of the deletion in the debug sidebar.

HTTP Response Node

Sends back either:

{ "message": "User 2 deleted.", "users": [...] }
Enter fullscreen mode Exit fullscreen mode

or

{ "message": "User 2 not found." }
Enter fullscreen mode Exit fullscreen mode

Example: Delete user with ID = 2

curl -X DELETE https://codenxa.leanea.com/hediyeh//user/2
Enter fullscreen mode Exit fullscreen mode
{
  "message": "User 2 deleted.",
  "users": [
    { "id": "1", "name": "hediyeh" },
    { "id": "3", "name": "sare" }
  ]
}
Enter fullscreen mode Exit fullscreen mode

PUT

Practice 1:

  • Creating a list of users
  • Get All Users
  • Update a User’s Status
Action Method Endpoint Description
Create users Inject (Internal) Loads a list of users into memory (flow context)
Get all users GET /users Returns the full list of users
Update user status PUT /user/:id/status Updates a user’s status (e.g. active → inactive)

Creating a list of users

Inject Node

Sends this JSON array into the flow:

[
  {"id": "1", "name": "Ali", "status": "active"},
  {"id": "2", "name": "Sara", "status": "inactive"},
  {"id": "3", "name": "Maryam", "status": "active"}
]
Enter fullscreen mode Exit fullscreen mode

Function Node

flow.set("users", msg.payload);
msg.payload = { message: "Users created", users: msg.payload };
return msg;
Enter fullscreen mode Exit fullscreen mode
  • Stores the user list in flow memory
  • Responds with confirmation and data

Debug Node

Shows this in debug:

Get All Users

HTTPIn Node

  • Method:DELETE
  • URL:/user/:id
GET https://codenxa.leanea.com/hediyeh/users
Enter fullscreen mode Exit fullscreen mode

Function Node

msg.payload = flow.get("users") || [];
return msg;
Enter fullscreen mode Exit fullscreen mode
  • Retrieves the list of users from memory
  • Responds with it

HTTP Response Node

[
  {"id": "1", "name": "Ali", "status": "active"},
  {"id": "2", "name": "Sara", "status": "inactive"},
  {"id": "3", "name": "Maryam", "status": "active"}
]
Enter fullscreen mode Exit fullscreen mode

Update User Status

HTTPIn Node

  • Method:PUT
  • URL:/user/:id/status


PUT https://codenxa.leanea.com/hediyeh/user/2/status
Enter fullscreen mode Exit fullscreen mode

Function Node

let users = flow.get("users") || [];
const userId = msg.req.params.id;
const newStatus = msg.payload.status;

let found = false;

users = users.map(u => {
    if (u.id === userId) {
        found = true;
        return { ...u, status: newStatus };
    }
    return u;
});

flow.set("users", users);

if (found) {
    msg.payload = { message: `User ${userId} status updated.`, users };
} else {
    msg.payload = { message: `User ${userId} not found.` };
}

return msg;
Enter fullscreen mode Exit fullscreen mode
  • Looks up the user by id
  • If found:
  • Updates their status
  • Saves the updated list
  • Sends a success message and full updated list
  • If not found:
  • Sends a “not found” message

How to Test the PUT (update) from CLI

Use this curl command:

curl -X PUT http://localhost:1880/user/2/status \
-H "Content-Type: application/json" \
-d "{\"status\": \"active\"}"
Enter fullscreen mode Exit fullscreen mode

Example Success Response:

{
  "message": "User 2 status updated.",
  "users": [
    {"id": "1", "name": "Ali", "status": "active"},
    {"id": "2", "name": "Sara", "status": "active"},
    {"id": "3", "name": "Maryam", "status": "active"}
  ]
}
Enter fullscreen mode Exit fullscreen mode

POST

Practice 1: Send user data via POST and store it in a file on your Node-RED system.

Steps:

1. Inject Node

  • Payload type: JSON
  • Payload value:
{
    "title": "Hello",
    "body": "This is a test",
    "userId": 5
}
Enter fullscreen mode Exit fullscreen mode

2. Function Node

flow.set("PostData", msg.payload);
return msg;

Enter fullscreen mode Exit fullscreen mode
  • Saves the incoming payload (from Inject) to flow memory under the key PostData.
  • Passes the same msg to the next nodes.

3. HTTP Request Node

  • Method: POST
  • URL: https://jsonplaceholder.typicode.com/posts
  • Sends: The JSON data to this test API.

  • Sends the JSON payload to the JSONPlaceholder fake API.

  • The API fakes saving the post and returns a response with a new id

Expected Output:

{
  "title": "Hello",
  "body": "This is a test",
  "userId": 5,
  "id": 101
}
Enter fullscreen mode Exit fullscreen mode

4. File Node

  • Filename: /tmp/user_data.txt
  • Action: Append payload to this file.

Example Output:

5. Debug Node

Shows the response from the POST API in the debug sidebar.

Node Type Purpose
Inject Simulates sending POST data manually
Function Saves data to flow memory + formats it for file
File Appends user data to /tmp/user_data.txt
HTTP Request Sends the same data to an external test API
Debug Shows the API response

Practice 2: Post Sensor Data to JSONPlaceholder API
See how Node-RED can automate data sending.

Steps:

1. Inject Node

Tick the checkbox labeled "Inject once after 0.1 seconds" — this allows the node to automatically trigger 0.1 seconds after you deploy the flow.

When you click Deploy, the Inject node automatically runs one time, after 0.1 seconds (100 milliseconds).

It sends this payload:

"payload": {
  "sensor": "temperature",
  "value": 23.5,
  "unit": "C"
}
Enter fullscreen mode Exit fullscreen mode

2. HTTP Request Node

  • Method: POST
  • URL: https://jsonplaceholder.typicode.com/posts (a fake API used for testing)

This service just pretends to save your data and replies with a fake response that includes your data and an ID.

3. Debug Node

Shows the response from the POST API in the debug sidebar.


Practice 3: Send Feedback Message to Your Local Express Server in node red what should i do to get answere

const express = require('express');
const app = express();

app.use(express.json());

app.post('/feedback', (req, res) => {
  console.log("✅ Received feedback:", req.body);
  res.send({ status: "ok" });
});

app.listen(3000, () => {
  console.log("🚀 Server is listening on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)