Read/Write Google sheet via Server without using OAuth The Next CEO of Stack OverflowAccess Google spreadsheet API without Oauth tokenHow do I check if a file exists in Java?How do I access (read, write) Google Sheets spreadsheets with Python?Write data to Google Sheet using Google Sheet API V4 - Java Sample Codegoogle sheets api v4 PHP Quickstart Writing to a single rangehow to filter the rows I read from google-sheets with Java APIGoogle Sheet API 4 (read/write sheet using browser request) in PHPWriting to Google Sheets without authenticationCan I write to Google Sheet via Google Sheets API without Oauth, using developer key?Writing to public google folder and google sheets withouth the use of oauth2?Bookmarklet writing to google sheet via POST

What did we know about the Kessel run before the prequels?

What does "Its cash flow is deeply negative" mean?

Is it okay to majorly distort historical facts while writing a fiction story?

Writing differences on a blackboard

Running a General Election and the European Elections together

Flying from Cape Town to England and return to another province

Can we say or write : "No, it'sn't"?

Does increasing your ability score affect your main stat?

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Prepend last line of stdin to entire stdin

Is it professional to write unrelated content in an almost-empty email?

Easy to read palindrome checker

Does Germany produce more waste than the US?

What is meant by "large scale tonal organization?"

Why does standard notation not preserve intervals (visually)

Yu-Gi-Oh cards in Python 3

Domestic-to-international connection at Orlando (MCO)

Is it possible to replace duplicates of a character with one character using tr

Axiom Schema vs Axiom

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Unclear about dynamic binding

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Where do students learn to solve polynomial equations these days?

Necessary condition on homology group for a set to be contractible



Read/Write Google sheet via Server without using OAuth



The Next CEO of Stack OverflowAccess Google spreadsheet API without Oauth tokenHow do I check if a file exists in Java?How do I access (read, write) Google Sheets spreadsheets with Python?Write data to Google Sheet using Google Sheet API V4 - Java Sample Codegoogle sheets api v4 PHP Quickstart Writing to a single rangehow to filter the rows I read from google-sheets with Java APIGoogle Sheet API 4 (read/write sheet using browser request) in PHPWriting to Google Sheets without authenticationCan I write to Google Sheet via Google Sheets API without Oauth, using developer key?Writing to public google folder and google sheets withouth the use of oauth2?Bookmarklet writing to google sheet via POST










2















Tried going through the internet and google docs they provide OAuth way only. Is there a way to read/write to google sheets with API Key and not OAuth.










share|improve this question




























    2















    Tried going through the internet and google docs they provide OAuth way only. Is there a way to read/write to google sheets with API Key and not OAuth.










    share|improve this question


























      2












      2








      2








      Tried going through the internet and google docs they provide OAuth way only. Is there a way to read/write to google sheets with API Key and not OAuth.










      share|improve this question
















      Tried going through the internet and google docs they provide OAuth way only. Is there a way to read/write to google sheets with API Key and not OAuth.







      java google-sheets google-spreadsheet-api google-sheets-api






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 15 '18 at 6:45







      Ankush

















      asked May 8 '18 at 9:16









      AnkushAnkush

      77112




      77112






















          3 Answers
          3






          active

          oldest

          votes


















          1














          After some research, Credential object from google-oath-client module can help. Download the .p12 file from the google account. Code for reading a google sheet without OAUth prompt below. This can also be used to write or append sheets with some modification :



          package com.mycomp;

          import com.google.api.client.auth.oauth2.Credential;
          import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
          import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
          import com.google.api.client.http.HttpTransport;
          import com.google.api.client.http.javanet.NetHttpTransport;
          import com.google.api.client.json.JsonFactory;
          import com.google.api.client.json.gson.GsonFactory;
          import com.google.api.services.sheets.v4.Sheets;
          import com.google.api.services.sheets.v4.SheetsScopes;
          import com.google.api.services.sheets.v4.model.ValueRange;
          import com.nm.vernacular.services.SpreadSheetsService;
          import org.slf4j.Logger;
          import org.slf4j.LoggerFactory;
          import org.springframework.beans.factory.annotation.Qualifier;
          import org.springframework.stereotype.Service;

          import java.io.File;
          import java.io.IOException;
          import java.net.URISyntaxException;
          import java.net.URL;
          import java.security.GeneralSecurityException;
          import java.util.Collections;
          import java.util.LinkedList;
          import java.util.List;

          /**
          * Created by ankushgupta & modified for SO.
          */

          public class GoogleSheetsReader

          private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
          private static final String KEY_FILE_LOCATION = "<Name of p12 file>.p12";
          private static final String SERVICE_ACCOUNT_EMAIL = "<email of google service account>";
          private static final String APPLICATION_NAME = "Google Sheets API";

          private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSheetsReader.class);

          /**
          * Global instance of the scopes required by this quickstart.
          * If modifying these scopes, delete your previously saved credentials/ folder.
          */
          private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);

          /**
          * Creates an authorized Credential object.
          * @return An authorized Credential object.
          * @throws IOException If there is no client_secret.
          */
          private Credential getCredentials() throws URISyntaxException, IOException, GeneralSecurityException
          //Reading Key File
          URL fileURL = GoogleSheetsReader.class.getClassLoader().getResource(KEY_FILE_LOCATION);
          // Initializes an authorized analytics service object.
          if(fileURL==null)
          fileURL = (new File("/resources/"+ KEY_FILE_LOCATION)).toURI().toURL();

          // Construct a GoogleCredential object with the service account email
          // and p12 file downloaded from the developer console.
          HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
          return new GoogleCredential.Builder()
          .setTransport(httpTransport)
          .setJsonFactory(JSON_FACTORY)
          .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
          .setServiceAccountPrivateKeyFromP12File(new File(fileURL.toURI()))
          .setServiceAccountScopes(SCOPES)
          .build();


          @Override
          public List<Object[]> readSheet(String nameAndRange, String key, int[] returnRange) throws GeneralSecurityException, IOException
          final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
          final String spreadsheetId = key;
          final String range = nameAndRange;
          try
          Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials())
          .setApplicationName(APPLICATION_NAME)
          .build();

          ValueRange response = service.spreadsheets().values()
          .get(spreadsheetId, range)
          .execute();
          List<List<Object>> values = response.getValues();

          int a = returnRange.length;
          List<Object[]> result = new LinkedList<>();

          if (values == null catch(Exception ex)
          LOGGER.error("Exception while reading google sheet", ex);
          finally


          return null;


          public static void main(String[] args)
          GoogleSheetsReader reader = new GoogleSheetsReader();
          reader.readSheet("<Sheet Name>!A2:B", "<sheets key from URL>", new int[]0, 1);







          share|improve this answer

























          • This does not answer the question. The OP is asking how to WRITE to the google sheet without using OAuth.

            – John Henckel
            Mar 4 at 2:10











          • @JohnHenckel : the question is around how to read/write without using OAuth token. And the answer above shows "How to read" without OAuth. Same can be used to write as well. Bottomline is "Not use OAuth".

            – Ankush
            Mar 5 at 8:01











          • you are correct! sorry my bad, removed my downvote

            – John Henckel
            Mar 8 at 16:21


















          0














          Based from this documentation, when your application requests public data, the request doesn't need to be authorized, but does need to be accompanied by an identifier, such as an API key.




          Every request your application sends to the Google Sheets API needs to identify your application to Google. There are two ways to identify your application: using an OAuth 2.0 token (which also authorizes the request) and/or using the application's API key. Here's how to determine which of those options to use:



          • If the request requires authorization (such as a request for an individual's private data), then the application must provide an OAuth 2.0 token with the request. The application may also provide the API key, but it doesn't have to.

          • If the request doesn't require authorization (such as a request for public data), then the application must provide either the API key or an OAuth 2.0 token, or both—whatever option is most convenient for you.



          However, there are some scopes which require OAuth authorization. Check this link: Access Google spreadsheet API without Oauth token.






          share|improve this answer























          • How to send the API Key in the form of Java code? A Curl request or using Google API. Any example would help

            – Ankush
            May 9 '18 at 10:08


















          0














          Using API key, you can read from google sheets, but only if the sheet is shared with public.



          However to write to google sheets, you must you OAuth. See this link.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50230112%2fread-write-google-sheet-via-server-without-using-oauth%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            After some research, Credential object from google-oath-client module can help. Download the .p12 file from the google account. Code for reading a google sheet without OAUth prompt below. This can also be used to write or append sheets with some modification :



            package com.mycomp;

            import com.google.api.client.auth.oauth2.Credential;
            import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
            import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
            import com.google.api.client.http.HttpTransport;
            import com.google.api.client.http.javanet.NetHttpTransport;
            import com.google.api.client.json.JsonFactory;
            import com.google.api.client.json.gson.GsonFactory;
            import com.google.api.services.sheets.v4.Sheets;
            import com.google.api.services.sheets.v4.SheetsScopes;
            import com.google.api.services.sheets.v4.model.ValueRange;
            import com.nm.vernacular.services.SpreadSheetsService;
            import org.slf4j.Logger;
            import org.slf4j.LoggerFactory;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.stereotype.Service;

            import java.io.File;
            import java.io.IOException;
            import java.net.URISyntaxException;
            import java.net.URL;
            import java.security.GeneralSecurityException;
            import java.util.Collections;
            import java.util.LinkedList;
            import java.util.List;

            /**
            * Created by ankushgupta & modified for SO.
            */

            public class GoogleSheetsReader

            private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
            private static final String KEY_FILE_LOCATION = "<Name of p12 file>.p12";
            private static final String SERVICE_ACCOUNT_EMAIL = "<email of google service account>";
            private static final String APPLICATION_NAME = "Google Sheets API";

            private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSheetsReader.class);

            /**
            * Global instance of the scopes required by this quickstart.
            * If modifying these scopes, delete your previously saved credentials/ folder.
            */
            private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);

            /**
            * Creates an authorized Credential object.
            * @return An authorized Credential object.
            * @throws IOException If there is no client_secret.
            */
            private Credential getCredentials() throws URISyntaxException, IOException, GeneralSecurityException
            //Reading Key File
            URL fileURL = GoogleSheetsReader.class.getClassLoader().getResource(KEY_FILE_LOCATION);
            // Initializes an authorized analytics service object.
            if(fileURL==null)
            fileURL = (new File("/resources/"+ KEY_FILE_LOCATION)).toURI().toURL();

            // Construct a GoogleCredential object with the service account email
            // and p12 file downloaded from the developer console.
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            return new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountPrivateKeyFromP12File(new File(fileURL.toURI()))
            .setServiceAccountScopes(SCOPES)
            .build();


            @Override
            public List<Object[]> readSheet(String nameAndRange, String key, int[] returnRange) throws GeneralSecurityException, IOException
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            final String spreadsheetId = key;
            final String range = nameAndRange;
            try
            Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials())
            .setApplicationName(APPLICATION_NAME)
            .build();

            ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
            List<List<Object>> values = response.getValues();

            int a = returnRange.length;
            List<Object[]> result = new LinkedList<>();

            if (values == null catch(Exception ex)
            LOGGER.error("Exception while reading google sheet", ex);
            finally


            return null;


            public static void main(String[] args)
            GoogleSheetsReader reader = new GoogleSheetsReader();
            reader.readSheet("<Sheet Name>!A2:B", "<sheets key from URL>", new int[]0, 1);







            share|improve this answer

























            • This does not answer the question. The OP is asking how to WRITE to the google sheet without using OAuth.

              – John Henckel
              Mar 4 at 2:10











            • @JohnHenckel : the question is around how to read/write without using OAuth token. And the answer above shows "How to read" without OAuth. Same can be used to write as well. Bottomline is "Not use OAuth".

              – Ankush
              Mar 5 at 8:01











            • you are correct! sorry my bad, removed my downvote

              – John Henckel
              Mar 8 at 16:21















            1














            After some research, Credential object from google-oath-client module can help. Download the .p12 file from the google account. Code for reading a google sheet without OAUth prompt below. This can also be used to write or append sheets with some modification :



            package com.mycomp;

            import com.google.api.client.auth.oauth2.Credential;
            import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
            import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
            import com.google.api.client.http.HttpTransport;
            import com.google.api.client.http.javanet.NetHttpTransport;
            import com.google.api.client.json.JsonFactory;
            import com.google.api.client.json.gson.GsonFactory;
            import com.google.api.services.sheets.v4.Sheets;
            import com.google.api.services.sheets.v4.SheetsScopes;
            import com.google.api.services.sheets.v4.model.ValueRange;
            import com.nm.vernacular.services.SpreadSheetsService;
            import org.slf4j.Logger;
            import org.slf4j.LoggerFactory;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.stereotype.Service;

            import java.io.File;
            import java.io.IOException;
            import java.net.URISyntaxException;
            import java.net.URL;
            import java.security.GeneralSecurityException;
            import java.util.Collections;
            import java.util.LinkedList;
            import java.util.List;

            /**
            * Created by ankushgupta & modified for SO.
            */

            public class GoogleSheetsReader

            private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
            private static final String KEY_FILE_LOCATION = "<Name of p12 file>.p12";
            private static final String SERVICE_ACCOUNT_EMAIL = "<email of google service account>";
            private static final String APPLICATION_NAME = "Google Sheets API";

            private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSheetsReader.class);

            /**
            * Global instance of the scopes required by this quickstart.
            * If modifying these scopes, delete your previously saved credentials/ folder.
            */
            private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);

            /**
            * Creates an authorized Credential object.
            * @return An authorized Credential object.
            * @throws IOException If there is no client_secret.
            */
            private Credential getCredentials() throws URISyntaxException, IOException, GeneralSecurityException
            //Reading Key File
            URL fileURL = GoogleSheetsReader.class.getClassLoader().getResource(KEY_FILE_LOCATION);
            // Initializes an authorized analytics service object.
            if(fileURL==null)
            fileURL = (new File("/resources/"+ KEY_FILE_LOCATION)).toURI().toURL();

            // Construct a GoogleCredential object with the service account email
            // and p12 file downloaded from the developer console.
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            return new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountPrivateKeyFromP12File(new File(fileURL.toURI()))
            .setServiceAccountScopes(SCOPES)
            .build();


            @Override
            public List<Object[]> readSheet(String nameAndRange, String key, int[] returnRange) throws GeneralSecurityException, IOException
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            final String spreadsheetId = key;
            final String range = nameAndRange;
            try
            Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials())
            .setApplicationName(APPLICATION_NAME)
            .build();

            ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
            List<List<Object>> values = response.getValues();

            int a = returnRange.length;
            List<Object[]> result = new LinkedList<>();

            if (values == null catch(Exception ex)
            LOGGER.error("Exception while reading google sheet", ex);
            finally


            return null;


            public static void main(String[] args)
            GoogleSheetsReader reader = new GoogleSheetsReader();
            reader.readSheet("<Sheet Name>!A2:B", "<sheets key from URL>", new int[]0, 1);







            share|improve this answer

























            • This does not answer the question. The OP is asking how to WRITE to the google sheet without using OAuth.

              – John Henckel
              Mar 4 at 2:10











            • @JohnHenckel : the question is around how to read/write without using OAuth token. And the answer above shows "How to read" without OAuth. Same can be used to write as well. Bottomline is "Not use OAuth".

              – Ankush
              Mar 5 at 8:01











            • you are correct! sorry my bad, removed my downvote

              – John Henckel
              Mar 8 at 16:21













            1












            1








            1







            After some research, Credential object from google-oath-client module can help. Download the .p12 file from the google account. Code for reading a google sheet without OAUth prompt below. This can also be used to write or append sheets with some modification :



            package com.mycomp;

            import com.google.api.client.auth.oauth2.Credential;
            import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
            import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
            import com.google.api.client.http.HttpTransport;
            import com.google.api.client.http.javanet.NetHttpTransport;
            import com.google.api.client.json.JsonFactory;
            import com.google.api.client.json.gson.GsonFactory;
            import com.google.api.services.sheets.v4.Sheets;
            import com.google.api.services.sheets.v4.SheetsScopes;
            import com.google.api.services.sheets.v4.model.ValueRange;
            import com.nm.vernacular.services.SpreadSheetsService;
            import org.slf4j.Logger;
            import org.slf4j.LoggerFactory;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.stereotype.Service;

            import java.io.File;
            import java.io.IOException;
            import java.net.URISyntaxException;
            import java.net.URL;
            import java.security.GeneralSecurityException;
            import java.util.Collections;
            import java.util.LinkedList;
            import java.util.List;

            /**
            * Created by ankushgupta & modified for SO.
            */

            public class GoogleSheetsReader

            private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
            private static final String KEY_FILE_LOCATION = "<Name of p12 file>.p12";
            private static final String SERVICE_ACCOUNT_EMAIL = "<email of google service account>";
            private static final String APPLICATION_NAME = "Google Sheets API";

            private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSheetsReader.class);

            /**
            * Global instance of the scopes required by this quickstart.
            * If modifying these scopes, delete your previously saved credentials/ folder.
            */
            private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);

            /**
            * Creates an authorized Credential object.
            * @return An authorized Credential object.
            * @throws IOException If there is no client_secret.
            */
            private Credential getCredentials() throws URISyntaxException, IOException, GeneralSecurityException
            //Reading Key File
            URL fileURL = GoogleSheetsReader.class.getClassLoader().getResource(KEY_FILE_LOCATION);
            // Initializes an authorized analytics service object.
            if(fileURL==null)
            fileURL = (new File("/resources/"+ KEY_FILE_LOCATION)).toURI().toURL();

            // Construct a GoogleCredential object with the service account email
            // and p12 file downloaded from the developer console.
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            return new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountPrivateKeyFromP12File(new File(fileURL.toURI()))
            .setServiceAccountScopes(SCOPES)
            .build();


            @Override
            public List<Object[]> readSheet(String nameAndRange, String key, int[] returnRange) throws GeneralSecurityException, IOException
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            final String spreadsheetId = key;
            final String range = nameAndRange;
            try
            Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials())
            .setApplicationName(APPLICATION_NAME)
            .build();

            ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
            List<List<Object>> values = response.getValues();

            int a = returnRange.length;
            List<Object[]> result = new LinkedList<>();

            if (values == null catch(Exception ex)
            LOGGER.error("Exception while reading google sheet", ex);
            finally


            return null;


            public static void main(String[] args)
            GoogleSheetsReader reader = new GoogleSheetsReader();
            reader.readSheet("<Sheet Name>!A2:B", "<sheets key from URL>", new int[]0, 1);







            share|improve this answer















            After some research, Credential object from google-oath-client module can help. Download the .p12 file from the google account. Code for reading a google sheet without OAUth prompt below. This can also be used to write or append sheets with some modification :



            package com.mycomp;

            import com.google.api.client.auth.oauth2.Credential;
            import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
            import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
            import com.google.api.client.http.HttpTransport;
            import com.google.api.client.http.javanet.NetHttpTransport;
            import com.google.api.client.json.JsonFactory;
            import com.google.api.client.json.gson.GsonFactory;
            import com.google.api.services.sheets.v4.Sheets;
            import com.google.api.services.sheets.v4.SheetsScopes;
            import com.google.api.services.sheets.v4.model.ValueRange;
            import com.nm.vernacular.services.SpreadSheetsService;
            import org.slf4j.Logger;
            import org.slf4j.LoggerFactory;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.stereotype.Service;

            import java.io.File;
            import java.io.IOException;
            import java.net.URISyntaxException;
            import java.net.URL;
            import java.security.GeneralSecurityException;
            import java.util.Collections;
            import java.util.LinkedList;
            import java.util.List;

            /**
            * Created by ankushgupta & modified for SO.
            */

            public class GoogleSheetsReader

            private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
            private static final String KEY_FILE_LOCATION = "<Name of p12 file>.p12";
            private static final String SERVICE_ACCOUNT_EMAIL = "<email of google service account>";
            private static final String APPLICATION_NAME = "Google Sheets API";

            private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSheetsReader.class);

            /**
            * Global instance of the scopes required by this quickstart.
            * If modifying these scopes, delete your previously saved credentials/ folder.
            */
            private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);

            /**
            * Creates an authorized Credential object.
            * @return An authorized Credential object.
            * @throws IOException If there is no client_secret.
            */
            private Credential getCredentials() throws URISyntaxException, IOException, GeneralSecurityException
            //Reading Key File
            URL fileURL = GoogleSheetsReader.class.getClassLoader().getResource(KEY_FILE_LOCATION);
            // Initializes an authorized analytics service object.
            if(fileURL==null)
            fileURL = (new File("/resources/"+ KEY_FILE_LOCATION)).toURI().toURL();

            // Construct a GoogleCredential object with the service account email
            // and p12 file downloaded from the developer console.
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            return new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountPrivateKeyFromP12File(new File(fileURL.toURI()))
            .setServiceAccountScopes(SCOPES)
            .build();


            @Override
            public List<Object[]> readSheet(String nameAndRange, String key, int[] returnRange) throws GeneralSecurityException, IOException
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            final String spreadsheetId = key;
            final String range = nameAndRange;
            try
            Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials())
            .setApplicationName(APPLICATION_NAME)
            .build();

            ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
            List<List<Object>> values = response.getValues();

            int a = returnRange.length;
            List<Object[]> result = new LinkedList<>();

            if (values == null catch(Exception ex)
            LOGGER.error("Exception while reading google sheet", ex);
            finally


            return null;


            public static void main(String[] args)
            GoogleSheetsReader reader = new GoogleSheetsReader();
            reader.readSheet("<Sheet Name>!A2:B", "<sheets key from URL>", new int[]0, 1);








            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 8 at 16:20









            John Henckel

            3,51913246




            3,51913246










            answered May 15 '18 at 6:43









            AnkushAnkush

            77112




            77112












            • This does not answer the question. The OP is asking how to WRITE to the google sheet without using OAuth.

              – John Henckel
              Mar 4 at 2:10











            • @JohnHenckel : the question is around how to read/write without using OAuth token. And the answer above shows "How to read" without OAuth. Same can be used to write as well. Bottomline is "Not use OAuth".

              – Ankush
              Mar 5 at 8:01











            • you are correct! sorry my bad, removed my downvote

              – John Henckel
              Mar 8 at 16:21

















            • This does not answer the question. The OP is asking how to WRITE to the google sheet without using OAuth.

              – John Henckel
              Mar 4 at 2:10











            • @JohnHenckel : the question is around how to read/write without using OAuth token. And the answer above shows "How to read" without OAuth. Same can be used to write as well. Bottomline is "Not use OAuth".

              – Ankush
              Mar 5 at 8:01











            • you are correct! sorry my bad, removed my downvote

              – John Henckel
              Mar 8 at 16:21
















            This does not answer the question. The OP is asking how to WRITE to the google sheet without using OAuth.

            – John Henckel
            Mar 4 at 2:10





            This does not answer the question. The OP is asking how to WRITE to the google sheet without using OAuth.

            – John Henckel
            Mar 4 at 2:10













            @JohnHenckel : the question is around how to read/write without using OAuth token. And the answer above shows "How to read" without OAuth. Same can be used to write as well. Bottomline is "Not use OAuth".

            – Ankush
            Mar 5 at 8:01





            @JohnHenckel : the question is around how to read/write without using OAuth token. And the answer above shows "How to read" without OAuth. Same can be used to write as well. Bottomline is "Not use OAuth".

            – Ankush
            Mar 5 at 8:01













            you are correct! sorry my bad, removed my downvote

            – John Henckel
            Mar 8 at 16:21





            you are correct! sorry my bad, removed my downvote

            – John Henckel
            Mar 8 at 16:21













            0














            Based from this documentation, when your application requests public data, the request doesn't need to be authorized, but does need to be accompanied by an identifier, such as an API key.




            Every request your application sends to the Google Sheets API needs to identify your application to Google. There are two ways to identify your application: using an OAuth 2.0 token (which also authorizes the request) and/or using the application's API key. Here's how to determine which of those options to use:



            • If the request requires authorization (such as a request for an individual's private data), then the application must provide an OAuth 2.0 token with the request. The application may also provide the API key, but it doesn't have to.

            • If the request doesn't require authorization (such as a request for public data), then the application must provide either the API key or an OAuth 2.0 token, or both—whatever option is most convenient for you.



            However, there are some scopes which require OAuth authorization. Check this link: Access Google spreadsheet API without Oauth token.






            share|improve this answer























            • How to send the API Key in the form of Java code? A Curl request or using Google API. Any example would help

              – Ankush
              May 9 '18 at 10:08















            0














            Based from this documentation, when your application requests public data, the request doesn't need to be authorized, but does need to be accompanied by an identifier, such as an API key.




            Every request your application sends to the Google Sheets API needs to identify your application to Google. There are two ways to identify your application: using an OAuth 2.0 token (which also authorizes the request) and/or using the application's API key. Here's how to determine which of those options to use:



            • If the request requires authorization (such as a request for an individual's private data), then the application must provide an OAuth 2.0 token with the request. The application may also provide the API key, but it doesn't have to.

            • If the request doesn't require authorization (such as a request for public data), then the application must provide either the API key or an OAuth 2.0 token, or both—whatever option is most convenient for you.



            However, there are some scopes which require OAuth authorization. Check this link: Access Google spreadsheet API without Oauth token.






            share|improve this answer























            • How to send the API Key in the form of Java code? A Curl request or using Google API. Any example would help

              – Ankush
              May 9 '18 at 10:08













            0












            0








            0







            Based from this documentation, when your application requests public data, the request doesn't need to be authorized, but does need to be accompanied by an identifier, such as an API key.




            Every request your application sends to the Google Sheets API needs to identify your application to Google. There are two ways to identify your application: using an OAuth 2.0 token (which also authorizes the request) and/or using the application's API key. Here's how to determine which of those options to use:



            • If the request requires authorization (such as a request for an individual's private data), then the application must provide an OAuth 2.0 token with the request. The application may also provide the API key, but it doesn't have to.

            • If the request doesn't require authorization (such as a request for public data), then the application must provide either the API key or an OAuth 2.0 token, or both—whatever option is most convenient for you.



            However, there are some scopes which require OAuth authorization. Check this link: Access Google spreadsheet API without Oauth token.






            share|improve this answer













            Based from this documentation, when your application requests public data, the request doesn't need to be authorized, but does need to be accompanied by an identifier, such as an API key.




            Every request your application sends to the Google Sheets API needs to identify your application to Google. There are two ways to identify your application: using an OAuth 2.0 token (which also authorizes the request) and/or using the application's API key. Here's how to determine which of those options to use:



            • If the request requires authorization (such as a request for an individual's private data), then the application must provide an OAuth 2.0 token with the request. The application may also provide the API key, but it doesn't have to.

            • If the request doesn't require authorization (such as a request for public data), then the application must provide either the API key or an OAuth 2.0 token, or both—whatever option is most convenient for you.



            However, there are some scopes which require OAuth authorization. Check this link: Access Google spreadsheet API without Oauth token.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 8 '18 at 16:45









            abielitaabielita

            9,6872940




            9,6872940












            • How to send the API Key in the form of Java code? A Curl request or using Google API. Any example would help

              – Ankush
              May 9 '18 at 10:08

















            • How to send the API Key in the form of Java code? A Curl request or using Google API. Any example would help

              – Ankush
              May 9 '18 at 10:08
















            How to send the API Key in the form of Java code? A Curl request or using Google API. Any example would help

            – Ankush
            May 9 '18 at 10:08





            How to send the API Key in the form of Java code? A Curl request or using Google API. Any example would help

            – Ankush
            May 9 '18 at 10:08











            0














            Using API key, you can read from google sheets, but only if the sheet is shared with public.



            However to write to google sheets, you must you OAuth. See this link.






            share|improve this answer



























              0














              Using API key, you can read from google sheets, but only if the sheet is shared with public.



              However to write to google sheets, you must you OAuth. See this link.






              share|improve this answer

























                0












                0








                0







                Using API key, you can read from google sheets, but only if the sheet is shared with public.



                However to write to google sheets, you must you OAuth. See this link.






                share|improve this answer













                Using API key, you can read from google sheets, but only if the sheet is shared with public.



                However to write to google sheets, you must you OAuth. See this link.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 4 at 2:14









                John HenckelJohn Henckel

                3,51913246




                3,51913246



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50230112%2fread-write-google-sheet-via-server-without-using-oauth%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                    Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                    How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page