Creating links between Blender nodes using the Python API

Typically links between nodes in Blender are created by simply dragging and dropping between the desired input and output node sockets. However, if necessary, we can also connect nodes using the Blender Python API.

All links between nodes are stored in the node tree structure, both for shaders and for Geometry Nodes.

Shader Editor

We can access the material node tree through a pointer to the object’s material.

For example, for the active mesh object:

Links between nodes are stored in the “links” collection:

We can create a new link between two nodes using the new() collection command.

We need to pass two parameters to the called command:

  1. pointer to the output socket of the first node – where the link will go from
  2. pointer to the input socket of the second node – where the link will come

A pointer to a desired node can be obtained by its name from the “nodes” collection of the node tree:

A pointer to the desired output socket can be obtained from the “outputs” collection of the node. It can be obtained by the ordinal number, or by name.

The pointer to the input socket can be obtained from the node’s “inputs” collection. Likewise by index or by name.

Having pointers to the input and output sockets of two nodes, we can create a link between them:

Geometry Nodes Editor

For geometry nodes, the principle of creating links between nodes is exactly the same as for materials.

The node tree for Geometry Nodes is accessed from the modifier.

Pay attention that the pointer to the node tree in the case of Geometry Nodes is named “node_group”.

Otherwise, everything is exactly the same as for materials.

Links between nodes are stored in the “links” collection:

A link between two nodes is created by the same new() command, in the parameters of which it is necessary to pass pointers to two sockets – the output on the first node and the input on the second.

We get the pointer to the nodes by name from the “nodes” collection of the node tree:

We can get a pointer to the desired output socket by index or by name from the “outputs” collection of the node.

And the pointer to the input socket we can get from the node’s “inputs” collection, also by index or by name.

Having pointers to the required sockets, we can create a link between them:

5 1 vote
Article Rating
Subscribe
Notify of
guest

2 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Roy
Roy
10 months ago

When i try to use in [‘Group Output’].inputs[1] it works in 3.4 but in 3.5 it does not work.Do you know if this is a bug?:

bpy.context.object.modifiers[‘GeometryNodes’].node_group.links.new(
  bpy.context.object.modifiers[‘GeometryNodes’].node_group.nodes[‘Cube’].outputs[‘Mesh’],
  bpy.context.object.modifiers[‘GeometryNodes’].node_group.nodes[‘Group Output’].inputs[1]
)