Python Cycles material reference?

I would like to create materials for Cycles completely within a Python script but I’m having difficulty finding information about how to achieve this.

The Blender API has very little information about this. It lists the shader node types such as ‘ShaderNodeBsdfDiffuse’, but says nothing about how to create them.

I’ve hunted around and found a few posted examples of properties that can be set for some types of Cycles materials via Python, but I haven’t found anything that explains how to work with Cycles in Python.

The fact that some people have contributed a few examples suggests there is some reference documentation somewhere that contains this information. Any pointers?

Quite in a hurry so here’s a piece of code from a personal addon with some comments added.

import bpy
from mathutils import *

#Create the material
mat ="randomName")
mat.use_nodes = True
nodes = mat.node_tree.nodes   #Important : This is where you gonna create your nodes on your material
nodes.clear()                          #I don't want the defaut diffuse + output for some reason
links = mat.node_tree.links       #The links between nodes

#Create nodes on the material : no connexion is done between those yet
nodeImage ="ShaderNodeTexImage")
nodeImage.image = img                                                    #img is not defined for this topic
nodeImage.location = Vector((-300,0))                                  #Just for esthetic
nodeTransparent ="ShaderNodeBsdfTransparent")
nodeTransparent.location = Vector((0,-150))                          #Just for esthetic
nodeEmission ="ShaderNodeEmission")
nodeEmission.location = Vector((0,-300))                              #Just for esthetic
nodeMix ="ShaderNodeMixShader")
nodeMix.location = Vector((300,0))                                      #Just for esthetic
nodeOutput ="ShaderNodeOutputMaterial")
nodeOutput.location = Vector((600,0))                                  #Just for esthetic

#Connect the nodes together like you'll do on a regular project["Color"],nodeEmission.inputs["Color"])["Emission"],nodeMix.inputs[2])["Shader"],nodeOutput.inputs["Surface"])["BSDF"],nodeMix.inputs[1])["Alpha"],nodeMix.inputs[0])

Thanks, that should give me enough to go on with for now. How did you learn this? Is there any documentation that contains this information?

The way this API works makes things quite similar when you create a new object, material, mesh, etc… using “new()” method.

I don’t remember if I learnt that from the documentation or just by looking to some sources.