How to add modifier to blender object programmatically?

Hi, in this article I am going to add a Bevel modifier to a cube in Blender with python script. In my previous tutorial I have already shown you how to run python script in Blender Text Editor as well as me writing a few lines of code to rotate and change the color of the cube. Applying a Bevel modifier to an object in Blender is super simple, all we need is to include these two lines of code within the previous code.

obj.modifiers.new("Bevel", "BEVEL")
bpy.ops.object.modifier_apply(apply_as='DATA', modifier="Bevel")

Here is the full script which will create the Bevel effect on the previous rotated object.

import bpy

scene = bpy.context.scene
material = bpy.data.materials.new("PKHG")
material.diffuse_color = (0.539,0.546,0.0042)
material.diffuse_fresnel = 3.0
material.darkness = 0.3
material.diffuse_intensity = 0.5
material.diffuse_intensity = 0.7
material.diffuse_toon_size = 3.0
for obj in scene.objects:
    obj.rotation_euler = (0.785398, 0.785398, 0.785398)
    obj.modifiers.new("Bevel", "BEVEL")
    bpy.ops.object.modifier_apply(apply_as='DATA', modifier="Bevel")
    obj.active_material = material

If you look at the 3D View window now after you have run the python script you will see this yellow cube with bevel effect!

Applying Modifier
Applying Bevel Modifier