Syncing Google Calendar via API explained
From time to time, it is required to do work with a 3rd party API.
In case you are working with Google Calendar API and happen to sync events into your server, you will need to keep your server and google server in sync – of course, only if you want to keep the user experience great.
How to do it
Google has pretty good was how to keep your data in sync.
The whole process consists of three steps:
- set up watching calendar via watcher (this guide does not explain that)
- initially sync all calendar data
- incrementally sync only changed data
Initially sync all calendar data
This is pretty straightforward.
https://developers.google.com/calendar/v3/reference/events/list
Repeatedly call the list
endpoint and retrieve all of the events available.
The very last paginated call will contain a key called nextSyncToken
which you will want to keep stored for the following incremental sync
Incrementally sync only changed data
Now, you do have all of the data synced and something changes in the calendar (the calendar data, events…etc).
You can set up watching of the calendar via push notification or you can repeatedly in a predefined period call the list
method to check, if something changed.
In this step you will want to use syncToken
parameter within the list
request.
What it will do is, it will return only modified data since last synchronization.
If you receive no data with the request, it means you are either having an error within building up your request 🙂 or there was no modified data.
If you do receive some data, it means something has changed in between and you should process that data.
Also keep in mind that there will be a new nextSyncToken
parameter returned from the request which you will want to store in order to get the modified data since the last request.
Keep in mind that the modified data can be paginated and thus the nextSyncToken
will be present only in the very last page of the paginated response.
Wrapping up
In this quick guide I explained how to keep calendar data from your server to google server in sync.
Sources:
- https://developers.google.com/calendar/v3/sync
- https://stackoverflow.com/a/55236385/2880184
- https://developers.google.com/calendar/v3/push
Credits:
- image: https://en.wikipedia.org/wiki/Google_Calendar