Accessing Google Calendar data using Google Calendar API
- Digital Engineering
Accessing Google Calendar data using Google Calendar API
In this article, we will create a simple spring boot application for Authorization and fetching data from Google Calendar API. We will authenticate users with Google OAuth 2.0 and use the authentication token to call Google Calendar API to retrieve users calendar data.
WHY DO WE NEED GOOGLE CALENDAR API
The Calendar API lets us integrate our app with Google Calendar, creating new ways for us to engage your users. Using google calendar API we can
- Create a event in users google calendar
- Read all events between two dates and also filter calendar events based on any particular keyword.
- Update event title, date, description, attendees etc.
- Delete event and more.
GETTING STARTED WITH GOOGLE CALENDAR API
The following steps would guide you through setting up a project on google cloud console, building a simple spring web app that prompts the user to provide permissions for accessing the Google Calendar.
1. Create a project on google cloud console
Firstly, create a new project or you can use existing project. To create a new project open Google Cloud Console and login with your Google account. After successful login click on new project. Enter project name and create the project.
2. Enable Google Calendar API
After creating a project you have to enable Google Calendar API. To enable click on “Enable APIs and Services” and search for Google calendar API, Click on Google Calendar API from search result and Enable it.
3. OAuth Consent Screen
Consent appears to the users when they try to login into any application using google. To make consent screen for your application click on “OAuth Consent Screen”, select External and create the consent screen.
Fill all required details in the next screen. These details will be visible to users when they will try to login using google.
Add email, profile and Google calendar API scopes and click on Save and Continue button. Calendar Scope is very neccessary, without calendar scope you won’t be able to access the google calendar APIs
4. Creating credentials(API key & API secret)
To create credentails, click on CREATE CREDENTIALS button and select OAuth Client ID from the dropdown.
Select web application in application type dropdown because we are creating a webaplication. You can create multiple credentials if required. Enter name of web application and also add Authorized redirect URI –
1 |
http://localhost:8080/login/oauth2/code/google |
Finally, we have created our application credentials and save Client ID and Client Secret for future use.
Google cloud console setup is completed, now create a spring boot project.
5. Create a spring boot application to access Google Calendar data
Create a Spring Project from start.spring.io with the following dependencies. If you have already created a spring starter project then paste this code into your pom.xml file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-calendar</artifactId> <version>v3-rev224-1.22.0</version> </dependency> |
Now define google client id, client secret, redirect uri and scopes in application.properties file.
1 2 3 4 |
spring.security.oauth2.client.registration.google.client-id=********************************************************* spring.security.oauth2.client.registration.google.client-secret=***************************************************** spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google spring.security.oauth2.client.registration.google.scope=email,profile,https://www.googleapis.com/auth/calendar |
Now create a SecurityConfiguration class and define oauth2Login for authentication.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private CustomOAuth2UserService oauthUserService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() .anyRequest().authenticated() .and() .oauth2Login() .userInfoEndpoint().userService(oauthUserService); } } |
Now we can make a controller to access google calendar using google calendar api. We need Google Oauth access token to call the google calendar API. For that we have made a CustomOAuth2User with a token parameter which can we accessed through Authentication Principal.
Access token must have the google calendar scopes otherwise you won’t be able to access the google calendar APIs(We have already defined scopes in application.properties file).
Fetching google calendar events (Google doc link)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
@RequestMapping(value = "/events") public ResponseEntity<String> getEvents(@AuthenticationPrincipal OAuth2User oAuth2User, @RequestParam(value = "sdate") String sdate, @RequestParam(value = "edate") String edate, @RequestParam(value = "q") String q) { com.google.api.services.calendar.model.Events eventList; String message; try { CustomOAuth2User customOAuth2User = (CustomOAuth2User)oAuth2User; String token = customOAuth2User.getToken(); GoogleCredential credential = new GoogleCredential().setAccessToken(token); final DateTime date1 = new DateTime(sdate + "T00:00:00"); final DateTime date2 = new DateTime(edate + "T23:59:59"); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); Calendar service = new Calendar.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); Events events = service.events(); eventList = events.list("primary").setTimeZone("Asia/Kolkata").setTimeMin(date1).setTimeMax(date2).setQ(q).execute(); message = eventList.getItems().toString(); System.out.println("My:" + eventList.getItems()); } catch (Exception e) { message = "Exception while handling OAuth2 callback (" + e.getMessage() + ")." + " Redirecting to google connection status page."; } return new ResponseEntity<>(message, HttpStatus.OK); } |
In this controller we have 3 query parameters sdate, edate and q. These all parameters will help in filtering the events. Parameter sdate(Start date) and edate(End Date) will only return the events falling between both dates. QUery prameter q is free text search terms to find events that match input text in any field like summary, description.
In this first we have created an object of Calendar Builder and used that object to fetch the events data.
This same calendar builder object can be used to create, update and delete the events.
6. Test Application
That’s it!, now run your application and open http://localhost:8080/events?sdate=2022-01-01&edate=2022-03-23&q= . You will be redirected to google login screen, enter your email and password, after successful login you will be redirected to –
Click on continue, now you will be redirected to another screen where you will be asked to whether to allow the application to see, edit the google calendar events or not.
Click on Continue, now you can see all the google calendar events between the date that you have passed in the url.
Conclusion
In this article, we learned how to use Google Calendar API with Spring Boot and read events from Google Calendar. Similarly other Google APIs can be used and integrated. I really hope you enjoyed it and had fun reading it.😊
Stay safe.
Related content
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s