Working on a plugin in Godot 4.0.1 so here is an update:
var key = InputEventKey.new()
key.physical_keycode = KEY_W
InputMap.add_action("__custom_action")
InputMap.action_add_event("__custom_action", key)
In my editor plugin context it's also advisable to clean up the action. But that's probably not the case for a game.
InputMap.erase_action("__custom_action")