HTTP request

What are HTTP request nodes used for in Node-RED

In Node-RED, an HTTP Request node allows you to make HTTP requests to external servers or services. This allows you to interact with web services, APIs, or any other HTTP-based endpoints.

When you configure an HTTP Request node, you typically specify the method (GET, POST, PUT, DELETE, among others), the URL of the endpoint you want to communicate with, any headers you need to include, and the payload if applicable. Once configured, this node will send the HTTP request when triggered by an incoming message or event.

Configuring HTTP Request node

Below, you'll find a range of settings to tailor HTTP requests to fit the needs of different APIs or web services. Depending on the service you're working with, some options might be crucial, while others could be optional.

  • Method: Select the HTTP method for the request (e.g., GET, POST, PUT, DELETE). You can dynamically set it using msg.method.
  • URL: Specify the endpoint URL to communicate with. Dynamic URL setting is allowed using msg.url. additionally, if you want to construct a URL with the message's property you can utilize Mustache-style tags with double braces {{ }}. For example, example.com/{{topic}}, where the value of msg.topic will be automatically inserted. Using double braces {{ }} performs HTML escaping by default, so special characters in the substituted value will be escaped. However, if you want to preserve special characters like / and & in the constructed URL, you can use triple braces {{{ }}}.
  • Payload: Allows to choose how received payload from the previous node will be sent with the request:
    • Ignore: If enabled Payload will be ignored.
    • Append to query-string parameter: Enabling this option will Allow sending URL query string parameters using msg.payload.
    • Send as request: Send payload data as part of the request body.
  • Enable Secure Connection: Allows to activate SSL/TLS for secure communication. TLS configuration options are available, For more information refer to TLS config node.
  • Use Authentication: If required, allow to provide credentials for authentication.
    • Type: Select the authentication type.
      • basic: Uses Basic authentication where the username and password are sent in the request headers in Base64-encoded form.
        • Username: Provide the username for authentication.
        • Password: Provide the password for authentication.
      • digest: Uses Digest authentication, which is more secure than Basic authentication as it sends hashed passwords rather than plaintext.
      • bearer: Uses Bearer token authentication where a bearer token, typically a JSON Web Token (JWT), is sent in the Authorization header.
        • Token: Provide the bearer token if bearer authentication is selected.
  • Enable Connection Keep-Alive: Enabling this option will allow Maintain persistent connections for efficiency.
  • Use Proxy: Allows to Route requests through a proxy server if necessary, for more information on the configuration of HTTP Proxy config node
  • Only send non-2xx responses to Catch node: Enabling this option will send only non-success responses to the Catch node.
  • Disable Strict HTTP Parsing: Enabling this option relaxes how Node-RED interprets HTTP responses. It's handy when dealing with responses that don't perfectly match the standard HTTP format.
  • Return: Allows to Choose the format for response data conversion
    • A UTF-8 string: Return response data as a UTF-8 string.
    • A binary buffer: Return response data as a binary buffer.
    • A parsed JSON object: Parse response data as JSON and return the object.
  • Headers: Allows to Add headers to the HTTP request such as content-type, accept, user agent, etc. You can dynamically set headers using msg.headers. However Reset msg.headers to avoid unintended header inheritance when using multiple HTTP request nodes in the same flow. Moreover, If msg.payload is an Object, the node automatically sets the Content-Type to application/json.

Usecase

  1. API Integration: The HTTP request node allows seamless integration with external APIs. Developers can utilize it to fetch data from APIs using GET requests or send data to APIs using POST/PUT requests. For instance, fetching weather data from a weather API or posting data to a messaging service like Slack are common scenarios.

  2. Webhooks: With the HTTP request node, users can set up webhooks to trigger actions in response to specific events. This enables real-time communication between different applications. For example, triggering a webhook to notify a third-party service when certain conditions are met or when data is received from a sensor. For more information, refer to Using webhook with Node-RED

  3. Remote Control and Device Management: In smart home systems, the HTTP request node can be used to facilitates remote device management. It allows users to control various devices such as lights, thermostats, and security cameras via web or mobile interfaces by interacting with device APIs. Actions like toggling devices, adjusting settings, and receiving real-time updates can be achieved through the HTTP request node.

These are a few use cases of the HTTP Request node, but its ability to communicate with other services is a significant and core capability. This capability alone opens the door to a diverse array of different use cases.

Examples

  1. Below is an example showing how you can construct a URL with message properties in the HTTP request node, an example includes sending a GET request.
  1. Below is an example showing how you can send an HTTP POST request to a mock API. This example includes registering a user.
  1. Below is an example demonstrating how you can dynamically set the URL, method, and headers for the HTTP request node. Additionally, this example illustrates sending a GET request to a mock API with an authorization token.
  1. Below is an example showing how you can send a PUT request using the HTTP request node.
  1. Below is an example showing how you can send a DELETE request using the HTTP request node.

Output

  • payload: The body of the response can be returned as a string, parsed JSON object, or a binary buffer.
  • statusCode: Indicates the status code of the response or the error code if the request couldn't be completed.
  • headers: An object containing the response headers.
  • responseURL: Provides the final redirected URL if any redirects occurred during processing; otherwise, it shows the URL of the original request.
  • responseCookies: If the response includes cookies, this property is an object containing name/value pairs for each cookie.
  • redirectList: Accumulated information about redirects, including the next redirect destination (location) and cookies returned from the redirect source.

Node Documentation

Sends HTTP requests and returns the response.

Inputs

url string
If not configured in the node, this optional property sets the url of the request.
method string
If not configured in the node, this optional property sets the HTTP method of the request. Must be one of GET, PUT, POST, PATCH or DELETE.
headers object
Sets the HTTP headers of the request. NOTE: Any headers set in the node configuration will overwrite any matching headers in msg.headers
cookies object
If set, can be used to send cookies with the request.
payload
Sent as the body of the request.
rejectUnauthorized
If set to false, allows requests to be made to https sites that use self signed certificates.
followRedirects
If set to false prevent following Redirect (HTTP 301).true by default
requestTimeout
If set to a positive number of milliseconds, will override the globally set httpRequestTimeout parameter.

Outputs

payload string | object | buffer
The body of the response. The node can be configured to return the body as a string, attempt to parse it as a JSON string or leave it as a binary buffer.
statusCode number
The status code of the response, or the error code if the request could not be completed.
headers object
An object containing the response headers.
responseUrl string
In case any redirects occurred while processing the request, this property is the final redirected url. Otherwise, the url of the original request.
responseCookies object
If the response includes cookies, this property is an object of name/value pairs for each cookie.
redirectList array
If the request was redirected one or more times, the accumulated information will be added to this property. `location` is the next redirect destination. `cookies` is the cookies returned from the redirect source.

Details

When configured within the node, the URL property can contain mustache-style tags. These allow the url to be constructed using values of the incoming message. For example, if the url is set to example.com/{{{topic}}}, it will have the value of msg.topic automatically inserted. Using {{{...}}} prevents mustache from escaping characters like / & etc.

The node can optionally automatically encode msg.payload as query string parameters for a GET request, in which case msg.payload has to be an object.

Note: If running behind a proxy, the standard http_proxy=... environment variable should be set and Node-RED restarted, or use Proxy Configuration. If Proxy Configuration was set, the configuration take precedence over environment variable.

Using multiple HTTP Request nodes

In order to use more than one of these nodes in the same flow, care must be taken with the msg.headers property. The first node will set this property with the response headers. The next node will then use those headers for its request - this is not usually the right thing to do. If msg.headers property is left unchanged between nodes, it will be ignored by the second node. To set custom headers, msg.headers should first be deleted or reset to an empty object: {}.

Cookie handling

The cookies property passed to the node must be an object of name/value pairs. The value can be either a string to set the value of the cookie or it can be an object with a single value property.

Any cookies returned by the request are passed back under the responseCookies property.

Content type handling

If msg.payload is an Object, the node will automatically set the content type of the request to application/json and encode the body as such.

To encode the request as form data, msg.headers["content-type"] should be set to application/x-www-form-urlencoded.

File Upload

To perform a file upload, msg.headers["content-type"] should be set to multipart/form-data and the msg.payload passed to the node must be an object with the following structure:

{
    "KEY": {
        "value": FILE_CONTENTS,
        "options": {
            "filename": "FILENAME"
        }
    }
}

The values of KEY, FILE_CONTENTS and FILENAME should be set to the appropriate values.