To cast a spell as an Opportunity Attack, you have to pick up the War Caster feat, which provides that feature (among others):
When a hostile creature's movement provokes an opportunily attack from you, you can use your reaction to cast a spell at the creature, rather than making an opportunity attack. The spell must have a casting time of 1 action and must target only that creature. (PHB 170)
There's a more detailed explanation of in the Sage Compendium:
Can you use a melee spell attack to make an opportunity attack?
You can’t if the spell attack is created by casting a spell. When a creature triggers an opportunity attack from you, you can use your reaction to make a melee attack against it. The opportunity attack doesn’t suddenly give you the ability to cast a spell, such as shocking grasp.
Each spell has a casting time. A game feature, such as an opportunity attack, doesn’t let you bypass that casting time, unless the feature says otherwise. The War Caster feat is an example of a feature that does let you bypass a 1-action casting time to cast a spell in place of making an opportunity attack. (p. 12, v. 2.1)