Backup the API key beforehand in case you have trouble reverting the file.
Let's say the file with a key you want to hide is <filename>
Open it and change the API key with a placeholder, like <api-key>
Save and add the file to git and commit
git commit -m 'Masking API key'
Then revert the file, undoing recent changes so your key is back where it should be and save it.
Use
git update-index --assume-unchanged <filename>
with the file where the key is so that git no longer tracks changes to this file, so you won't be bothered to push the real key to the repository.
If you need to make changes to this file and have git track them, use:
git update-index --no-assume-unchanged <filename>
Thanks! Was searching for this!