Do you have to take an anesthetic injection before getting a cavity filled?

Not necessarily. Some cavities are quite near the surface of the tooth. They can be filled without needing any numbing medication. Deeper cavities which are nearer to the root of the tooth may require local anesthesia to be filled comfortably. Your dentist will advise you as to the best way to have dental work done safely and comfortably.
Not always. I have a few patients that do work without anesthetic. The majority of patients do not want to feel the dental procedure so they elect to have anesthetic.