gcal.jpg
Cover image for joseph_appsmith

Joseph Petty Verified userVerified user

Sr. Developer Advocate

Appsmith

Integrating with the Google Calendar API

Goal

Integrate Appsmith with the Google Calendar API to list and create events. 

Prerequisites

  • An Appsmith Account

  • A Google Account

Overview

This tutorial will cover:

  • Creating a Project and enabling the Google Calendar API
  • Creating OAuth2 credentials
  • Saving the credentials as an Authenticated API Datasource in Appsmith
  • Listing and creating events from Appsmith
  1. Create a Google Project and Enabling the Calendar API

    Start out by going to your Google Cloud Console and creating a new project. Enter a name for the project, and click create. 

    create google project

    Note: It will take a few seconds for the project to be created, so after you click Create, you may see a different project still selected than the one you just created. Make sure you stop and select the new project before proceeding to the next step. 

    Once the project is created and selected, 

    1. click the APIs & Services link, then on the next page + Enable APIs and Services.
    2. Search for "Calendar", select Google Calendar API
    3. Click Enable
    enable google cal api

    The Calendar API is now enabled for your project. However, this step does not actually create an API key or token. To use the API, you must first create a new set of credentials. 

  2. Create OAuth2 Credentials

    Next, Select Credentials from the left sidebar, then + Create Credentials, and select OAuth2 Client ID

    create creds

    On the next screen, enter the following settings:

    1. Application Type : Web Application
    2. Name: enter a name for the credentials
    3. Authorized redirect URIs: https://app.appsmith.com/api/v1/datasources/authorize
    4. Click CREATE
    create OAuth creds

     

    Leave the next screen open so you can copy the new Client ID and Secret. 

  3. Save Credentials to Appsmith Datasource

    Now, open the Appsmith app where you want to add the Google Calendar datasource. Click the Data icon on the left sidebar, and add a new Authenticated REST API. 

    Enter the following settings:

    URL https://www.googleapis.com
    Authentication Type OAuth2
    Grant Type Authorization Code
    Add Access Token To Request Header
    Header prefix Bearer
    Acces token URL https://oauth2.googleapis.com/token
    Client ID YOUR_CLIENT_ID
    Client secret YOUR_CLIENT_SECRET
    Scopes https://www.googleapis.com/auth/calendar.events
    Client Authentication Send client credentials in body
    Authorization URL https://accounts.google.com/o/oauth2/v2/auth
    Custom Authentication Parameter #1 access_type : offline
    Custom Authentication Parameter #2 prompt : consent

    Note the green lock icon on the Client Secret field. This indicates that the value will be securely encrypted on the Appsmith server, and never sent back to end-users in the application. Even you as the admin will not be able to view it again from Appsmith, but the secret can be copied again from the Google Console later. 

     

    save datasource

     

    Click Save & Authorize. You should be directed to select your Google account, then shown the consent screen. 

    consent screen

    Click Allow, and you should be redirected back to Appsmith and see a toast message that the connection was successful. 

    Your datasource is now connected and ready to use. 

  4. Listing Events

    Next, create a new API under the new Google Calendar datasource. If you're still viewing the datasource, you can use the + New API button in the top right. Or go to the Queries pane and click + , then select the datasource. You can also use cmd-shift-+ (mac) or ctrl-shift-+ (windows) to create a new API. 

    Name the new API getEvents and set the endpoint to :

    /calendar/v3/calendars/primary/events

    Click Run and you should get back a 200 response with events from your primary Google Calendar. The events are nested in the response, at getEvents.data.items

    getEvents

    Switch over to the UI tab and drag in a List Widget. Then, in the List Widget properties under Data, set the Items to:

    {{getEvents.data.items}}
    list events

    Then update the two text widgets on the first row of the list to display the currentItem.summary and currentItem.start.dateTime. You can delete the default Image widget that was included with the List. 

    list binding

    You should now see a list of events from your calendar, starting with the oldest event in your account. 

    Next, add a date filter by dragging in two DatePicker widgets, and name them date_start and date_end. In both widgets, set the onDateSelected Event to run the getEvents query. 

    getEvents trigger

     

    Now just update the getEvents URL and bind the selected dates to the query parameters. The Google Calendar API uses a minTime and maxTime parameter to filter events. So update the URL with: 

    /calendar/v3/calendars/primary/events?timeMin={{date_start.selectedDate}}&timeMax={{date_end.selectedDate}}&&singleEvents=true

    The singleEvents=true will expand recurring events to show each instance as a new record. 

    date filter


    Now head back to the UI and test it out. You should now be able to filter events by the start and end date and see the results update as you change the dates. 

     

  5. Creating an Event Form

    Next, add a form for creating new events. Start by adding an Icon Button and select the plus icon. Then set its onClick action to Show Modal and select + New Modal

    open modal

    Drag a JSONForm into the new Modal. You can delete the two buttons that came with the modal since the JSONForm has its own Reset and Submit buttons. 

    JSONForm

    In the JSONForm's properties under Data, click the JS toggle and enter this for the Source data:

    {{
    {
        "summary": "",
        "start": {
            "dateTime": "",
            "timeZone": moment.tz.guess()
        },
        "end": {
            "dateTime": "",
            "timeZone": moment.tz.guess()
        },
        "description": "",
        "attendees": [{ "email": appsmith.user.email }]
    }
    }}

    Notice how the start and end dates are objects, containing the datetime and a timezone. This is the format required by the Google Calendar API. The moment.tz.guess() snippet will pre-fill the timezone value for the user. 

    Next, update the settings for both of the timezone fields. The settings are nested, just the data. So first go into the settings for the start field, then into its timezone

    column settings

    Once you're inside the TimeZone column settings, inside the Start column:

    1. Change the Field Type to Select
    2. Change the Select Options to: {{moment.tz.names().map(o=>({label:o,value:o}))}}
    3. Back out of the column settings and repeat step 1-2 on the end.timezone column. 
    timezones select list

    You should now have a dropdown of timezones in the JSONForm. 

  6. Saving the Event Form

    Now create a new API under the Google Calendar datasource, and name it createEvent

    Set the method to POST, and set the URL to:

    /calendar/v3/calendars/primary/events?text={{JSONForm1.formData.summary}}&sendUpdates=all

    The sendUpdates=all parameter will send email notifications to all attendees. 

    Next, set the body to:

    {{
    JSONForm1.formData
    }}

    Now go back to the UI and enter a start and end date, and a summary, so that you can see it in the API body. Click Run on the createEvent API and you should get back a 200 response with the event details. 

    createEvent

    Lastly, connect the API to the JSONForm. Start out by selecting the JSONForm and go to the Events section in the widget properties. 

    1. Set the onSubmit Action to run the createEvent API
    2. Set the onSuccess callback to run the getEvents API 
    3. In the getEvents callback, update the placeholder function with: closeModal(Modal1.name);


     

    jsonform submit


    Now the Submit button should also refresh the List Widget and close the Modal. 

    That's it! You can now list and create events using the Google Calendar API. See the Google Calendar API docs for more info on editing and deleting events. 

Conclusion

Integrating with the Google Calendar API in Appsmith is easy once you have all the correct settings for the datasource. With this guide, you can quickly get started with listing and creating events from Appsmith, using an Authenticated API Datasource to securely store the credentials on your own self-hosted Appsmith server. For more API tutorials, check out the portal content by integrations page. 

darasabahi public View darasabahi's profile
Sat, 08/17/2024 - 03:45

I created a data source via a REST API connected to the Google Calendar API in Appsmith. As mentioned, however, the data source keeps asking me to reauthorize every few days. It is getting quite boring

Joseph Petty Verified userVerified user staff View joseph_appsmith's profile
Mon, 08/19/2024 - 11:51

Hi darasabahi, it sounds like your datasource is missing the access_type : offline custom header. It will work without this, but then the refresh token fails. 

Please try reauthorizing the datasource and add the access_type : offline header under the custom auth headers section.