Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Google Sheets Java API with API key not OAuth?

Is there a way to use "Google Sheet Java API" with API key not with OAuth which is given in their examples

https://developers.google.com/sheets/api/quickstart/java

I know you can use HTTP request to get data with API key but I was thinking if there is a way to do this with the google provided Java API so that I don't have to parse JSON for every request.

like image 294
Mayank Wadhwa Avatar asked Dec 23 '18 04:12

Mayank Wadhwa


Video Answer


1 Answers

I didn't find any official way to achieve this, but I was able to do it as described in Acquiring and using an API key:

After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs.

by using a request interceptor and adding the key query parameter manually, like this:

private Sheets getSheets() {
    NetHttpTransport transport = new NetHttpTransport.Builder().build();
    JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer httpRequestInitializer = request -> {
        request.setInterceptor(intercepted -> intercepted.getUrl().set("key", API_KEY));
    };

    return new Sheets.Builder(transport, jsonFactory, httpRequestInitializer)
            .setApplicationName(APPLICATION_NAME)
            .build();
}

public List<List<Object>> getValues(String spreadsheetId, String range) throws IOException {
    return getSheets()
            .spreadsheets()
            .values()
            .get(spreadsheetId, range)
            .execute()
            .getValues();
}
like image 86
arekolek Avatar answered Oct 20 '22 01:10

arekolek