Custom operator that applies transforms to all objects
Press A to select all and then &#9096; CtrlA->All Transforms - apply transforms already works on all selected objects.

To get your example working, the context calling the operator needs to be from the 3dviewport, so it will fail if you are running the script in the text editor. Don't call the operator from your script, register the class and then search for it in the 3d view.

If you still have an issue, you can override the context. You can find several questions here to explain ways to do that.