I want to get list of my albums from Google Photos. And I'm using new REST API.
I wrote the code which executes GET request:
GET
https://photoslibrary.googleapis.com/v1/albums
according to the official guide: https://developers.google.com/photos/library/guides/list
And this code only returns response with status 200, but without json body:
Listing:
public static void main(String[] args) throws IOException, GeneralSecurityException, ServiceException, ParseException {
GoogleCredential credential = createCredential();
if (!credential.refreshToken()) {
throw new RuntimeException("Failed OAuth to refresh the token");
}
System.out.println(credential.getAccessToken());
doGetRequest(credential.getAccessToken(), "https://photoslibrary.googleapis.com/v1/albums");
}
private static GoogleCredential createCredential() {
try {
return new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAccount)
.setServiceAccountPrivateKeyFromP12File(ENCRYPTED_FILE)
.setServiceAccountScopes(SCOPE)
.setServiceAccountUser(emailAccount)
.build();
} catch (Exception e) {
throw new RuntimeException("Error while creating Google credential");
}
}
private static void doGetRequest(String accessToken, String url) throws IOException, ParseException {
logger.debug("doGetRequest, with params: url: {}, access token: {}", accessToken, url);
HttpGet get = new HttpGet(url);
get.addHeader("Authorization",
"Bearer" + " " + accessToken);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(get);
String json = EntityUtils.toString(response.getEntity());
System.out.println(json);
}
Also i tried to use other REST clients (e.g. Postman) and the same result i recieve is:
{}
It looks like you are using a service account to access the API. Service accounts are not supported by the Google Photos Library API.
You will need to set up OAuth 2.0 for a Web Application as described here:
You will then use the client Id
and client secret
returned on this page as part of your requests. If you need offline access, which means access when the user is not present in the browser, you can also request an offline
access_type
and use refresh tokens
to maintain access.
It looks like you are using the Google API Java client, which also has support for this flow. Set the client secrets on the builder by calling setClientSecrets(..)
like this:
return new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build();
You also need to handle the callback from the OAuth request in your application where you will receive the access tokens at the callback URL that you have configured in the developer console.
There is also a more complete example in the documentation for the client library.