Package: nodered-forge
NodeRedForgeNodeRedForge is a Python-based tool designed to facilitate the generation of custom JSON API nodes for Node-RED.InstallationTo install NodeRedForge, use the following pip command:pipinstallnodered-forgeUsageNodeForgeAppTo create custom API nodes for Node-RED, start by defining the application name and the base URL:fromnodered_forgeimportNodeForgeAppnodeforge_app=NodeForgeApp("TestTodoApi","http://test_api:5000")Additional options for initializingNodeForgeAppinclude:NodeForgeApp(name,base_url,ignore_ssl_errors=False,authentication=False,# Whether authentication is required for API requests.authentication_header='Authorization',# Header used for authenticationpackage_name=None,# package name for generated Node-RED moduledefault_icon=None,default_color=None,# HTML Color, a default color is generated randomlydefault_category=None,global_parameters_config=None# Global configuration for parameters shared across all API nodes):Creating API nodesAPI nodes can be created using either the methodnodeforge_app.register_api_node()or the decorator@nodeforge_app.api_node().Example:@nodeforge_app.api_node('/todos/<str:todo_id>',method='GET')@flask_app.route('/todos/<int:todo_id>',methods=['GET'])defget_todo(todo_id):todo=next((itemforitemintodosifitem['id']==todo_id),None)iftodo:returnjsonify({'todo':todo})else:returnjsonify({'message':'Todo not found'}),404Other options for adding API nodes include:nodeforge_app.register_api_node(name,# for api_node decorator the name can be taken from the function nameroute,method='GET',color=None,# HTML color codecategory=None,# Category in Node-red palleticon=None,parameters_config=None,# Configuration for API parametersdescription='No API description is provided'):API ParametersAPI parameters can be set in three ways:Using therouteargument of either the methodnodeforge_app.register_api_node()or the decorator@nodeforge_app.api_node().Using theparameters_configargument of either the methodnodeforge_app.register_api_node()or the decorator@nodeforge_app.api_node(). This parameter accepts a list of parameter strings, dictionaries, or instances ofNodeParameter.Using theglobal_parametersargument in the initialization ofNodeForgeApp. This argument accepts the same formats asparameters_config.Parameter StringsParameter strings accept the following formats:param_nameparam_type:param_nameparam_type:param_name:default_valueNodeParameterThere are three types of API parameters:Route parameters (constructing the URI stem),URL parameters (sent as URL-encoded key-values),Body parameters (sent as JSON).Initialization options forNodeParameter:NodeParameter(name,type=InputType.STR,default=None,# Default valuerequired=Falseplain_type="text"# For plain input type, specifies the HTML input type.route_param=Falseurl_param=Falseoptions=None# List of options for parameters with a predefined set of values,# Accepts an iterator either strings, value & label tuples,or dictionaries with value and label keysmultiple_select=False# Allows selecting multiple values if options are defined):InputTypeInput types accepted byNodeParameter:InputType.PLAINInputType.STRInputType.NUMInputType.BOOLInputType.JSONInputType.DATEInputType.SELECTAll these types correspond to Node-REDTypedInput Widgettypes,
except forInputType.PLAIN, which uses a plain HTML input (you can set the type of the input using theplain_typeargument).Example:@nodeforge_app.api_node('/todos/<int:todo_id>',method='PUT',parameters_config=['str:text','date:due-date','bool:done',NodeParameter('notes',type=InputType.PLAIN,plain_type='textarea'),'int:level',NodeParameter('tags',options=['work','personal','chore','family'],multiple_select=True),NodeParameter('assigned-to',options=['me','you','him','her']),NodeParameter(name="pretty",type=InputType.BOOL,default=True,url_param=True),])@flask_app.route('/todos/<int:todo_id>',methods=['PUT'])@require_authenticationdefupdate_todo(todo_id):todo=next((itemforitemintodosifitem['id']==todo_id),None)iftodo:data=request.get_json()todo.update({'text':data.get('text',todo['text']),'done':data.get('done',todo['done']),'due-date':data.get('due-date',todo['due-date']),'tags':data.get('tags',todo['tags']),'notes':data.get('notes',todo['notes']),'level':data.get('level',todo['level']),'assigned-to':data.get('assigned-to',todo['assigned-to'])})returnjsonify({'todo':todo})else:returnjsonify({'message':'Todo not found'}),404This code will generate a custom node with the following edit view:JSON Body RequestIf a body parameter (neitherroute_paramnorurl_paramis set to True) is included in the node config, a JSON body property is added to the custom node.
If this field is filled, body parameters from the form will be ignored, giving the user a way to send custom objects.Generating Custom NodesAfter configuring the nodes, you can generate them using theoutput_packagemethod:nodeforge_app.output_package('/modules')This will create a package directory under/moduleswith the prefix "node-red-contrib-nodered-forge-" unless thepackage_nameis specified in the initialization ofNodeForgeApp.To install the generated module in Node-RED, run the following commands:cd/path/to/node-red/data/
npminstall/modules/package-nameRestart Node-RED if the module is installed or updated.Test AppAn example app can be found underdev/test-api-docker/test_api_app.py, which is a dummy todo manager with CRUD operations. There is also a Docker Compose file with both this app and Node-RED to test the app; don't forget to restart upon making changes to the test app.