How to get the ID of the GAE project that a Java app is running in?

Viewed 400

I have a Java app running in Google App Engine. I need to programmatically get the ID of the project it's running as part of, in Java.

This question explains how to achieve my goals in Python, but that's not Java of course.

This documentation says that I can simply call ApiProxy.getCurrentEnvironment().getAppId(), but this method just returns null in my app.

This question explains how to get the project ID over an HTTP request, but I'm wondering if there's a better way to do this in Java without having to manually construct an HTTP request?

Edit: Luyi's answer seems like it's working for most people, but it returns null for me.

2 Answers

You can use com.google.cloud.ServiceOptions helper to get the default project id. It will provide you some abstraction to be able to retrieve project-id depending on your context and current app-engine runtime.

For instance Java11 runtime does not support some old api. And getting project-id via requesting metadata by HTTP is a versatile solution.

In this case, ServiceOptions.getDefaultProjectId is a good way to keep your code versatile and simple.

Spring Cloud GCP is using this method behind the scene to retrieve project-id.

Import google-cloud-core dependency :

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-core</artifactId>
  <version>1.94.0</version>
</dependency>

Then use ServiceOptions:

import com.google.cloud.ServiceOptions;
...

String projectId = ServiceOptions.getDefaultProjectId();

Maybe you are looking for this:

import com.google.appengine.api.utils.SystemProperty;
    
String appId = SystemProperty.applicationId.get();

From SystemProperty you can get other info too, such as Environment and Application Version.

Related