You can't apologize without first understanding the impact of your actions.
And for that you need to listen actively to your counterpart. Ask questions such as: "What went through your head", "What did you feel in that moment" etc.
Once you think you understand, say it back to them (paraphrase it), not just cognitively, but also emotionally.
If they reply with something like: "Yes, but also this...and also that". Then you don't have the full picture yet. Keep listening and paraphrasing.
When they reply with something like "Exactly". Then that's your confirmation to go to the next step.
Step 2: Apologize
Apologizing is simple: "I'm sorry I ____ you".
But we almost always mess it up either by not really taking responsibility: "I'm sorry you feel that way"
Or by defending ourselves: "I'm sorry...but that was not my intention"
Clarifying that you didn't have bad intentions is important, just not yet!
Apologizing is about showing remorse and taking responsibility, not about explaining what was going on in your head at that time (that's step #3).
After you apologize, stop. Don't say another word. Your apology is exactly they wanted to hear all along, so let them hear it and process it. Don’t rush to fill the silence
If they think you truly understood the impact of your actions (step #1), and that you actually regret it, they are not only very likely to accept your apology but also to feel relieved.
Because a good apology makes the other feel seen, respected, and valuable, and allows them to trust you again.
Step 3: Explain
Now is the time to explain what happened in your head, but not as a way to excuse yourself (that'd immediately undo your apology), but as a way to help them understand why you acted the way you did.
Just make sure to ask for permission first: "Can I tell you what happened in my head and why I acted that way?"
Regardless of how you explain it, emphasize over and over you are not evading the responsibility of your actions: "The reason I acted that way was because...still, what I did was wrong, and that doesn't excuse my behavior"
This will give them the opportunity to understand you as well, and make room for forgiveness.
Finally, commit to never make that mistake again. Not with a shallow: "I'll never do it again" but with concrete actions.
The more concrete the better. It shows the other person you really care about them.