Youtube API Key
Asked Answered
T

3

8

When I try to use YouTube API for Search, I get this error:

There was a service error: 403 : The request did not specify any Android package name or signing-certificate fingerprint. Please ensure that the client is sending them or use the API Console to update your key restrictions.

In the MainActivity I have this code:

youtube = new YouTube.Builder(new NetHttpTransport(), JSON_FACTORY, new HttpRequestInitializer() {
                    @Override
                    public void initialize(HttpRequest httpRequest) throws IOException {

                    }
                }).setYouTubeRequestInitializer(new YouTubeRequestInitializer(apiKey)).setApplicationName("Some Name").build();

In the cloud console I have an ApiKey for Android, with the package name set and the SHA-1 number obtained with keytool command.

Tractile answered 17/9, 2016 at 5:19 Comment(1)
Did you find any solution to your question?Turnabout
T
15

After lot of trial and error, the thing which finally worked for me was changing API KEY restriction to None instead of Android from API Manager console and just save. enter image description here

After doing the above step I am able to make search API call from my Android device using my API KEY.

Turnabout answered 28/9, 2016 at 12:19 Comment(10)
It is the only solution that has worked for me at the time.Tractile
this can be considered as an work around, it works but the main problem with restricted key remains unsolvedTarsal
@Turnabout this solution is not working for release version, it only working for debug phase. How to solve it for release version?.Flocculent
This solution not working in release version. Any others update ?Edessa
@AslamHossin, Are you doing all steps properly because for me the fix is working with release version.Turnabout
Is there any risk if i follow your procedure like i am requesting from android but API key is no restriction is ok ?Edessa
@AslamHossin is there any solution for release version?Ribbing
@DarkLeonhart yeah, finally I resolve it by creating browser key cause android key not working for release version for me.Edessa
Hi, you should try Ayman Al-Absi's solution, it works for me.Ribbing
I'm doing exactly the same as explained above. Still not working for me.Noonberg
I
21

At last I found a solution for this problem :)

After creating API_KEY in Google Developer Console and restrict it with "Package name" and "SHA-1 certificate fingerprint", You have to provide these data in every youtube api request. Below the steps:

1- get Package Name:

String packageName = context.getPackageName();

2- get SHA-1:

private String getSHA1(String packageName){
    try {
        Signature[] signatures = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures;
        for (Signature signature: signatures) {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            md.update(signature.toByteArray());
            return BaseEncoding.base16().encode(md.digest());
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

3- Prepare youtube api http header:

youTube = new YouTube.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), new HttpRequestInitializer() {
    @Override
    public void initialize(HttpRequest request) throws IOException {
        String packageName = context.getPackageName();
        String SHA1 = getSHA1(packageName);

        request.getHeaders().set("X-Android-Package", packageName);
        request.getHeaders().set("X-Android-Cert",SHA1);
    }
}).setApplicationName(appName).build();

4- Build your youtube api query as you like: For example to search for video:

YouTube.Search.List query;
query = youTube.search().list("id, snippet");
query.setKey(YOUR_API_KEY);
query.setType("video");
query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");
query.setQ(search keywords);
SearchListResponse response = query.execute();
List<SearchResult> results = response.getItems();

then process returned search results.

Illusion answered 16/4, 2017 at 23:8 Comment(11)
Where did you find info for putting the package and sha1 fingerprint there?Widow
when you create Android Client key for your project, package name and SHA-1 is required.Illusion
Where did you find this document about hot to add package name and SHA1 fingerprint into a request headers?Yep
Where did you found those cert and package headers specified in docs :)?Kobi
You may check steps in this link #27609942Illusion
Package name is equivalent to BuildConfig.APPLICATION_IDElectrodeposit
Did you use okhttp for this?Chiles
@AymanAl-Absi I tried your above solution. Still i'm getting error as ( "The Android package name and signing-certificate fingerprint, com.example.somename and ZFzdtB22bpkKGc1kSgi0qxUPSWk=, do not match the app restrictions configured on your API key.")Noonberg
@JianLi Still no luck. #55101696Noonberg
@Noonberg try sending the SHA1 in lower case hexcode format e.g:(AB:8A:CC:7R....) as (ab8acc7r...). worked for me.Saharanpur
Use this link for getting the SHA in all Android versions as packageManager.signatures is deprecated in Android P. https://mcmap.net/q/650634/-how-to-use-packageinfo-get_signing_certificates-in-api-28Bodywork
T
15

After lot of trial and error, the thing which finally worked for me was changing API KEY restriction to None instead of Android from API Manager console and just save. enter image description here

After doing the above step I am able to make search API call from my Android device using my API KEY.

Turnabout answered 28/9, 2016 at 12:19 Comment(10)
It is the only solution that has worked for me at the time.Tractile
this can be considered as an work around, it works but the main problem with restricted key remains unsolvedTarsal
@Turnabout this solution is not working for release version, it only working for debug phase. How to solve it for release version?.Flocculent
This solution not working in release version. Any others update ?Edessa
@AslamHossin, Are you doing all steps properly because for me the fix is working with release version.Turnabout
Is there any risk if i follow your procedure like i am requesting from android but API key is no restriction is ok ?Edessa
@AslamHossin is there any solution for release version?Ribbing
@DarkLeonhart yeah, finally I resolve it by creating browser key cause android key not working for release version for me.Edessa
Hi, you should try Ayman Al-Absi's solution, it works for me.Ribbing
I'm doing exactly the same as explained above. Still not working for me.Noonberg
F
2

Try to double check if you follow properly the setup when creating OAuth Credentials. And make sure you enable the YouTube Data API in your Developer Console.

Here the steps that you need to do.

  1. In the Package name field, enter your Android app's package name

  2. In a terminal, run the Keytool utility to get the SHA1 fingerprint for your digitally signed .apk file's public certificate.

keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v

  1. Paste the SHA1 fingerprint into the form where requested.

I also found here in this SO question answered by a Googler that a user has to go through OAuth2. Because Service accounts are not supported in Data API v3.

Falco answered 19/9, 2016 at 1:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.