If someone gets the API key that you are using either by reverse-engineering the APK or by any other means, they can use the key for their own purposes while your YouTube API quota gets used. Restricting the YouTube API key ensures that only your app is authorized to use this key for making requests and all the requests from any other app will get rejected.
This guide will show you how to restrict the key for both the debug and release versions of the app.
Restricting the key for the debug version
In order to restrict the key, you will need the Debug SHA-1 which can be generated using Android Studio. Go to your Android Studio project and open the Gradle section which can be found in the top right section of the Android Studio as shown in the screenshot below.
Now, navigate to app > Tasks > android and then double click on signingReport. Please wait while the Android Studio generates the signing report.
Once the signing report is generated, you can find the Debug SHA-1 in the Run tab as shown below.
Copy this SHA-1 as you will need it later.
Now, go to Google Developers Console and select the project from the dropdown present in the header.
From the menu, click on APIs & Services and then select Credentials.
Click on the API key that you generated initially while creating the project.
In the Application restrictions section, select the Android apps option and then click on ADD AN ITEM button.
Enter your app package name, copy the SHA-1 that you generated earlier, and then click on DONE.
In the API restrictions section, select the Restrict key option and then select the YouTube Data API v3 from the dropdown. Click on the SAVE button and your API key will be restricted for the debug version of the app.
Restricting the key for the release version
Go to the Google Play Console and select the app. Under the Release management tab, select App signing. Copy the SHA1 from the App signing certificate section.
On the Google Developers Console's Credentials page, click on the API key, and under the Restrict usage to your Android apps section, click on ADD AN ITEM button.
Enter your app package name, enter the App signing certificate SHA1 that you copied, and then click on DONE. Click on the SAVE button at the bottom of the page.
Again go to the App signing section of the Google Play Console and scroll down to find the Upload certificate section. Copy the SHA1 from the Upload certificate section.
Go to the Google Developers Console's Credentials page, click on the API key, and under the Restrict usage to your Android apps section, click on ADD AN ITEM button.
Enter your app package name, enter the Upload certificate SHA1 that you copied, and then click on DONE. Click on the SAVE button at the bottom of the page and your API key will be restricted for the release version of the app.