Node-RED HTTP ノードガイド

🖥️ ローカル/ラズパイ 環境とは?
通信が初めての方へ: サーバーとクライアント、ポート、プロトコルの全体像は 通信の基礎(ネットワーク入門) でまとめて解説しています。先に読むと本ガイドが理解しやすくなります。

目次

1. 概要

Node-RED には HTTP通信に関連する3つのノードが用意されています。これらを組み合わせることで、WebサーバーやAPIクライアントの機能を実装できます。

💡 そもそも「API」とは?

API(Application Programming Interface)とは、プログラム同士がデータをやり取りするための「窓口」です。レストランに例えると分かりやすくなります。

このガイドで扱うHTTPは、この「注文のやり取り」に使われる共通のルール(プロトコル)です。「APIを呼び出す」とは、決まった形式でリクエストを送り、レスポンスを受け取ることを指します。

HTTP In

HTTP In

役割: HTTPリクエストを受信(サーバー機能)

URLエンドポイントを定義し、外部からのリクエストを受け付けます

HTTP Response

HTTP Response

役割: HTTPレスポンスを送信(サーバー機能)

リクエストに対してステータスコードとデータを返します

HTTP Request

HTTP Request

役割: 外部APIにリクエストを送信(クライアント機能)

外部のWebサービスやAPIを呼び出します

重要: HTTP In と HTTP Response はペアで使用します。HTTP Response がないと、リクエスト元はタイムアウトまで待ち続けます。

基本フローパターン

サーバー機能(API提供):

HTTP In → 処理 → HTTP Response

クライアント機能(API呼び出し):

Inject → HTTP Request → Debug

動作を図で見る

http in ノードは、ブラウザなどからの要求を待ち受けて msg を作り、http response ノードがその相手に応答を返します。http request ノードは、逆に Node-RED から外の URL へ要求を送ります。

ブラウザhttp intemplatehttp responseGET /hello「こんにちは」の HTMLmsg.res を使って、同じ相手に返す
http in で受けた要求に、途中で作った payload を http response で返す
きっかけの msghttp request天気 APIGET https://api…/weather200 {"weather":"晴れ"}出ていく msgpayload: {weather: "晴れ"}statusCode: 200(出力形式を「JSON」にしたとき)
http request は、返ってきた本文とステータスコードを msg に入れて送り出す

2. HTTP In ノード

主要プロパティ

プロパティ説明例
メソッド受け付けるHTTPメソッドGET, POST, PUT, DELETE
URLエンドポイントのパス/api/data, /users/:id
名前ノードの表示名GET /api/sensors

メソッドによっては、ボディの扱いを決める次の項目が追加で現れます。GET のときはどちらも表示されません。

設定項目説明既定値
ファイルのアップロードメソッドが POST のときだけ表示される。multipart/form-data で送られたファイルを受け取る。ファイルの内容は msg.req.files に入るオフ
リクエストボティをパースしないメソッドが POST / PUT / PATCH / DELETE のときに表示される。ボディを解析せず、受け取ったバイト列のまま msg.payload に入れる。独自形式の受信や、署名の検証で生データが要るときに使うオフ

「リクエストボティ」は Node-RED 本体の日本語表示をそのまま載せています。エディター上でもこの表記で表示されます。

💡 URLパラメータ(補足): 上の表の「URL」に :パラメータ名 を含めると、動的なパスを定義できます。

// URL設定: /users/:userId/posts/:postId // リクエスト: GET /users/123/posts/456 // msg.req.params の内容: { "userId": "123", "postId": "456" }

出力される msg のプロパティ(HTTP In が自動設定)

プロパティ説明例
msg.payloadリクエストボディPOSTで送られたJSONなど
msg.req.paramsURLパラメータ{id: "123"}
msg.req.queryクエリパラメータ{page: "1", limit: "10"}
msg.req.headersリクエストヘッダー{"content-type": "..."}
msg.req.bodyリクエストボディ(生)POSTデータ

エンドポイントのアクセス方法

http://localhost:1880/[設定したURL]

例: URLを /api/hello に設定した場合

http://localhost:1880/api/hello

3. HTTP Response ノード

主要プロパティ

設定項目説明既定値
ステータスコードHTTPステータスコード(msg.statusCodeを使用)
ヘッダ追加ヘッダー(msg.headersを使用)

入力する msg のプロパティ(HTTP Response に渡す前に設定)

プロパティ説明例
msg.payloadレスポンスボディJSON、HTML、テキスト
msg.statusCodeステータスコード200, 201, 400, 404, 500
msg.headersレスポンスヘッダー{"Content-Type": "..."}

主要なHTTPステータスコード

コード意味用途
200OK成功(デフォルト)
201Createdリソース作成成功
400Bad Requestリクエスト形式エラー
401Unauthorized認証必要
404Not Foundリソースが存在しない
500Internal Server Errorサーバー内部エラー

ステータスコード欄の使い分け

欄を空にしておくと msg.statusCode が使われ、それも無ければ 200 が返ります。内容を見て自動で判断されるわけではありません。エラーを表す payload を返しても、設定しなければ 200 のままです。

やりたいこと設定
常に200でよい欄は空のまま(何もしなくてよい)
常に同じ200以外を返す(201など)欄に固定値を入れる
成功と失敗で返し分ける欄は空にして msg.statusCode で決める
注意: 欄に値を入れると msg.statusCode より優先されます。Functionノードで404を設定しても、欄に200が入っていれば常に200で返ります。返し分けたいときは欄を空にしてください。
どこまで返し分けるか: ステータスコードは60種類以上ありますが、全部を使う必要はありません。上の表の200・400・404・500があれば社内向けAPIはたいてい足ります。呼び出し側が結果によって動きを変えないなら、200だけを返すフローでも構いません。返し分けが要るのは、ブラウザの fetch、HTTP Requestノードの分岐、監視ツールなど、受け取る側がコードを見て判断するときです。

4. HTTP Request ノード

設定項目

エディターの表示順に並べています。「TLS設定」「種別」「ユーザ名」「パスワード」「トークン」「プロキシ設定」は、直前のチェックボックスや選択に応じて表示される欄です。

設定項目説明既定値
メソッド送信するHTTPメソッド。GET / POST / PUT / DELETE / HEAD から選ぶ。「- msg.methodに定義 -」を選ぶと msg.method の値を使うGET
URLリクエスト先のURL。空欄にすると msg.url を使う。https://example.com/{{{topic}}} のように書くと、msg のプロパティ(この例では msg.topic)を埋め込める。二重括弧 {{ }} では / や & がエスケープされるため、三重括弧を使う(空)
ペイロードmsg.payload をリクエストにどう載せるか(無視 / クエリパラメータに追加 / リクエストボディとして送信)。メソッドが GET のときだけ表示される。POST や PUT などでは msg.payload がボディとして送られる(HEAD ではボディは送られない)無視
SSL/TLS接続を有効化https の接続で使う証明書を指定するときにオンにする。公的なCAの証明書を使うサイトなら、URLを https にするだけでよく、オフのままでよい。自作CAや社内CAのサーバーに接続するときに使うオフ
TLS設定「SSL/TLS接続を有効化」をオンにすると表示される。証明書を指定したTLS設定ノードを選ぶ。各欄の意味はTLSと証明書ガイドを参照(なし)
認証を使用オンにすると、下の「種別」「ユーザ名」「パスワード」が表示される。Web API が認証を求めるときに使うオフ
種別認証の方式。Basic認証 / Digest認証 / Bearer認証。API の説明書に書かれた方式を選ぶ。Bearer認証は、API キーやアクセストークンを Authorization: Bearer … ヘッダで送る方式Basic認証
ユーザ名Basic認証とDigest認証で使うユーザー名。Bearer認証では表示されない(空)
パスワードBasic認証とDigest認証のパスワード。ユーザ名とともに資格情報として保存され、フローを書き出しても含まれない(空)
トークンBearer認証を選ぶと、「パスワード」の欄がこの名前に変わる。API から発行されたトークン(APIキー)を入れる。パスワードと同じく資格情報として保存される(空)
コネクションkeep-aliveを有効化同じサーバーへの接続を使い回す。短い間隔で何度もリクエストする場合に、接続のたびの準備(https ではTLSのハンドシェイクも)を省けるオフ
プロキシを使用社内ネットワークなど、外部への通信がプロキシサーバーを経由する環境でオンにするオフ
プロキシ設定「プロキシを使用」をオンにすると表示される。プロキシ設定ノードを選ぶ。プロキシ設定ノードには「名前」「URL」(プロキシサーバーのURL)、「プロキシ認証を使用」(オンで「ユーザ名」「パスワード」を入力)、「例外ホスト」(プロキシを通さないホストの一覧)の欄がある(なし)
2xx以外の応答をcatchノードへ送信接続できない、タイムアウト、証明書エラーなど、応答を受け取れなかった失敗の送り先を決める。オンでは catch ノードだけに送り、オフでは catch ノードと出力の両方に送る。名前に反して、404 や 500 などの応答は、この設定に関係なく通常どおり出力される(msg.statusCode で判別する)オフ
厳密なHTTPパース処理を無効化HTTPの規格に厳密に従っていない応答も受け付ける。古い機器や組み込み機器のWebサーバーで、応答の読み取りに失敗するときだけオンにする。不正な応答を受け入れることになるため、ふだんはオフのままにするオフ
出力形式応答の本文をどの型で msg.payload に入れるか。UTF8文字列 / バイナリバッファ / JSONオブジェクト。JSONオブジェクトを選んで解析に失敗した場合は、文字列のまま出力されるUTF8文字列
ヘッダリクエストに付けるHTTPヘッダを、名前と値の組で追加する。msg.headers と同じ名前のヘッダがある場合は、この欄の値が優先される(空)
名前ノードに表示する名前(空)

メソッドの選択肢

オプション用途ボディ
GETデータ取得、検索なし
POSTデータ送信、新規作成あり
PUTデータ更新(全体置換)あり
DELETEデータ削除任意
HEADヘッダー情報のみ取得なし
- msg.methodに定義 -msg.method で動的に指定可変

出力形式の選択肢

オプション説明用途
UTF8文字列文字列として受信テキスト、HTML、JSON
バイナリバッファBufferオブジェクト画像、ファイル
JSONオブジェクト自動でJSONパースREST API

動的なURL設定

URLを空にすると、msg.url でURLを動的に指定できます:

// Function ノードで動的にURL設定 msg.url = "https://api.example.com/users/" + msg.payload.userId; return msg;

動的なヘッダー設定

// Function ノードでヘッダーを設定 msg.headers = { "Content-Type": "application/json", "Authorization": "Bearer " + flow.get("apiToken") }; return msg;

APIテスト用リソース

以下の認証不要で安定した公開APIを使ってテストできます:

World Time API(time.now)

世界各地の現在時刻を取得

https://time.now/developer/api/time?timezone=Asia/Tokyo

提供元: World Time API by Time.Now(無料で使えるかわりに、使う側のサイトやアプリに提供元へのリンクを載せることが求められています。詳しくは time.now/developer を参照)

postman-echo.com

HTTPリクエストのテストやデバッグ用

https://postman-echo.com/get, /post, /status/200

JSONPlaceholder

REST APIのテスト用(TODOリスト、投稿など)

https://jsonplaceholder.typicode.com/todos/1

5. 実用的な使用パターン

📥 サンプルフローを試す手順:

フローJSONは、Node-REDエディタの「読み込み」画面に貼り付けるためのものです。ブラウザの開発者ツール(Console)に貼り付けても何も起きません。

  1. Node-REDを起動し、ブラウザでエディタを開く(http://localhost:1880)
  2. 下の「公式サンプルフローJSON」を「コピー」ボタンでコピー
  3. エディタ右上の メニュー → 読み込み を選択し、JSONを貼り付けて「読み込み」をクリック
  4. エディタ右上の「デプロイ」ボタンをクリック(クリックするまでフローは動きません)
  5. 後述の「動作確認方法」の手順で、動作を確認する

公式サンプルフロー

最初のサンプルフローは、Node-RED本体に同梱されている公式サンプル(「Create HTTP endpoint」から「Working with cookies」までの7例)を1つのタブにまとめ、ノード名を日本語化したものです。エディタの メニュー → 読み込み → サンプル → node-red → network → http からも同じものを開けます。

💼 使いどころ:

📥 公式サンプルフローJSON(クリックで展開)
[ { "id": "http_examples_tab", "type": "tab", "label": "http", "disabled": false, "info": "", "env": [] }, { "id": "87bd706a.aec93", "type": "comment", "z": "http_examples_tab", "name": "Create an HTTP Endpoint", "info": "The `HTTP In` and `HTTP Response` pair of nodes are the starting point for all HTTP endpoints you create.\n\nAny flow that starts with an `HTTP In` node must have a path to an `HTTP Response` node otherwise requests will eventually timeout.\n\nThe `HTTP Response` node uses the `payload` property of messages it receives as the body of the response. Other properties can be used to further customize the response - they are covered in other recipes.\n\nThe `Template` node provides a convenient way to embed a body of content into a flow. It may be desirable to maintain such static content outside of the flow.\n\nSee Node-RED cookbook [item](https://cookbook.nodered.org/http/create-an-http-endpoint) for details.", "x": 230, "y": 40, "wires": [] }, { "id": "7f10afe.b1faa5", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello", "method": "get", "upload": false, "swaggerDoc": "", "x": 240, "y": 80, "wires": [ [ "db134063.83b7a" ] ] }, { "id": "d5ce67fc.e6e608", "type": "http response", "z": "http_examples_tab", "name": "", "statusCode": "", "headers": {}, "x": 490, "y": 80, "wires": [] }, { "id": "5a89ce70.db6d5", "type": "http request", "z": "http_examples_tab", "name": "", "method": "GET", "ret": "txt", "paytoqs": "ignore", "url": "http://localhost:1880/hello", "tls": "", "persist": false, "proxy": "", "authType": "", "x": 390, "y": 220, "wires": [ [ "18b48ed8.1072e1" ] ] }, { "id": "31f7aabb.3fbe06", "type": "inject", "z": "http_examples_tab", "name": "GET /hello を送る", "props": [ { "p": "payload" }, { "p": "topic", "vt": "str" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "", "payloadType": "date", "x": 240, "y": 220, "wires": [ [ "5a89ce70.db6d5" ] ] }, { "id": "18b48ed8.1072e1", "type": "debug", "z": "http_examples_tab", "name": "/hello の応答", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "false", "statusVal": "", "statusType": "auto", "x": 550, "y": 220, "wires": [] }, { "id": "3c61c12c.5abaae", "type": "comment", "z": "http_examples_tab", "name": "Send HTTP request: http://localhost:1880/hello", "info": "`http request` node can be used to make an **HTTP GET** request.\n\nSee Node-RED cookbook [item](https://cookbook.nodered.org/http/simple-get-request) for details.", "x": 300, "y": 140, "wires": [] }, { "id": "db134063.83b7a", "type": "template", "z": "http_examples_tab", "name": "ページ生成", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<html>\n <head></head>\n <body>\n <h1>Hello World!</h1>\n </body>\n</html>", "output": "str", "x": 370, "y": 80, "wires": [ [ "d5ce67fc.e6e608" ] ] }, { "id": "83e766b1.154438", "type": "http request", "z": "http_examples_tab", "name": "", "method": "GET", "ret": "txt", "paytoqs": "ignore", "url": "", "tls": "", "persist": false, "proxy": "", "authType": "", "x": 390, "y": 300, "wires": [ [ "188bc18.5487a3f" ] ] }, { "id": "89c4d7a7.f8d798", "type": "inject", "z": "http_examples_tab", "name": "msg.url で GET /hello を送る", "props": [ { "p": "payload" }, { "p": "url", "v": "http://localhost:1880/hello", "vt": "str" }, { "p": "topic", "vt": "str" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "", "payloadType": "date", "x": 240, "y": 300, "wires": [ [ "83e766b1.154438" ] ] }, { "id": "188bc18.5487a3f", "type": "debug", "z": "http_examples_tab", "name": "msg.url で呼んだ /hello の応答", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "false", "statusVal": "", "statusType": "auto", "x": 550, "y": 300, "wires": [] }, { "id": "a65364a3.c72a58", "type": "comment", "z": "http_examples_tab", "name": "Set URL in HTTP request node setting panel", "info": "`http request` node can be used to make an **HTTP GET** request.\n\nSee Node-RED cookbook [item](https://cookbook.nodered.org/http/simple-get-request) for details.", "x": 490, "y": 180, "wires": [] }, { "id": "47396a8e.6804f4", "type": "comment", "z": "http_examples_tab", "name": "Set URL via url property of input message of HTTP request node", "info": "Target URL of `http request` node can be specified via `url` property of input message.\n\nSee Node-RED cookbook [item](https://cookbook.nodered.org/http/set-request-url) for details.", "x": 550, "y": 260, "wires": [] }, { "id": "ac0b58f6.c85138", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-query", "method": "get", "upload": false, "swaggerDoc": "", "x": 260, "y": 440, "wires": [ [ "d9c345c7.c2e148" ] ] }, { "id": "c110b7f7.22f238", "type": "http response", "z": "http_examples_tab", "name": "", "statusCode": "", "headers": {}, "x": 530, "y": 440, "wires": [] }, { "id": "976b2bb3.f5ff98", "type": "comment", "z": "http_examples_tab", "name": "Handle query parameters passed to an HTTP endpoint", "info": "The `HTTP in` node can accept query parameters passwd to an HTTP endpoint. It use the `msg.req.query` property of the message sent by the HTTP In node to access the parameters.\n\nSee Node-RED cookbook [item](https://cookbook.nodered.org/http/handle-query-parameters) for details.", "x": 320, "y": 400, "wires": [] }, { "id": "77a6b44f.4695ac", "type": "inject", "z": "http_examples_tab", "name": "GET /hello-query?name=Nick を送る", "props": [ { "p": "payload" }, { "p": "topic", "vt": "str" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "", "payloadType": "date", "x": 240, "y": 540, "wires": [ [ "9094aba0.095678" ] ] }, { "id": "f523b8e.b5c8c48", "type": "debug", "z": "http_examples_tab", "name": "/hello-query の応答", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "false", "statusVal": "", "statusType": "auto", "x": 550, "y": 540, "wires": [] }, { "id": "9a63c9c5.949128", "type": "comment", "z": "http_examples_tab", "name": "Send HTTP GET request: http://localhost:1880/hello-query?name=Nick", "info": "`http request` node can be used to send **HTTP GET** request.", "x": 370, "y": 500, "wires": [] }, { "id": "d9c345c7.c2e148", "type": "template", "z": "http_examples_tab", "name": "ページ生成", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<html>\n <head></head>\n <body>\n <h1>Hello {{req.query.name}}!</h1>\n </body>\n</html>", "output": "str", "x": 410, "y": 440, "wires": [ [ "c110b7f7.22f238" ] ] }, { "id": "9094aba0.095678", "type": "http request", "z": "http_examples_tab", "name": "", "method": "GET", "ret": "txt", "paytoqs": "ignore", "url": "http://localhost:1880/hello-query?name=Nick", "tls": "", "persist": false, "proxy": "", "authType": "", "x": 390, "y": 540, "wires": [ [ "f523b8e.b5c8c48" ] ] }, { "id": "9b2d7459.8dd598", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-param/:name", "method": "get", "upload": false, "swaggerDoc": "", "x": 290, "y": 680, "wires": [ [ "83753c80.5e271" ] ] }, { "id": "7fe50f46.46209", "type": "http response", "z": "http_examples_tab", "name": "", "statusCode": "", "headers": {}, "x": 590, "y": 680, "wires": [] }, { "id": "6e88d2b.828a92c", "type": "comment", "z": "http_examples_tab", "name": "Handle URL parameters in an HTTP endpoint", "info": "Named path parameters (e.g. `:name`) in the URL property can be used to identify parts of the path that can vary between requests.\n\nThe `msg.req.params` property is an object of key/value pairs for each path parameter.", "x": 290, "y": 640, "wires": [] }, { "id": "214bc398.b3482c", "type": "http request", "z": "http_examples_tab", "name": "", "method": "GET", "ret": "txt", "paytoqs": "ignore", "url": "http://localhost:1880/hello-param/Nick", "tls": "", "persist": false, "proxy": "", "authType": "", "x": 390, "y": 780, "wires": [ [ "70c0eba4.5f0dc4" ] ] }, { "id": "70c0eba4.5f0dc4", "type": "debug", "z": "http_examples_tab", "name": "/hello-param の応答", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "false", "statusVal": "", "statusType": "auto", "x": 550, "y": 780, "wires": [] }, { "id": "83753c80.5e271", "type": "template", "z": "http_examples_tab", "name": "ページ生成", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<html>\n <head></head>\n <body>\n <h1>Hello {{req.params.name}}!</h1>\n </body>\n</html>", "output": "str", "x": 470, "y": 680, "wires": [ [ "7fe50f46.46209" ] ] }, { "id": "89523bfe.6e5c18", "type": "inject", "z": "http_examples_tab", "name": "GET /hello-param/Nick を送る", "props": [ { "p": "payload" }, { "p": "topic", "vt": "str" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "", "payloadType": "date", "x": 240, "y": 780, "wires": [ [ "214bc398.b3482c" ] ] }, { "id": "6276a6cd.5c3b18", "type": "comment", "z": "http_examples_tab", "name": "Send HTTP GET request: http://localhost:1880/hello-param/Nick", "info": "`http request` node can be used to send **HTTP GET** request.", "x": 350, "y": 740, "wires": [] }, { "id": "1ccc20e.71730df", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-headers", "method": "get", "upload": false, "swaggerDoc": "", "x": 270, "y": 920, "wires": [ [ "3a62f641.2c0e8a" ] ] }, { "id": "bc626348.1496d", "type": "http response", "z": "http_examples_tab", "name": "", "statusCode": "", "headers": {}, "x": 550, "y": 920, "wires": [] }, { "id": "b13b7c19.79cbd", "type": "comment", "z": "http_examples_tab", "name": "Access HTTP request headers", "info": " `msg.req.headers` property of the message sent by the `HTTP In` node to access the headers.\n\nSee Node-RED cookbook [item](https://cookbook.nodered.org/http/access-http-request-headers) for details.", "x": 240, "y": 880, "wires": [] }, { "id": "7fe0fee5.f3ed7", "type": "http request", "z": "http_examples_tab", "name": "", "method": "GET", "ret": "txt", "paytoqs": "ignore", "url": "http://localhost:1880/hello-headers", "tls": "", "persist": false, "proxy": "", "authType": "", "x": 390, "y": 1020, "wires": [ [ "65b13d57.700074" ] ] }, { "id": "65b13d57.700074", "type": "debug", "z": "http_examples_tab", "name": "/hello-headers の応答", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "false", "statusVal": "", "statusType": "auto", "x": 550, "y": 1020, "wires": [] }, { "id": "3a62f641.2c0e8a", "type": "template", "z": "http_examples_tab", "name": "ページ生成", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<html>\n <head></head>\n <body>\n <h1>User agent: {{req.headers.user-agent}}</h1>\n </body>\n</html>", "output": "str", "x": 430, "y": 920, "wires": [ [ "bc626348.1496d" ] ] }, { "id": "757fe655.e28558", "type": "inject", "z": "http_examples_tab", "name": "ヘッダー付きで GET /hello-headers を送る", "props": [ { "p": "payload" }, { "p": "headers", "v": "{\"User-Agent\":\"Node-RED\"}", "vt": "json" }, { "p": "topic", "vt": "str" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "", "payloadType": "date", "x": 240, "y": 1020, "wires": [ [ "7fe0fee5.f3ed7" ] ] }, { "id": "5195095.03b4cf8", "type": "comment", "z": "http_examples_tab", "name": "Set HTTP request header & send HTTP GET request: http://localhost:1880/hello-headers", "info": "The field value pairs of the request headers \nyou would like to include in the message sent to the `HTTP request` node can be specified by setting `the msg.headers` field.\n\nSee Node-RED cookbook [item](https://cookbook.nodered.org/http/set-request-header) for details.", "x": 430, "y": 980, "wires": [] }, { "id": "69a64e3d.84da3", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-raw", "method": "post", "upload": false, "swaggerDoc": "", "x": 260, "y": 1160, "wires": [ [ "38d357a7.b69d08" ] ] }, { "id": "43e49c36.dc7624", "type": "http response", "z": "http_examples_tab", "name": "", "statusCode": "", "headers": {}, "x": 530, "y": 1160, "wires": [] }, { "id": "8cb4b74e.602c28", "type": "comment", "z": "http_examples_tab", "name": "Post data to a flow", "info": "The `HTTP In` node can listen for POST requests. It returns the posted data as `msg.payload`.\n\nSee Node-RED cookbook items(\n[post raw data(https://cookbook.nodered.org/http/post-raw-data-to-a-flow), [post form data](https://cookbook.nodered.org/http/post-form-data-to-a-flow), [post JSON data](https://cookbook.nodered.org/http/post-json-data-to-a-flow)\n) for details.", "x": 210, "y": 1120, "wires": [] }, { "id": "ec661b6b.c3c2b8", "type": "http request", "z": "http_examples_tab", "name": "", "method": "POST", "ret": "txt", "paytoqs": "ignore", "url": "http://localhost:1880/hello-raw", "tls": "", "persist": false, "proxy": "", "authType": "", "x": 370, "y": 1260, "wires": [ [ "7c2812c.c6ee7ec" ] ] }, { "id": "7c2812c.c6ee7ec", "type": "debug", "z": "http_examples_tab", "name": "/hello-raw の応答", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "false", "statusVal": "", "statusType": "auto", "x": 530, "y": 1260, "wires": [] }, { "id": "38d357a7.b69d08", "type": "template", "z": "http_examples_tab", "name": "ページ生成", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<html>\n <head></head>\n <body>\n <h1>Hello {{payload}}</h1>\n </body>\n</html>", "output": "str", "x": 410, "y": 1160, "wires": [ [ "43e49c36.dc7624" ] ] }, { "id": "e45041b6.9ec13", "type": "inject", "z": "http_examples_tab", "name": "POST /hello-raw に Nick を送る", "props": [ { "p": "payload" }, { "p": "topic", "vt": "str" } ], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "Nick", "payloadType": "str", "x": 230, "y": 1260, "wires": [ [ "ec661b6b.c3c2b8" ] ] }, { "id": "af33dae7.b21138", "type": "comment", "z": "http_examples_tab", "name": "Send HTTP POST request: http://localhost:1880/hello-raw", "info": "", "x": 330, "y": 1220, "wires": [] }, { "id": "59760c9d.172d94", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-upload", "method": "post", "upload": true, "swaggerDoc": "", "x": 270, "y": 1580, "wires": [ [ "e30073f3.ad429" ] ] }, { "id": "d0b3e8b4.2cfde8", "type": "comment", "z": "http_examples_tab", "name": "Post file to a flow", "info": "The `HTTP In` node can listen for POST requests for file upload. Information for uploaded files can be accessed from `msg.req.files`.\n", "x": 200, "y": 1360, "wires": [] }, { "id": "a888a043.ebb72", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-upload", "method": "get", "upload": false, "swaggerDoc": "", "x": 270, "y": 1480, "wires": [ [ "14b950b.0ed5aaf" ] ] }, { "id": "2ccb67c7.02c568", "type": "http response", "z": "http_examples_tab", "name": "", "statusCode": "", "headers": {}, "x": 590, "y": 1480, "wires": [] }, { "id": "14b950b.0ed5aaf", "type": "template", "z": "http_examples_tab", "name": "", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<html>\n <head></head>\n <body>\n <form method=\"POST\" enctype=\"multipart/form-data\">\n <div>\n <label for=\"file\">Select file to upload:</label>\n <input type=\"file\" id=\"file\" name=\"file\"/>\n </div>\n <div>\n <button type=\"submit\">OK</button>\n </div>\n </form>\n </body>\n</html>", "output": "str", "x": 440, "y": 1480, "wires": [ [ "2ccb67c7.02c568" ] ] }, { "id": "54f2edb5.62fca4", "type": "http response", "z": "http_examples_tab", "name": "", "statusCode": "", "headers": {}, "x": 590, "y": 1580, "wires": [] }, { "id": "e30073f3.ad429", "type": "template", "z": "http_examples_tab", "name": "", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<html>\n <head></head>\n <body>\n <h1>Hello {{req.files.0.originalname}}</h1>\n </body>\n</html>", "output": "str", "x": 440, "y": 1580, "wires": [ [ "54f2edb5.62fca4" ] ] }, { "id": "6c3c1bf.48cc2e4", "type": "comment", "z": "http_examples_tab", "name": "Create HTTP page for file upload: open http://localhost:1880/hello-upload \\n from Web browser. Then upload a file.", "info": "", "x": 440, "y": 1420, "wires": [] }, { "id": "c6242caa.8ec63", "type": "comment", "z": "http_examples_tab", "name": "Serve POST request for file upload", "info": "", "x": 320, "y": 1540, "wires": [] }, { "id": "c362b989.954ae8", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-cookie", "method": "get", "swaggerDoc": "", "x": 250, "y": 1780, "wires": [ [ "21ddf71f.d00518" ] ] }, { "id": "21ddf71f.d00518", "type": "function", "z": "http_examples_tab", "name": "Cookieを整形", "func": "msg.payload = JSON.stringify(msg.req.cookies,null,4);\nreturn msg;", "outputs": 1, "noerr": 0, "x": 460, "y": 1780, "wires": [ [ "f3aa98c1.befc18" ] ] }, { "id": "f3aa98c1.befc18", "type": "template", "z": "http_examples_tab", "name": "ページ生成", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<html>\n <head></head>\n <body>\n <h1>Cookies</h1>\n <a href=\"hello-cookie/add\">Add a cookie</a><br/>\n <a href=\"hello-cookie/clear\">Clear cookies</a><br/>\n <pre>{{ payload }}</pre>\n </body>\n</html>", "output": "str", "x": 650, "y": 1780, "wires": [ [ "f52e2880.180968" ] ] }, { "id": "f52e2880.180968", "type": "http response", "z": "http_examples_tab", "name": "", "x": 870, "y": 1780, "wires": [] }, { "id": "9a2a9a4.0fc0768", "type": "change", "z": "http_examples_tab", "name": "/hello-cookie へリダイレクト", "rules": [ { "t": "set", "p": "statusCode", "pt": "msg", "to": "302", "tot": "num" }, { "t": "set", "p": "headers", "pt": "msg", "to": "{}", "tot": "json" }, { "t": "set", "p": "headers.location", "pt": "msg", "to": "/hello-cookie", "tot": "str" } ], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 670, "y": 1840, "wires": [ [ "f52e2880.180968" ] ] }, { "id": "afefb90.53dcf48", "type": "function", "z": "http_examples_tab", "name": "Cookieを追加", "func": "msg.cookies = { };\nmsg.cookies[\"demo-\"+(Math.floor(Math.random()*1000))] = Date.now();\nreturn msg;", "outputs": 1, "noerr": 0, "x": 450, "y": 1820, "wires": [ [ "9a2a9a4.0fc0768" ] ] }, { "id": "d5205a2c.db9018", "type": "function", "z": "http_examples_tab", "name": "Cookieを削除", "func": "// Find demo cookies and clear them\nvar cookieNames = Object.keys(msg.req.cookies).filter(function(cookieName) { return /^demo-/.test(cookieName);});\nmsg.cookies = {};\n\ncookieNames.forEach(function(cookieName) {\n msg.cookies[cookieName] = null;\n});\n\nreturn msg;", "outputs": 1, "noerr": 0, "x": 460, "y": 1860, "wires": [ [ "9a2a9a4.0fc0768" ] ] }, { "id": "fda60c66.04975", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-cookie/add", "method": "get", "swaggerDoc": "", "x": 260, "y": 1820, "wires": [ [ "afefb90.53dcf48" ] ] }, { "id": "35285a76.1f8636", "type": "http in", "z": "http_examples_tab", "name": "", "url": "/hello-cookie/clear", "method": "get", "swaggerDoc": "", "x": 260, "y": 1860, "wires": [ [ "d5205a2c.db9018" ] ] }, { "id": "cb094c2f.7e34d", "type": "comment", "z": "http_examples_tab", "name": "Working with cookies", "info": "The messages sent by the `HTTP In` node include the `msg.req.cookies` property that lists the cookies set on the current request.\n\nThe `HTTP Response` node will use the `msg.cookies` property in order to set or clear cookies.\n\nSee Node-RED cookbook [item](https://cookbook.nodered.org/http/work-with-cookies) for details.\n", "x": 220, "y": 1680, "wires": [] }, { "id": "287a9146.683afe", "type": "comment", "z": "http_examples_tab", "name": "Create HTTP page for testing cookies: open http://localhost:1880/hello-cookie from Web browser. ", "info": "", "x": 500, "y": 1740, "wires": [] } ]

動作確認方法

⚠️ 動作確認の前提: フローを読み込んで「デプロイ」ボタンをクリックした後に行ってください。デプロイ前はエンドポイントがまだ存在しないため、すべて失敗します。

例1〜5は「エンドポイント(http in → http response)」と「それを呼び出すテスト用フロー(inject → http request → debug)」のセットになっており、エディタ内とブラウザの両方で確認できます。例6・7はブラウザから直接確認します。

  1. 例1〜5: 各例の injectノードの左端のボタンをクリックすると、debugサイドバー(右パネルの虫アイコン)に、エンドポイントが返したレスポンス(HTMLやテキスト)が表示されます
  2. ブラウザでも確認できます: http://localhost:1880/hello、http://localhost:1880/hello-query?name=Taro、http://localhost:1880/hello-param/Taro、http://localhost:1880/hello-headers を開くと、フローが生成したページが表示されます
  3. 例6(ファイルアップロード): ブラウザで http://localhost:1880/hello-upload を開き、ファイルを選択して送信すると、受信結果が表示されます
  4. 例7(Cookie): ブラウザで http://localhost:1880/hello-cookie を開くと現在のCookie一覧が表示され、ページ内の「Add a cookie」「Clear cookies」リンクで追加・削除を試せます

🖥️ 本ガイドはローカル環境前提です: サンプルフローのHTTP Requestノードは http://localhost:1880/... へ接続する(自分自身のAPIを呼び出す)設定です。httpsで公開された共有クラウド環境では、この接続先が存在しないため公式サンプルは動作しません(同じループバック構成のwebsocketガイドで実測確認済み)。自分のPCにインストールしたNode-REDで学習してください(Windowsインストールガイド/Raspberry Piインストールガイド)。なお、Raspberry Pi上のNode-REDを別のPCのブラウザから操作している場合、ブラウザで開くURLの localhost はPiのアドレス(例: http://raspberrypi.local:1880)になります。フロー内部の http://localhost:1880/... はPi自身への接続なので、そのままで動きます。

応用(サイト独自): 実用パターン集

ここから先は公式サンプルではなく、本サイトが用意した応用教材です。JSONを返すAPI、flow変数へのデータ保存、外部API呼び出し(time.now の World Time API)、ステータスコードによるエラーハンドリング、セルフテストを1つのタブにまとめたもので、以下で説明する使用パターンの実例になっています。

📥 応用フローJSON(クリックで展開)
[ { "id": "http_sample_tab", "type": "tab", "label": "HTTP ノード サンプル", "disabled": false, "info": "" }, { "id": "http_comment1", "type": "comment", "z": "http_sample_tab", "name": "━━━ 基本: Hello World API ━━━", "info": "GET http://localhost:1880/api/hello", "x": 190, "y": 40, "wires": [] }, { "id": "http_in_hello", "type": "http in", "z": "http_sample_tab", "name": "GET /api/hello", "url": "/api/hello", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 160, "y": 100, "wires": [["http_change_hello"]] }, { "id": "http_change_hello", "type": "change", "z": "http_sample_tab", "name": "レスポンス設定", "rules": [ {"t": "set", "p": "payload", "pt": "msg", "to": "{\"message\":\"Hello from Node-RED!\",\"timestamp\":\"\"}", "tot": "json"}, {"t": "set", "p": "payload.timestamp", "pt": "msg", "to": "", "tot": "date"}, {"t": "set", "p": "headers", "pt": "msg", "to": "{\"Content-Type\":\"application/json\"}", "tot": "json"} ], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 380, "y": 100, "wires": [["http_response_hello", "http_debug_hello"]] }, { "id": "http_response_hello", "type": "http response", "z": "http_sample_tab", "name": "Response", "statusCode": "200", "headers": {}, "x": 580, "y": 100, "wires": [] }, { "id": "http_debug_hello", "type": "debug", "z": "http_sample_tab", "name": "リクエスト確認", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "\"リクエスト受信\"", "statusType": "jsonata", "x": 600, "y": 140, "wires": [] }, { "id": "http_comment2", "type": "comment", "z": "http_sample_tab", "name": "━━━ POST: データ受信API ━━━", "info": "POST http://localhost:1880/api/data", "x": 190, "y": 200, "wires": [] }, { "id": "http_in_post", "type": "http in", "z": "http_sample_tab", "name": "POST /api/data", "url": "/api/data", "method": "post", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 160, "y": 260, "wires": [["http_func_post"]] }, { "id": "http_func_post", "type": "function", "z": "http_sample_tab", "name": "データ処理", "func": "// 受信データを処理\nconst receivedData = msg.payload;\n\n// データを保存(flow変数)\nconst dataStore = flow.get('dataStore') || [];\ndataStore.push({\n id: Date.now(),\n data: receivedData,\n receivedAt: new Date().toISOString()\n});\nflow.set('dataStore', dataStore);\n\n// レスポンス作成\nmsg.payload = {\n success: true,\n message: \"データを受信しました\",\n received: receivedData,\n totalCount: dataStore.length\n};\nmsg.statusCode = 201;\nmsg.headers = {\"Content-Type\": \"application/json\"};\n\nreturn msg;", "outputs": 1, "timeout": 0, "initialize": "", "finalize": "", "libs": [], "x": 350, "y": 260, "wires": [["http_response_post", "http_debug_post"]] }, { "id": "http_response_post", "type": "http response", "z": "http_sample_tab", "name": "Response", "statusCode": "", "headers": {}, "x": 540, "y": 260, "wires": [] }, { "id": "http_debug_post", "type": "debug", "z": "http_sample_tab", "name": "受信データ", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "\"データ受信\"", "statusType": "jsonata", "x": 550, "y": 300, "wires": [] }, { "id": "http_comment3", "type": "comment", "z": "http_sample_tab", "name": "━━━ URLパラメータ: /users/:id ━━━", "info": "GET http://localhost:1880/api/users/1", "x": 200, "y": 360, "wires": [] }, { "id": "http_in_users", "type": "http in", "z": "http_sample_tab", "name": "GET /api/users/:id", "url": "/api/users/:id", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 170, "y": 420, "wires": [["http_func_users"]] }, { "id": "http_func_users", "type": "function", "z": "http_sample_tab", "name": "ユーザー検索", "func": "// URLパラメータからIDを取得\nconst userId = msg.req.params.id;\n\n// サンプルユーザーデータ\nconst users = {\n \"1\": {name: \"田中太郎\", email: \"tanaka@example.com\"},\n \"2\": {name: \"鈴木花子\", email: \"suzuki@example.com\"},\n \"3\": {name: \"佐藤次郎\", email: \"sato@example.com\"}\n};\n\n// ユーザー検索\nif (users[userId]) {\n msg.payload = {\n success: true,\n user: { id: userId, name: users[userId].name, email: users[userId].email }\n };\n msg.statusCode = 200;\n} else {\n msg.payload = {\n success: false,\n error: \"ユーザーが見つかりません\",\n requestedId: userId\n };\n msg.statusCode = 404;\n}\n\nmsg.headers = {\"Content-Type\": \"application/json\"};\nreturn msg;", "outputs": 1, "timeout": 0, "initialize": "", "finalize": "", "libs": [], "x": 380, "y": 420, "wires": [["http_response_users", "http_debug_users"]] }, { "id": "http_response_users", "type": "http response", "z": "http_sample_tab", "name": "Response", "statusCode": "", "headers": {}, "x": 580, "y": 420, "wires": [] }, { "id": "http_debug_users", "type": "debug", "z": "http_sample_tab", "name": "検索結果", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "req.params.id", "statusType": "msg", "x": 570, "y": 460, "wires": [] }, { "id": "http_comment4", "type": "comment", "z": "http_sample_tab", "name": "━━━ 外部API呼び出し ━━━", "info": "time.now の World Time API で時刻取得", "x": 180, "y": 520, "wires": [] }, { "id": "http_inject_api", "type": "inject", "z": "http_sample_tab", "name": "東京の時刻取得", "props": [], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "x": 160, "y": 580, "wires": [["http_request_time"]] }, { "id": "http_request_time", "type": "http request", "z": "http_sample_tab", "name": "time.now", "method": "GET", "ret": "obj", "paytoqs": "ignore", "url": "https://time.now/developer/api/time?timezone=Asia/Tokyo", "tls": "", "persist": false, "proxy": "", "insecureHTTPParser": false, "authType": "", "senderr": false, "headers": [], "x": 360, "y": 580, "wires": [["http_func_time"]] }, { "id": "http_func_time", "type": "function", "z": "http_sample_tab", "name": "時刻を整形", "func": "// APIレスポンス(JSONオブジェクト)\nconst data = msg.payload;\n\n// 時刻を取得できなかったとき(APIがエラーを返したなど)は、ここで止めて知らせる\nif (!data || typeof data.datetime !== 'string') {\n node.error('時刻を取得できませんでした(ステータスコード: ' + msg.statusCode + ')', msg);\n return null;\n}\n\n// datetime は \"2026-11-25T21:29:55.836985+09:00\" の形の文字列。\n// 日付(先頭の10文字)と時・分(12文字目からの5文字)を取り出して、読みやすい形にする\nconst formatted = data.datetime.slice(0, 10) + ' ' + data.datetime.slice(11, 16);\n\nmsg.payload = {\n timezone: data.timezone,\n datetime: data.datetime,\n formatted: formatted\n};\n\nreturn msg;", "outputs": 1, "timeout": 0, "initialize": "", "finalize": "", "libs": [], "x": 550, "y": 580, "wires": [["http_debug_time"]] }, { "id": "http_debug_time", "type": "debug", "z": "http_sample_tab", "name": "時刻表示", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "payload.formatted", "statusType": "msg", "x": 720, "y": 580, "wires": [] }, { "id": "http_comment5", "type": "comment", "z": "http_sample_tab", "name": "━━━ エラーハンドリング ━━━", "info": "ステータスコードで分岐", "x": 180, "y": 640, "wires": [] }, { "id": "http_inject_error", "type": "inject", "z": "http_sample_tab", "name": "404テスト", "props": [], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "x": 150, "y": 700, "wires": [["http_request_error"]] }, { "id": "http_request_error", "type": "http request", "z": "http_sample_tab", "name": "404エラーテスト", "method": "GET", "ret": "obj", "paytoqs": "ignore", "url": "https://postman-echo.com/status/404", "tls": "", "persist": false, "proxy": "", "insecureHTTPParser": false, "authType": "", "senderr": false, "headers": [], "x": 360, "y": 700, "wires": [["http_switch_status"]] }, { "id": "http_switch_status", "type": "switch", "z": "http_sample_tab", "name": "ステータス判定", "property": "statusCode", "propertyType": "msg", "rules": [ {"t": "btwn", "v": "200", "vt": "num", "v2": "299", "v2t": "num"}, {"t": "btwn", "v": "400", "vt": "num", "v2": "499", "v2t": "num"}, {"t": "gte", "v": "500", "vt": "num"} ], "checkall": "false", "repair": false, "outputs": 3, "x": 560, "y": 700, "wires": [["http_debug_success"], ["http_debug_client_err"], ["http_debug_server_err"]] }, { "id": "http_debug_success", "type": "debug", "z": "http_sample_tab", "name": "成功 (2xx)", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "statusCode", "targetType": "msg", "statusVal": "\"成功\"", "statusType": "jsonata", "x": 750, "y": 660, "wires": [] }, { "id": "http_debug_client_err", "type": "debug", "z": "http_sample_tab", "name": "クライアントエラー (4xx)", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "statusCode", "targetType": "msg", "statusVal": "\"クライアントエラー\"", "statusType": "jsonata", "x": 790, "y": 700, "wires": [] }, { "id": "http_debug_server_err", "type": "debug", "z": "http_sample_tab", "name": "サーバーエラー (5xx)", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "statusCode", "targetType": "msg", "statusVal": "\"サーバーエラー\"", "statusType": "jsonata", "x": 780, "y": 740, "wires": [] }, { "id": "http_comment6", "type": "comment", "z": "http_sample_tab", "name": "━━━ HTMLページ提供 ━━━", "info": "GET http://localhost:1880/page", "x": 180, "y": 800, "wires": [] }, { "id": "http_in_page", "type": "http in", "z": "http_sample_tab", "name": "GET /page", "url": "/page", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 140, "y": 860, "wires": [["http_in_change_html"]] }, { "id": "http_in_change_html", "type": "change", "z": "http_sample_tab", "name": "タイムスタンプ設定", "rules": [ {"t": "set", "p": "timestamp", "pt": "msg", "to": "$fromMillis($millis(), '[Y0001]-[M01]-[D01] [H01]:[m01]:[s01]', '+0900')", "tot": "jsonata"}, {"t": "set", "p": "headers", "pt": "msg", "to": "{\"Content-Type\":\"text/html; charset=utf-8\"}", "tot": "json"} ], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 330, "y": 860, "wires": [["http_in_template"]] }, { "id": "http_in_template", "type": "template", "z": "http_sample_tab", "name": "HTML生成", "field": "payload", "fieldType": "msg", "format": "html", "syntax": "mustache", "template": "<!DOCTYPE html>\n<html lang=\"ja\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Node-RED Page</title>\n <style>\n body { font-family: Arial, sans-serif; padding: 40px; background: #f0f0f0; }\n main { background: white; padding: 30px; border-radius: 10px; max-width: 600px; margin: 0 auto; }\n h1 { color: #b92d5d; }\n .info { background: #e8f5e9; padding: 15px; border-radius: 5px; }\n </style>\n</head>\n<body>\n <main>\n <h1>Node-RED Web Page</h1>\n <p>This page is dynamically generated by Node-RED.</p>\n <section class=\"info\">\n <p><strong>Current Time:</strong> {{timestamp}}</p>\n <p><strong>Request Host:</strong> {{req.headers.host}}</p>\n </section>\n </main>\n</body>\n</html>", "output": "str", "x": 530, "y": 860, "wires": [["http_response_page"]] }, { "id": "http_response_page", "type": "http response", "z": "http_sample_tab", "name": "Response", "statusCode": "200", "headers": {}, "x": 700, "y": 860, "wires": [] }, { "id": "http_comment7", "type": "comment", "z": "http_sample_tab", "name": "━━━ セルフテスト ━━━", "info": "HTTP Requestで自分のAPIを呼び出し", "x": 170, "y": 920, "wires": [] }, { "id": "http_inject_selftest", "type": "inject", "z": "http_sample_tab", "name": "APIテスト", "props": [], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "x": 140, "y": 980, "wires": [["http_request_selftest"]] }, { "id": "http_request_selftest", "type": "http request", "z": "http_sample_tab", "name": "自分のAPIを呼出", "method": "GET", "ret": "obj", "paytoqs": "ignore", "url": "http://localhost:1880/api/hello", "tls": "", "persist": false, "proxy": "", "insecureHTTPParser": false, "authType": "", "senderr": false, "headers": [], "x": 350, "y": 980, "wires": [["http_debug_selftest"]] }, { "id": "http_debug_selftest", "type": "debug", "z": "http_sample_tab", "name": "テスト結果", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "payload.message", "statusType": "msg", "x": 550, "y": 980, "wires": [] } ]

応用フローの動作確認

作成したAPIの動作確認方法:

応用フローをデプロイしたら、以下のいずれかの方法でHTTPリクエストを送って動作を確認できます。初心者の方は、まず「HTTP Request ノード」か「ブラウザ」から試すのがおすすめです。

💡 よく使うcurlオプション早見表:

オプション意味例
-XHTTPメソッドを指定(省略時は常にGET)-X POST / -X DELETE
-Hリクエストヘッダーを指定-H "Content-Type: application/json"
-d送信するデータ(ボディ)を指定-d '{"text":"hello"}'
-uBasic認証のユーザー名とパスワード-u ユーザー名:パスワード

※ Windows PowerShellを使う場合の注意: PowerShellでは curl という名前がPowerShell独自の別コマンド(Invoke-WebRequest)に割り当てられており、上記のオプションのままでは正しく動作しません。curl.exe と拡張子まで明示すると、本来のcurlコマンドを呼び出せます。また -d でJSONデータを渡す際は、内側の二重引用符を \" のようにエスケープしてください。例: curl.exe -X POST -H "Content-Type: application/json" -d '{\"sensor\":\"temp\",\"value\":25.3}' http://localhost:1880/api/data

パターン1: シンプルなGET API

GET /api/hello → レスポンス設定 → Response

用途: 固定データや状態を返すシンプルなエンドポイント

パターン2: POST でデータ受信

POST /api/data → データ処理 → Response

用途: センサーデータの受信、フォーム送信の処理

💡 テスト方法(重要): このパターンはPOST専用のため、ブラウザでURLを開いたり curl URL だけを実行したりするとGETリクエストになってしまい、「Cannot GET /api/data」のようなエラーになります。-X POST でメソッドを指定してください(オプションの詳細はcurlオプション早見表参照)。

curl -X POST -H "Content-Type: application/json" -d '{"sensor":"temp","value":25.4}' http://localhost:1880/api/data

パターン3: 外部API呼び出し

トリガー → HTTP Request → データ整形 → 結果表示

用途: 外部APIからのデータ取得、Webhook 連携

パターン4: エラーハンドリング

リクエスト → API呼出 → ステータス判定 →成功 (2xx) →クライアントエラー (4xx) →サーバーエラー (5xx)

用途: msg.statusCode でHTTPステータスを確認し、エラー時の処理を分岐

パターン5: HTMLページの提供

GET /page → タイムスタンプ設定 → HTML生成 → Response

用途: 動的なWebページ、ダッシュボード

注意: テンプレート内の {{timestamp}} は template ノードが実行された時点の値に置き換わります。値をセットする change ノードは、必ず template ノードより前に置いてください。順序を逆にすると、その項目は空欄で出力されます。

6. 演習問題

演習1: シンプルなJSON API 初級

課題: GET /api/status でシステムの状態を返すAPIを作成してください。

💼 使いどころ: APIに外部から到達できるかを確認する、簡単な死活確認に使います。

作る範囲:

利用者
ブラウザ や curl
(既にあるもの)
これを作る
Node-RED
サーバー側
リクエストを受けて
状態を返す

要求仕様:

成功の条件:

💡 ヒント

HTTP In ノード:

  • メソッド:GET
  • URL:/api/status

Change ノード:

  • msg.payload に JSONオブジェクトを設定
  • msg.headers に Content-Type を設定

HTTP Response ノード: デフォルト設定でOK

✅ 解答例フロー
[ {"id": "ex1_tab", "type": "tab", "label": "演習1"}, {"id": "ex1_http_in", "type": "http in", "z": "ex1_tab", "name": "GET /api/status", "url": "/api/status", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 170, "y": 100, "wires": [["ex1_change"]]}, {"id": "ex1_change", "type": "change", "z": "ex1_tab", "name": "レスポンス設定", "rules": [{"t": "set", "p": "payload", "pt": "msg", "to": "{\"status\":\"running\",\"version\":\"1.0.0\"}", "tot": "json"}, {"t": "set", "p": "headers", "pt": "msg", "to": "{\"Content-Type\":\"application/json\"}", "tot": "json"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 390, "y": 100, "wires": [["ex1_response"]]}, {"id": "ex1_response", "type": "http response", "z": "ex1_tab", "name": "Response", "statusCode": "200", "headers": {}, "x": 580, "y": 100, "wires": []} ]

演習2: 外部APIからデータ取得 初級

課題: time.now の World Time API を使って、ニューヨークの現在時刻を取得し、Debugノードに表示してください。

💼 使いどころ: 天気・為替・時刻など、外部サービスの情報を取り込んで自分の処理に使う場面で使います。

作る範囲:

これを作る
Node-RED
クライアント側
手動のトリガーで
外部APIを呼ぶ
time.now
外部サービス
(既にあるもの)

要求仕様:

成功の条件:

💡 ヒント

Inject ノード: デフォルト設定でOK(タイムスタンプを送信)

HTTP Request ノード:

  • メソッド:GET
  • URL:上記URLを入力
  • 出力形式:JSONオブジェクト

Debug ノード: msg.payload全体を表示

✅ 解答例フロー
[ {"id": "ex2_tab", "type": "tab", "label": "演習2"}, {"id": "ex2_inject", "type": "inject", "z": "ex2_tab", "name": "NY時刻取得", "props": [], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "x": 150, "y": 100, "wires": [["ex2_http"]]}, {"id": "ex2_http", "type": "http request", "z": "ex2_tab", "name": "time.now", "method": "GET", "ret": "obj", "paytoqs": "ignore", "url": "https://time.now/developer/api/time?timezone=America/New_York", "tls": "", "persist": false, "proxy": "", "insecureHTTPParser": false, "authType": "", "senderr": false, "headers": [], "x": 360, "y": 100, "wires": [["ex2_debug"]]}, {"id": "ex2_debug", "type": "debug", "z": "ex2_tab", "name": "NY時刻", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "payload.datetime", "statusType": "msg", "x": 550, "y": 100, "wires": []} ]

演習3: POSTで送られたデータを受け取る 初級

課題: POST /api/echo で受け取ったJSONに、受信時刻を添えて返すAPIを作成してください。

💼 使いどころ: センサーやフォームから送られたデータを受け取り、記録や通知につなげる場面で使います。

作る範囲:

利用者
curl
(既にあるもの)
これを作る
Node-RED
サーバー側
本文を受け取って
応答を組み立てる

要求仕様:

成功の条件:

💡 ヒント

HTTP In ノード:

  • メソッド:POST
  • URL:/api/echo

リクエストボディの受け取り: Content-Type が application/json であれば、HTTP In が本文をパースして msg.payload にオブジェクトとして入れます。Functionノードでの追加のパースは不要です。

Change ノード: 次の2つのルールを上から順に並べます。

  1. 「値の移動」: msg.payload → msg.payload.received(受け取った内容を received の中へ移す)
  2. 「値の代入」: msg.payload.receivedAt に「日時」型の YYYY-MM-DDTHH:mm:ss.sssZ(ISO 8601形式)を設定する

Content-Type: msg.payload がオブジェクトのまま HTTP Response に届くと、HTTP Response が JSON に変換し、Content-Type も application/json にします。自分で設定する必要はありません。

✅ 解答例フロー
[ {"id": "ex3_tab", "type": "tab", "label": "演習3"}, {"id": "ex3_http_in", "type": "http in", "z": "ex3_tab", "name": "POST /api/echo", "url": "/api/echo", "method": "post", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 170, "y": 100, "wires": [["ex3_change"]]}, {"id": "ex3_change", "type": "change", "z": "ex3_tab", "name": "受信内容を組み立て", "rules": [{"t": "move", "p": "payload", "pt": "msg", "to": "payload.received", "tot": "msg"}, {"t": "set", "p": "payload.receivedAt", "pt": "msg", "to": "iso", "tot": "date"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 400, "y": 100, "wires": [["ex3_response"]]}, {"id": "ex3_response", "type": "http response", "z": "ex3_tab", "name": "Response", "statusCode": "", "headers": {}, "x": 590, "y": 100, "wires": []} ]

演習4: URLパラメータを使ったAPI 中級

課題: GET /api/items/:id で商品情報を返すAPIを作成してください。

💼 使いどころ: 機器IDや商品コードなど、対象を指定して個別の情報を返す場面で使います。

作る範囲:

利用者
ブラウザ や curl
(既にあるもの)
これを作る
Node-RED
サーバー側
IDで商品を探して
見つからなければ404を返す

要求仕様:

成功の条件:

💡 ヒント

URLパラメータの取得: msg.req.params.id

商品を探す(Change ノード):

  1. 「値の代入」で msg.items に「JSON」型の商品表を入れる。キーを商品ID("1" など)にしておく
  2. 「値の代入」で msg.item に「JSONata式」型の $lookup(items, req.params.id) を入れる。商品表から、URLのIDをキーにして1件を取り出す式で、見つからなければ何も入らない

見つかったかで分ける(Switch ノード): プロパティを msg.item にし、「nullでない」と「その他」の2つのルールで出力を分ける。

応答を作る(Change ノードを2つ): 見つかった側は msg.payload を組み立てる。見つからなかった側は、加えて msg.statusCode に「数値」の 404 を入れる。msg.statusCode を入れなければ 200 で返る。2つの出力は、同じ HTTP Response ノードにつなげてよい。

✅ 解答例フロー
[ {"id": "ex4_tab", "type": "tab", "label": "演習4"}, {"id": "ex4_http_in", "type": "http in", "z": "ex4_tab", "name": "GET /api/items/:id", "url": "/api/items/:id", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 180, "y": 100, "wires": [["ex4_change_find"]]}, {"id": "ex4_change_find", "type": "change", "z": "ex4_tab", "name": "IDで商品を探す", "rules": [{"t": "set", "p": "items", "pt": "msg", "to": "{\"1\": {\"id\": \"1\", \"name\": \"りんご\", \"price\": 150}, \"2\": {\"id\": \"2\", \"name\": \"みかん\", \"price\": 100}, \"3\": {\"id\": \"3\", \"name\": \"バナナ\", \"price\": 120}}", "tot": "json"}, {"t": "set", "p": "item", "pt": "msg", "to": "$lookup(items, req.params.id)", "tot": "jsonata"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 400, "y": 100, "wires": [["ex4_switch"]]}, {"id": "ex4_switch", "type": "switch", "z": "ex4_tab", "name": "見つかった?", "property": "item", "propertyType": "msg", "rules": [{"t": "nnull"}, {"t": "else"}], "checkall": "true", "repair": false, "outputs": 2, "x": 570, "y": 100, "wires": [["ex4_change_found"], ["ex4_change_notfound"]]}, {"id": "ex4_change_found", "type": "change", "z": "ex4_tab", "name": "200: 商品情報", "rules": [{"t": "set", "p": "payload", "pt": "msg", "to": "{\"success\":true}", "tot": "json"}, {"t": "move", "p": "item", "pt": "msg", "to": "payload.item", "tot": "msg"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 760, "y": 60, "wires": [["ex4_response"]]}, {"id": "ex4_change_notfound", "type": "change", "z": "ex4_tab", "name": "404: 見つからない", "rules": [{"t": "set", "p": "payload", "pt": "msg", "to": "{\"success\":false,\"error\":\"商品が見つかりません\"}", "tot": "json"}, {"t": "set", "p": "payload.requestedId", "pt": "msg", "to": "req.params.id", "tot": "msg"}, {"t": "set", "p": "statusCode", "pt": "msg", "to": "404", "tot": "num"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 760, "y": 140, "wires": [["ex4_response"]]}, {"id": "ex4_response", "type": "http response", "z": "ex4_tab", "name": "Response", "statusCode": "", "headers": {}, "x": 980, "y": 100, "wires": []} ]

演習5: 外部APIを自作APIで包む 中級

課題: GET /api/tokyo-time にアクセスすると、外部API(time.now の World Time API)から東京の現在時刻を取得し、必要な項目だけに絞って返すAPIを作成してください。この演習では、Node-RED が利用者に対してはサーバー役、time.now に対してはクライアント役という、2つの役割を同時に担います。

💼 使いどころ: 外部APIの応答を必要な項目だけに整え、自分のシステム向けのAPIとして提供する場面で使います。外部APIの応答には、利用者に渡す必要のない項目が混ざっていることがあります。この API の応答には client_ip(API を呼び出した側、つまり Node-RED が動いている回線のIPアドレス)が入っているので、そのまま返すと自分の回線のIPアドレスを利用者に見せることになります。

作る範囲:

利用者
ブラウザ や curl
(既にあるもの)
これを作る
Node-RED
サーバー側 と クライアント側
受けたリクエストをきっかけに
自分が外部APIを呼ぶ
time.now
外部サービス
(既にあるもの)

要求仕様:

成功の条件:

💡 ヒント

フローの並び: HTTP In と HTTP Response の間に HTTP Request を挟みます。

HTTP Request ノード: メソッドはGET、URLは上記の外部API、出力形式は「JSONオブジェクト」。

上書きされる msg: HTTP Request ノードは msg.payload だけでなく msg.statusCode と msg.headers も外部APIの応答で上書きします。一方 msg.req と msg.res は残るため、後段の HTTP Response ノードは元のリクエストに応答できます。

4項目だけ残す(Change ノード): 外部APIの応答を一度 msg.api へ「値の移動」で退避し、msg.payload.timezone などに msg.api.timezone などを「値の代入」で1つずつ入れます。最後に「値の削除」で msg.api を消します。

ヘッダーの扱い: msg.headers には外部APIの応答ヘッダーが入っていますが、変更せずに HTTP Response へ渡せば、HTTP Response はそれをクライアントへ返しません(HTTP Request が付けた目印で、変更されていないことを判定します)。msg.payload がオブジェクトなら、Content-Type は application/json になります。反対に、msg.headers にプロパティを1つ足すなど一部だけ変更すると、外部APIのヘッダーもまとめて返り、Content-Type が意図しない値になります。Content-Type を自分で指定したいときは、msg.headers を丸ごと置き換えてください。

外部APIが応答しない場合: 分岐のさせ方はパターン4(エラーハンドリング)を参照してください。

✅ 解答例フロー
[ {"id": "ex5_tab", "type": "tab", "label": "演習5"}, {"id": "ex5_http_in", "type": "http in", "z": "ex5_tab", "name": "GET /api/tokyo-time", "url": "/api/tokyo-time", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 180, "y": 100, "wires": [["ex5_request"]]}, {"id": "ex5_request", "type": "http request", "z": "ex5_tab", "name": "time.now", "method": "GET", "ret": "obj", "paytoqs": "ignore", "url": "https://time.now/developer/api/time?timezone=Asia/Tokyo", "tls": "", "persist": false, "proxy": "", "insecureHTTPParser": false, "authType": "", "senderr": false, "headers": [], "x": 410, "y": 100, "wires": [["ex5_change"]]}, {"id": "ex5_change", "type": "change", "z": "ex5_tab", "name": "必要な項目だけ残す", "rules": [{"t": "move", "p": "payload", "pt": "msg", "to": "api", "tot": "msg"}, {"t": "set", "p": "payload.timezone", "pt": "msg", "to": "api.timezone", "tot": "msg"}, {"t": "set", "p": "payload.datetime", "pt": "msg", "to": "api.datetime", "tot": "msg"}, {"t": "set", "p": "payload.utc_offset", "pt": "msg", "to": "api.utc_offset", "tot": "msg"}, {"t": "set", "p": "payload.abbreviation", "pt": "msg", "to": "api.abbreviation", "tot": "msg"}, {"t": "delete", "p": "api", "pt": "msg"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 630, "y": 100, "wires": [["ex5_response"]]}, {"id": "ex5_response", "type": "http response", "z": "ex5_tab", "name": "Response", "statusCode": "", "headers": {}, "x": 820, "y": 100, "wires": []} ]

演習6: CRUD APIの作成 上級

💡 CRUDとは: データ操作の基本4種類 Create(作成)・Read(読み取り)・Update(更新)・Delete(削除)の頭文字です。この演習では、それぞれをHTTPメソッドの POST(作成)・GET(読み取り)・DELETE(削除)に対応させます。

課題: メモを管理するシンプルなREST API(GET/POST/DELETEなどのHTTPメソッドで操作する、一般的なWeb APIの設計スタイル)を作成してください。

💼 使いどころ: 設定値や登録データを、追加・参照・削除できる形で管理する場面で使います。

作る範囲:

利用者
curl
(既にあるもの)
これを作る
Node-RED
サーバー側
メモの保管も
Node-REDの中で行う

要求仕様:

成功の条件:

💡 ヒント

データ保存: flow.set('notes', notesArray)

データ取得: flow.get('notes') || []

新規ID生成: Date.now()

削除: array.filter() で該当IDを除外

この演習は、配列の検索・追加・削除を4つのエンドポイントで行うため、解答例は Function ノードで書いています。処理の意味はコード内のコメントで説明しています。

✅ 解答例フロー
[ {"id": "ex6_tab", "type": "tab", "label": "演習6"}, {"id": "ex6_get_all", "type": "http in", "z": "ex6_tab", "name": "GET /api/notes", "url": "/api/notes", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 160, "y": 80, "wires": [["ex6_func_get_all"]]}, {"id": "ex6_func_get_all", "type": "function", "z": "ex6_tab", "name": "全件取得", "func": "// flow変数からメモ一覧を読み出す(まだ1件も無ければ空の配列)\nconst notes = flow.get('notes') || [];\n// 一覧と件数を返す\nmsg.payload = {notes: notes, count: notes.length};\nreturn msg;", "outputs": 1, "timeout": 0, "initialize": "", "finalize": "", "libs": [], "x": 370, "y": 80, "wires": [["ex6_response"]]}, {"id": "ex6_post", "type": "http in", "z": "ex6_tab", "name": "POST /api/notes", "url": "/api/notes", "method": "post", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 170, "y": 140, "wires": [["ex6_func_post"]]}, {"id": "ex6_func_post", "type": "function", "z": "ex6_tab", "name": "新規作成", "func": "// 保存済みのメモ一覧を読み出す(まだ無ければ空の配列)\nconst notes = flow.get('notes') || [];\n// リクエスト本文(JSON)。本文が無いときは空のオブジェクトとして扱う\nconst body = msg.payload || {};\n// 新しいメモを作る。IDには現在時刻のミリ秒を使う(学習用の簡易的な採番)\nconst newNote = {\n id: Date.now(),\n text: body.text || \"(内容なし)\",\n createdAt: new Date().toISOString()\n};\n// 一覧に追加して、flow変数へ書き戻す\nnotes.push(newNote);\nflow.set('notes', notes);\n// 作成したメモを返す。201 は「作成した」を表すステータスコード\nmsg.payload = {success: true, note: newNote};\nmsg.statusCode = 201;\nreturn msg;", "outputs": 1, "timeout": 0, "initialize": "", "finalize": "", "libs": [], "x": 370, "y": 140, "wires": [["ex6_response"]]}, {"id": "ex6_get_one", "type": "http in", "z": "ex6_tab", "name": "GET /api/notes/:id", "url": "/api/notes/:id", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 180, "y": 200, "wires": [["ex6_func_get_one"]]}, {"id": "ex6_func_get_one", "type": "function", "z": "ex6_tab", "name": "1件取得", "func": "const notes = flow.get('notes') || [];\n// URLの :id は文字列で届くので、数値に変換してから比べる\nconst noteId = parseInt(msg.req.params.id);\n// IDが一致するメモを探す(見つからなければ undefined)\nconst note = notes.find(function(n) { return n.id === noteId; });\nif (note) {\n // 見つかった: 200 で返す\n msg.payload = {success: true, note: note};\n msg.statusCode = 200;\n} else {\n // 見つからない: 404 で返す\n msg.payload = {success: false, error: \"Not found\"};\n msg.statusCode = 404;\n}\nreturn msg;", "outputs": 1, "timeout": 0, "initialize": "", "finalize": "", "libs": [], "x": 370, "y": 200, "wires": [["ex6_response"]]}, {"id": "ex6_delete", "type": "http in", "z": "ex6_tab", "name": "DELETE /api/notes/:id", "url": "/api/notes/:id", "method": "delete", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 190, "y": 260, "wires": [["ex6_func_delete"]]}, {"id": "ex6_func_delete", "type": "function", "z": "ex6_tab", "name": "削除", "func": "// filter で作り直した配列を代入し直すため、const ではなく let\nlet notes = flow.get('notes') || [];\n// URLの :id は文字列で届くので、数値に変換してから比べる\nconst noteId = parseInt(msg.req.params.id);\n// 削除前の件数を覚えておき、減ったかどうかで削除できたかを判定する\nconst originalLength = notes.length;\n// 指定IDのメモを除いた配列を作り、flow変数へ書き戻す\nnotes = notes.filter(function(n) { return n.id !== noteId; });\nflow.set('notes', notes);\nif (notes.length < originalLength) {\n // 1件減った: 削除できた\n msg.payload = {success: true, message: \"Deleted\"};\n msg.statusCode = 200;\n} else {\n // 減っていない: そのIDのメモは無かった\n msg.payload = {success: false, error: \"Not found\"};\n msg.statusCode = 404;\n}\nreturn msg;", "outputs": 1, "timeout": 0, "initialize": "", "finalize": "", "libs": [], "x": 370, "y": 260, "wires": [["ex6_response"]]}, {"id": "ex6_response", "type": "http response", "z": "ex6_tab", "name": "Response", "statusCode": "", "headers": {}, "x": 560, "y": 160, "wires": []} ]

演習7: 2人でAPIをつなぐ(社内LAN) 上級

課題: 2人1組になり、片方がサーバー側、もう片方がクライアント側を作って、社内LAN越しに通信してください。ここまでの演習は1台のNode-REDの中で完結していましたが、この演習では相手のNode-REDへ実際にネットワークを越えてリクエストを送ります。

💼 使いどころ: 別の機器やシステムが公開しているAPIを呼び出して連携する場面で使います。

作る範囲:

Bさんが作る
Bさんの Node-RED
クライアント側
相手のIPアドレスを指定して
APIを呼ぶ
Aさんが作る
Aさんの Node-RED
サーバー側
/api/hello を公開して
自分の名前と時刻を返す

要求仕様:

成功の条件:

注意: この演習で作るエンドポイントには認証をかけていません。IPアドレスとURLを知っていれば、同じLANにいる誰でも呼び出せます。社内LANでの学習に限って行い、インターネットへ公開しないでください。
💡 ヒント

自分のIPアドレスの調べ方: Windows は ipconfig の「IPv4 アドレス」、ラズパイ・Linux は hostname -I。Mac の hostname には -I が無いため、「システム設定」の「ネットワーク」で、使っている接続(Wi-Fi など)の「詳細」を開き、「TCP/IP」の「IPアドレス」を見ます。詳しくはローカル/ラズパイ演習ガイドの共通の準備を参照してください。

待ち受けの設定は不要: Node-RED は既定ですべてのIPv4インターフェイスで待ち受けます(uiHost の既定値が 0.0.0.0)。そのため設定変更なしで他のPCから接続できます。ただし settings.js で uiHost: "127.0.0.1" を有効にしている場合は、同じPCからしか接続できません。

ファイアウォール: Windows では Defender ファイアウォールが受信をブロックすることがあります。初回接続時の許可ダイアログで許可するか、1880番の受信を許可してください(Windows編)。

つながらないときの切り分け順:

  1. Aさん自身が curl http://localhost:1880/api/hello で応答を得られるか。得られなければフロー側の問題(デプロイ忘れ、URLのつづり、メソッド違い)。
  2. BさんのブラウザでAさんのエディター http://(AさんのIP):1880/ が開けるか。開けなければネットワークかファイアウォールの問題。
  3. エディターは開けるのにAPIだけ失敗するなら、URLのつづりかメソッドの不一致を疑う。
✅ 解答例フロー(サーバー担当・Aさん)

「応答を作る」Change ノードの1つ目のルールにある "Aさん" を、自分の名前に書き換えてください。

[ {"id": "ex7s_tab", "type": "tab", "label": "演習7 サーバー側"}, {"id": "ex7s_http_in", "type": "http in", "z": "ex7s_tab", "name": "GET /api/hello", "url": "/api/hello", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 180, "y": 100, "wires": [["ex7s_change"]]}, {"id": "ex7s_change", "type": "change", "z": "ex7s_tab", "name": "応答を作る", "rules": [{"t": "set", "p": "payload", "pt": "msg", "to": "{\"from\":\"Aさん\"}", "tot": "json"}, {"t": "set", "p": "payload.time", "pt": "msg", "to": "iso", "tot": "date"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 400, "y": 100, "wires": [["ex7s_response"]]}, {"id": "ex7s_response", "type": "http response", "z": "ex7s_tab", "name": "Response", "statusCode": "", "headers": {}, "x": 590, "y": 100, "wires": []} ]
✅ 解答例フロー(クライアント担当・Bさん)

HTTP Request ノードのURLは、Aさんから聞いたIPアドレスに書き換えてください(下の例は 192.168.1.10)。

[ {"id": "ex7c_tab", "type": "tab", "label": "演習7 クライアント側"}, {"id": "ex7c_inject", "type": "inject", "z": "ex7c_tab", "name": "呼び出す", "props": [], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "x": 160, "y": 100, "wires": [["ex7c_request"]]}, {"id": "ex7c_request", "type": "http request", "z": "ex7c_tab", "name": "相手のNode-RED", "method": "GET", "ret": "obj", "paytoqs": "ignore", "url": "http://192.168.1.10:1880/api/hello", "tls": "", "persist": false, "proxy": "", "insecureHTTPParser": false, "authType": "", "senderr": false, "headers": [], "x": 380, "y": 100, "wires": [["ex7c_debug"]]}, {"id": "ex7c_debug", "type": "debug", "z": "ex7c_tab", "name": "相手の応答", "active": true, "tosidebar": true, "console": false, "tostatus": true, "complete": "payload", "targetType": "msg", "statusVal": "payload.from", "statusType": "msg", "x": 580, "y": 100, "wires": []} ]

演習8: 全員のAPIを巡回して一覧にする(社内LAN) 上級

課題: 受講者全員が同じ仕様のAPIを公開し、集約役の1人が全員分を順に呼び出して1つの一覧にまとめてください。演習7を人数分に広げたもので、全員が同じ仕様で作ることの意味を体験します。

💼 使いどころ: 複数の機器やシステムから同じ形式の情報を集め、1つの一覧にまとめる場面で使います。

作る範囲:

集約役が作る
集約役の Node-RED
クライアント側
全員のIPアドレスを
順に呼んで1つにまとめる
受講者全員が作る
受講者全員の Node-RED
サーバー側
全員が同じ仕様で
/api/whoami を公開する

要求仕様:

成功の条件:

注意: 演習7と同じく、このエンドポイントには認証をかけていません。社内LANでの学習に限って行い、インターネットへ公開しないでください。返す内容にも、名前以外の個人情報を入れないようにします。
💡 ヒント

IPアドレスの一覧をどこに持つか: Injectノードの payload に配列として書くのが手軽です。人数が変わったらここだけ直します。

1件ずつ呼び出すには: 配列を split ノードで1件ずつに分けます。HTTP Request ノードはURL欄を空にしておくと msg.url の値を使うので、split の後で msg.url を組み立てます(動的なURL設定を参照)。解答例では template ノードの出力先を msg.url にし、http://{{targetIp}}:1880/api/whoami のように組み立てています。

結果をまとめるには: join ノードを「自動モード」にすると、split が付けた msg.parts を見て自動で配列へ戻します。split と join を対で使うのが定石です。

呼び出し先のIPを結果に残すには: HTTP Request ノードは msg.payload を応答で上書きします。IPアドレスは msg.payload 以外のプロパティ(たとえば msg.targetIp)へ退避してから呼び出してください。

応答しない相手の扱い: HTTP Request ノードは既定で、接続できなかった場合もメッセージを下流へ流します。そのとき msg.payload にはエラー文が、msg.statusCode には ECONNREFUSED のような文字列が入ります。デバッグサイドバーには赤いエラーも出ますが、フローは止まりません。

成功と失敗の分け方: 解答例では switch ノードを2つ続けています。1つ目で msg.statusCode が数値の200かどうかを見ます(接続できなかったときは ECONNREFUSED のような文字列なので、「その他」へ流れます)。2つ目で、成功した応答にだけ含まれる msg.payload.name が「nullでない」かを見ます。相手が想定と違う内容を返したときに、成功として扱わないためです。どちらかの「その他」に流れたものは、失敗として扱います。失敗の側も必ず join ノードへつないでください。1件でも途中で止まると、join は人数分そろうのを待ち続け、一覧が表示されません。

待ち時間: 応答がない相手は、既定で120秒待ってから打ち切られます(settings.js の httpRequestTimeout で変更できます)。人数が多くて待ち時間が気になるときは、呼び出し前に msg.requestTimeout(ミリ秒)を設定すると短くできます。

✅ 解答例フロー(受講者全員・サーバー側)

全員がこれを読み込み、「自分の名前を返す」Change ノードにある "山田" だけを自分の名前に書き換えます。

[ {"id": "ex8s_tab", "type": "tab", "label": "演習8 サーバー側"}, {"id": "ex8s_http_in", "type": "http in", "z": "ex8s_tab", "name": "GET /api/whoami", "url": "/api/whoami", "method": "get", "upload": false, "skipBodyParsing": false, "swaggerDoc": "", "x": 180, "y": 100, "wires": [["ex8s_change"]]}, {"id": "ex8s_change", "type": "change", "z": "ex8s_tab", "name": "自分の名前を返す", "rules": [{"t": "set", "p": "payload", "pt": "msg", "to": "{\"name\":\"山田\"}", "tot": "json"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 400, "y": 100, "wires": [["ex8s_response"]]}, {"id": "ex8s_response", "type": "http response", "z": "ex8s_tab", "name": "Response", "statusCode": "", "headers": {}, "x": 590, "y": 100, "wires": []} ]
✅ 解答例フロー(集約役)

Injectノードの中にあるIPアドレスの配列を、実際の受講者のものへ書き換えてください。

[ {"id": "ex8c_tab", "type": "tab", "label": "演習8 集約役"}, {"id": "ex8c_inject", "type": "inject", "z": "ex8c_tab", "name": "全員のIP一覧", "props": [{"p": "payload"}], "repeat": "", "crontab": "", "once": false, "onceDelay": 0.1, "topic": "", "payload": "[\"192.168.1.11\",\"192.168.1.12\",\"192.168.1.13\"]", "payloadType": "json", "x": 160, "y": 100, "wires": [["ex8c_split"]]}, {"id": "ex8c_split", "type": "split", "z": "ex8c_tab", "name": "1件ずつに分ける", "splt": "\\n", "spltType": "str", "arraySplt": 1, "arraySpltType": "len", "stream": false, "addname": "", "property": "payload", "x": 350, "y": 100, "wires": [["ex8c_save"]]}, {"id": "ex8c_save", "type": "change", "z": "ex8c_tab", "name": "IPを退避", "rules": [{"t": "move", "p": "payload", "pt": "msg", "to": "targetIp", "tot": "msg"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 530, "y": 100, "wires": [["ex8c_url"]]}, {"id": "ex8c_url", "type": "template", "z": "ex8c_tab", "name": "URLを組み立てる", "field": "url", "fieldType": "msg", "format": "handlebars", "syntax": "mustache", "template": "http://{{targetIp}}:1880/api/whoami", "output": "str", "x": 710, "y": 100, "wires": [["ex8c_request"]]}, {"id": "ex8c_request", "type": "http request", "z": "ex8c_tab", "name": "相手を呼ぶ", "method": "GET", "ret": "obj", "paytoqs": "ignore", "url": "", "tls": "", "persist": false, "proxy": "", "insecureHTTPParser": false, "authType": "", "senderr": false, "headers": [], "x": 900, "y": 100, "wires": [["ex8c_switch_status"]]}, {"id": "ex8c_switch_status", "type": "switch", "z": "ex8c_tab", "name": "200が返ってきた?", "property": "statusCode", "propertyType": "msg", "rules": [{"t": "eq", "v": "200", "vt": "num"}, {"t": "else"}], "checkall": "true", "repair": false, "outputs": 2, "x": 180, "y": 200, "wires": [["ex8c_switch"], ["ex8c_ng"]]}, {"id": "ex8c_switch", "type": "switch", "z": "ex8c_tab", "name": "名前が返ってきた?", "property": "payload.name", "propertyType": "msg", "rules": [{"t": "nnull"}, {"t": "else"}], "checkall": "true", "repair": false, "outputs": 2, "x": 370, "y": 200, "wires": [["ex8c_ok"], ["ex8c_ng"]]}, {"id": "ex8c_ok", "type": "change", "z": "ex8c_tab", "name": "成功: ipとnameにする", "rules": [{"t": "move", "p": "payload", "pt": "msg", "to": "reply", "tot": "msg"}, {"t": "set", "p": "payload.ip", "pt": "msg", "to": "targetIp", "tot": "msg"}, {"t": "set", "p": "payload.name", "pt": "msg", "to": "reply.name", "tot": "msg"}, {"t": "delete", "p": "reply", "pt": "msg"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 580, "y": 170, "wires": [["ex8c_join"]]}, {"id": "ex8c_ng", "type": "change", "z": "ex8c_tab", "name": "失敗: errorにする", "rules": [{"t": "move", "p": "payload", "pt": "msg", "to": "errorText", "tot": "msg"}, {"t": "set", "p": "payload.ip", "pt": "msg", "to": "targetIp", "tot": "msg"}, {"t": "move", "p": "errorText", "pt": "msg", "to": "payload.error", "tot": "msg"}], "action": "", "property": "", "from": "", "to": "", "reg": false, "x": 580, "y": 230, "wires": [["ex8c_join"]]}, {"id": "ex8c_join", "type": "join", "z": "ex8c_tab", "name": "配列に戻す", "mode": "auto", "build": "array", "property": "payload", "propertyType": "msg", "key": "topic", "joiner": "\\n", "joinerType": "str", "accumulate": "false", "timeout": "", "count": "", "reduceRight": false, "reduceExp": "", "reduceInit": "", "reduceInitType": "", "reduceFixup": "", "x": 780, "y": 200, "wires": [["ex8c_debug"]]}, {"id": "ex8c_debug", "type": "debug", "z": "ex8c_tab", "name": "全員の一覧", "active": true, "tosidebar": true, "console": false, "tostatus": false, "complete": "payload", "targetType": "msg", "statusVal": "", "statusType": "auto", "x": 950, "y": 200, "wires": []} ]

7. まとめ

重要ポイント:

注意事項:

8. トラブルシューティング

症状原因解決方法
リクエストがタイムアウト HTTP Response がない 必ず HTTP Response を配置
404 Not Found(サーバー側) URLが間違っている HTTP In のURL設定を確認
POSTのボディが空 Content-Typeがない クライアント側でヘッダー設定
CORSエラー クロスオリジン制限 CORSヘッダーを追加
レスポンスが空(クライアント側) URLが間違い / サーバーダウン URLを確認、ブラウザでアクセスしてみる
401 Unauthorized 認証情報がない/間違い APIキーやトークンを確認
タイムアウト(クライアント側) サーバーの応答が遅い タイムアウト時間を延長
JSONパースエラー レスポンスがJSONでない 出力形式を「UTF8文字列」に変更
文字化け エンコーディング問題 charset=utf-8 を追加

CORSヘッダーの追加方法

💡 CORSとは: Cross-Origin Resource Sharing(クロスオリジン・リソース・シェアリング)の略です。ブラウザには「今見ているWebページと違うドメイン(オリジン)のAPIには、無断でJavaScriptからアクセスさせない」というセキュリティの仕組みがあります。これをクロスオリジン制限と呼び、制限に引っかかって通信がブロックされることをCORSエラーと呼びます。サーバー側(Node-RED)が「このオリジンからのアクセスは許可します」という許可証にあたるレスポンスヘッダーを付けて返すことで、ブラウザは通信を許可するようになります。

// Functionノードで設定 msg.headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE", "Access-Control-Allow-Headers": "Content-Type" }; return msg;

9. 実務活用例

ケース1: センサーデータ受信エンドポイント

Raspberry Pi からHTTP POSTでセンサーデータを受け取り、データベースやクラウドに転送

POST /api/sensor → データ検証と保存 → Response

ケース2: Webhook受信

GitHub、Slack、LINE等の外部サービスからの Webhook(外部から自動的に送られてくる HTTP 通知。用語集参照)を受信して処理

POST /webhook → イベント処理 → 200 OK

ケース3: 外部API連携

天気情報やクラウドサービスのAPIを定期的に呼び出し、データを取得して通知

5分ごと → 天気API → 閾値判定 → 通知

ケース4: 機器制御API + モニタリング

IoT機器の状態取得や制御コマンド送信のためのREST APIを提供しつつ、外部APIでモニタリングデータを送信

GET /api/device → 状態取得 → Response
定期実行 → データ収集 → クラウドAPI

代替APIリスト(サンプルAPIが使えない場合):

📚 Node-RED 公式ドキュメント - HTTP ノード

🏠