Updated:

Quickest: creative mode

/gamemode creative

Creative players take no damage, except from the void and /kill. To keep playing survival, use the effect below. See the gamemode guide.

Resistance V

# Java
/effect give @s minecraft:resistance infinite 4 true
# Bedrock
/effect @s resistance 99999 4 true

Each Resistance level cuts damage by 20%, so level V blocks almost everything. Levels count from 0 in commands, so level V is 4. The final true hides the particles. Java's infinite works from 1.19.4.

Resistance does not stop the void or /kill. To stop hunger as well, add Saturation:

/effect give @s minecraft:saturation infinite 0 true

Turn off one kind of damage (game rules)

DamageJava 1.21.11+Java 1.21.10 and earlierBedrock
Fallingminecraft:fall_damagefallDamagefalldamage
Fire and lavaminecraft:fire_damagefireDamagefiredamage
Drowningminecraft:drowning_damagedrowningDamagedrowningdamage
/gamerule minecraft:fall_damage false

That example uses the 1.21.11+ name. Game rules affect everyone in the world. The game rule list has the rest.

Make a mob invincible (Java)

/summon minecraft:villager ~ ~ ~ {Invulnerable:1b}
/data merge entity @e[type=minecraft:villager,limit=1,sort=nearest] {Invulnerable:1b}

A mob with Invulnerable:1b ignores attacks, explosions and other damage, which is handy for shop villagers and pets. Set {Invulnerable:0b} to undo it. Bedrock has no such data, so give the mob Resistance instead.

Undo it

# Java
/effect clear @s minecraft:resistance
# Bedrock (removes every effect)
/effect @s clear

Set game rules back to true.

When it does not work

Common questions

Check your command

The Command Error Doctor checks common syntax mistakes in your browser.