Last Updated on June 10, 2025 by KnownSense
In this tutorial, you’ll learn how to read Google Docs with Spring Boot application using google docs api. We’ll guide you through setting up OAuth 2.0, accessing the Docs API, and retrieving document data programmatically.
Create a Google Cloud project
In the Google Cloud console, go to menu > IAM & Admin > Create a Project.
Enter Project Name and Create.
Enable Google Drive API
In the google cloud console, again go to menu > APIs & Services > API Library
Search for google drive API and Enable it.
Configure the OAuth consent screen
In Google Cloud Console, go to Menu > Google Auth Platform > Branding > Get Started.
Enter the App Name and Support Email under App Information, then click Next.
Under Audience, select External and click Next.
Enter your Contact Email and click Next.
Review and accept the User Data Policy, then click Continue and Create.
Authorize credentials for a application
In Google Cloud Console, go to Menu > Google Auth Platform > Clients, click Create Client, choose Desktop app, and enter a name. Click Create.
Download the JSON file, rename it to credentials.json, and move it to your working directory.
Add Test Users
In Google Cloud Console, go to Menu > Google Auth Platform > Audience.
Under Test Users, click Add Users, enter the email ID you’ll use for testing, and click Save.
Create Spring boot project
Open start.spring.io select Java 17 and the latest Maven version. Fill in the project details like Group, Artifact, Name, and Description. Add dependencies: Spring Web and Spring Boot DevTools, then click Generate. Download and open the project, then add the following dependency to pom.xml:
<!-- mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.39.0</version>
</dependency>
<!-- mvnrepository.com/artifact/com.google.apis/google-api-services-docs -->
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-docs</artifactId>
<version>v1-rev61-1.25.0</version>
</dependency>
Create a service
Let’s create a service that sets up and returns an authenticated Docs service from the Google Docs API using OAuth 2.0
@Configuration
public class GoogleDocsConfig {
private static final String APPLICATION_NAME = "My Google Docs App";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = List.of(DocsScopes.DOCUMENTS);
@Bean
public Docs googleDocs() throws IOException, GeneralSecurityException {
// Establishes a secure HTTP connection for Google API client communication
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
//Loads Google OAuth 2.0 client ID and client secret from the credentials file
InputStream in = new ClassPathResource("credentials.json").getInputStream();
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Sets up OAuth 2.0 flow with specified scopes, credential storage, and offline access for refresh tokens
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File("tokens")))
.setAccessType("offline")
.build();
//Authorize the User and Store Credentials
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
// Build and Return the Google Docs Service
return new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
}
Here’s how the googleDocs() method works step-by-step during execution:
- Secure HTTP transport is created
GoogleNetHttpTransport.newTrustedTransport()sets up a secure connection to Google’s servers.- This is needed for all API calls.
- Load client secrets
credentials.jsonis read from the classpath (yourresourcesfolder).- This file contains your OAuth 2.0
client_idandclient_secretfrom the Google Cloud Console. - It’s used to identify your app to Google’s authorization server.
- Build authorization flow
GoogleAuthorizationCodeFlowhandles the OAuth process.- It’s configured with:
- The HTTP transport and JSON parser.
- The loaded
clientSecrets. - The list of
SCOPES(likeDocsScopes.DOCUMENTS). .setAccessType("offline"): requests a refresh token, so the app can access Google Docs without repeated logins..setDataStoreFactory(...): stores the user’s credentials (tokens) in a localtokens/folder so the user doesn’t have to log in every time.
- Start local web server
LocalServerReceiverruns a small HTTP server onlocalhost:8888.- After the user grants access, Google redirects the browser to this local server with the authorization code.
- Authorize user
AuthorizationCodeInstalledApp(...).authorize("user"):- Launches a browser window.
- Prompts the user to log in with their Google account and grant access.
- On success, receives the authorization code via the local server.
- Exchanges it for access and refresh tokens.
- Stores those tokens in
tokens/.
- Create Docs service
- A
Docsclient object is created and returned. - This object is authorized to call Google Docs API methods on behalf of the user (like reading or editing documents).
- A
Create a controller
Let’s create a controller that expose a endpoint to access the above service
@RestController
@RequestMapping("/docs")
public class DocsController {
private final Docs docsService;
public DocsController(Docs docsService) {
this.docsService = docsService;
}
@GetMapping("/read/{documentId}")
public String readDocument(@PathVariable String documentId) throws IOException {
Document doc = docsService.documents().get(documentId).execute();
return "Title: " + doc.getTitle();
}
}
Test the application
Build the project using the command mvn clean install, then run it with mvn spring-boot:run.
The first time you run it, a link will be displayed in the console prompting you to verify your account.
Open the link in a browser, complete the verification, and grant the necessary permissions.
Then, open the endpoint in your browser: http://localhost:8080/docs/read/{docId}.
Replace {docId} with the actual document ID to test the API.