Placeholder
Blogs
On
April 14, 2025

Create Charts in Google Slides with Python API

Save time by using Python and the Google Slides API to automate chart creation in slide decks. This post shows how to generate a chart in Google Sheets, embed it into a Google Slides presentation, and keep it updated automatically. Say goodbye to manual chart updates and hello to a scalable, error-free workflow for data-driven presentations.

Create Charts in Google Slides with Python API

Manually adding charts to Google Slides is so last year. If you’re a developer tired of copy-pasting graphs into slide decks, this guide is for you. Imagine updating a spreadsheet and instantly seeing the charts in your presentation refresh with the new data — no more tedious manual updates. In this tutorial, we’ll walk through how to automate Google Slides chart creation using Python and the Google Slides API, so your slides are always up-to-date with minimal effort.

A chart created in Google Sheets can be embedded into a Google Slides presentation via the API. This means that instead of manually copying charts, developers can programmatically insert and update charts with Python. The result is an automated workflow where slide decks update with the latest data at the push of a script.

Why Automate Chart Creation in Google Slides?

Automating chart creation and updates in Google Slides offers several benefits for developers and teams:

  • Time-Saving: Stop spending hours every week updating slide decks. A Python script can generate and update charts in seconds.
  • Scalable and Repeatable: Whether it’s a weekly report or a sales deck for each client, automation scales effortlessly. Generate multiple presentations or charts without breaking a sweat.
  • Reduces Errors: Manual copying can introduce mistakes (missed updates, copy-paste errors). Automation ensures the data on your slides is accurate and consistent with your source.
  • Developer Happiness: Let’s face it – no one became a developer to manually format slides. By using the Google Slides API, you get to write code to handle the boring stuff and focus on more challenging tasks (or have an extra coffee ☕).

In short, by combining Google Slides, Google Sheets, and Python, you can create a mini "report generation" pipeline that turns raw data into polished charts on slides automatically. The Google Slides API supports any chart type you can create in Google Sheets (bar charts, line charts, pie charts, etc.) (Adding Charts to Your Slides), so you’re not limited in how you visualize your data.

Setting Up Your Environment and API Access

Before we dive into code, let’s make sure you have the necessary setup:

  • Google APIs Enabled: Go to the Google Cloud Console and enable both the Google Slides API and Google Sheets API for your project. These APIs allow your Python script to interact with Slides and Sheets.
  • Credentials (OAuth2 or Service Account): Set up authentication so your Python app can access the APIs. You can use an OAuth2 client ID (for a desktop app flow) or a service account. For development, the OAuth2 flow is straightforward – download your credentials.json from the Cloud Console and let the Python Google API client library handle the OAuth consent. For service accounts (automated server scripts), generate a key file (.json) and share your Google Drive items (the Slides and Sheets) with the service account email so it can access them.
  • Install Google API Client Library: Install the Python packages for Google APIs by running:
    pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
  • These libraries will help us authenticate and make calls to the Slides and Sheets APIs.
  • Required Scopes: When authenticating, request the scopes that allow editing Slides and Sheets. For example:
    SCOPES = [
       'https://www.googleapis.com/auth/presentations',    # Google Slides scope
       'https://www.googleapis.com/auth/spreadsheets'      # Google Sheets scope (read/write)
    ]
  • (If you only need to read data from Sheets, you could use the more restrictive read-only scope (Google for Developers), but in our case we’ll be writing charts and data.)
  • Identify Your Files: Have the IDs of the Google Slides presentation and Google Sheets spreadsheet you’ll be working with. You can find the IDs in the URLs (the long string in the share link). For example, in https://docs.google.com/presentation/d/**<ID>**/edit, the part in place of <ID> is the presentationId. Similarly, for the spreadsheet URL.

With that ready, you can build service client objects for Slides and Sheets. For instance, using a service account file:

import google.auth
from google.oauth2 import service_account
from googleapiclient.discovery import build

creds = service_account.Credentials.from_service_account_file(
   'path/to/your-service-account.json', scopes=SCOPES)
slides_service = build('slides', 'v1', credentials=creds)
sheets_service = build('sheets', 'v4', credentials=creds)

If using OAuth2 for a desktop app, you’d use InstalledAppFlow.from_client_secrets_file() to get creds instead. Either way, after this setup, you’ll have slides_service and sheets_service objects to call the API.

Step 1: Create a Chart in Google Sheets (with Python)

The first step is to have a chart in Google Sheets. The Google Slides API can only embed charts that already exist in a Google Sheet (Google for Developers). So we’ll programmatically create a chart in our spreadsheet using the Google Sheets API.

Prepare the Data: Make sure your spreadsheet has the data you want to visualize. You can manually input this data or use the Sheets API to fill it. For example, let's assume Sheet1 of our spreadsheet has a simple table of quarterly sales:

QuarterSalesQ1100Q2150Q3130Q4170

(If this data isn’t there yet, you can use sheets_service.spreadsheets().values().update(...) to add it, but we’ll skip those details for brevity.)

Add a Chart via Sheets API: Now, we use an AddChartRequest to create a chart based on that data. The chart will be created as an embedded chart object in the spreadsheet. Here’s a Python snippet to add a basic column chart to the spreadsheet:

# IDs for the spreadsheet and the sheet (tab) containing data
SPREADSHEET_ID = 'your-spreadsheet-id-here'
SOURCE_SHEET_ID = 0  # usually the first sheet; replace with actual ID if not 0.

# Define a request to add a column chart for range A1:B5 (Quarter vs Sales)
add_chart_request = {
   'addChart': {
       'chart': {
           'spec': {
               'title': 'Quarterly Sales',        # Chart title
               'basicChart': {
                   'chartType': 'COLUMN',         # Column chart (bar chart vertically)
                   'legendPosition': 'BOTTOM_LEGEND',
                   'axis': [
                       {'position': 'BOTTOM_AXIS', 'title': 'Quarter'},
                       {'position': 'LEFT_AXIS', 'title': 'Sales'}
                   ],
                   'domains': [{  # X-axis domain - the quarters (column A)
                       'domain': {
                           'sourceRange': {
                               'sources': [{
                                   'sheetId': SOURCE_SHEET_ID,
                                   'startRowIndex': 0, 'endRowIndex': 5,       # rows 1-5 (0-indexed)
                                   'startColumnIndex': 0, 'endColumnIndex': 1  # col A
                               }]
                           }
                       }
                   }],
                   'series': [{   # Y-axis series - the sales values (column B)
                       'series': {
                           'sourceRange': {
                               'sources': [{
                                   'sheetId': SOURCE_SHEET_ID,
                                   'startRowIndex': 0, 'endRowIndex': 5,       # rows 1-5
                                   'startColumnIndex': 1, 'endColumnIndex': 2  # col B
                               }]
                           }
                       },
                       'targetAxis': 'LEFT_AXIS'
                   }],
                   'headerCount': 1  # first row is headers (Quarter, Sales)
               }
           },
           'position': {'newSheet': True}  # place the chart on a new sheet/tab
       }
   }
}

# Send the request to add the chart
response = sheets_service.spreadsheets().batchUpdate(
   spreadsheetId=SPREADSHEET_ID,
   body={'requests': [add_chart_request]}
).execute()

# Get the new chart's ID from the response
chart_id = response['replies'][0]['addChart']['chart']['chartId']
print(f"Created chart with ID: {chart_id}")

Let’s unpack that:

  • We specify the chart type (COLUMN chart in this case) and the ranges for our domain (x-axis labels from column A) and series (y-axis values from column B).
  • We set position: newSheet: true to have the chart appear in its own sheet tab (makes it easy to manage).
  • After calling the batchUpdate, the API returns a response that includes the details of the added chart, including a generated chartId. We capture that chart_id – this is crucial, because we’ll need it to tell Google Slides which chart to embed.

At this point, our Google Sheets spreadsheet has a chart (e.g., “Quarterly Sales” chart). You can open the sheet in your browser to verify the chart was created if you want. Now, onto the Slides side of things!

Step 2: Insert the Chart into a Google Slides Presentation

With a chart available in Google Sheets, we can use the Google Slides API to insert that chart into a slide. Essentially, we’re going to tell Slides “take the chart with ID X from spreadsheet Y, and put it on slide Z.”

Prepare the Slide: You need a Google Slides presentation to insert into, and a specific slide within that presentation. This could be an existing presentation (like a template slide deck) or one you created on the fly. For this tutorial, let’s assume you have a presentation ready and want to add the chart to the first slide. We’ll fetch the first slide’s ID using the Slides API:

PRESENTATION_ID = 'your-slides-presentation-id-here'

# Get presentation details to find the first slide ID
pres = slides_service.presentations().get(presentationId=PRESENTATION_ID).execute()
first_slide_id = pres['slides'][0]['objectId']
print(f"First slide ID: {first_slide_id}")

Now we build a request to create the chart on that slide using a CreateSheetsChartRequest. We’ll specify:

  • The spreadsheetId (the Google Sheets file that has our chart).
  • The chartId of the chart we created in Step 1.
  • The pageObjectId of the slide where we want to place the chart.
  • Optionally, we can give the new chart shape an objectId in the presentation (so we can reference it later easily). Here we’ll call it "MyChart1".
  • Set the linkingMode to LINKED so that the chart stays linked to the Sheets data (allowing future updates) (Google for Developers) (Google for Developers).
  • (Optional) Set size and transform: here we define a size (4 million EMUs ~ 4 inches for width/height) and position (translateX/Y) so the chart is nicely placed and scaled on the slide. You can tweak these values or omit them for default placement.

Code to insert the Sheets chart into Slides:

# Define a request to embed the Sheets chart into the slide
create_chart_request = {
   'createSheetsChart': {
       'spreadsheetId': SPREADSHEET_ID,
       'chartId': chart_id,            # from Step 1
       'linkingMode': 'LINKED',       # keep it linked to Sheets
       'objectId': 'MyChart1',        # name for the chart element in Slides
       'elementProperties': {
           'pageObjectId': first_slide_id,     # which slide to place it on
           'size': {
               'width': {'magnitude': 4000000, 'unit': 'EMU'},
               'height': {'magnitude': 4000000, 'unit': 'EMU'}
           },
           'transform': {
               'scaleX': 1, 'scaleY': 1,
               'translateX': 100000, 'translateY': 100000, 'unit': 'EMU'
           }
       }
   }
}

# Execute the request to add the chart to the slide
slides_service.presentations().batchUpdate(
   presentationId=PRESENTATION_ID,
   body={'requests': [create_chart_request]}
).execute()

print("Added chart to Google Slides presentation!")

Boom! 🥳 Check your Google Slides deck — you should now see the chart appear on the specified slide. The chart is inserted as a linked object, meaning it retains a connection to the source spreadsheet. In the Slides editor, if you click the chart, you’ll notice a link back to the Google Sheet. The Slides API effectively took our existing Sheets chart and embedded it into the presentation (Google for Developers). (If we had set linkingMode to NOT_LINKED_IMAGE, it would have just pasted a static image of the chart, but then it wouldn’t update with data change (Google for Developers) (Google for Developers)

Behind the scenes: The Slides API batchUpdate call processed our CreateSheetsChart request. We provided the spreadsheet and chart info, and Slides pulled in the chart. We could have added more requests in the same batchUpdate (for example, to create a new slide or add some text), but here we focused only on the chart. Using batch requests is useful to perform multiple operations in one API call.

Step 3: Update the Chart Data and Refresh the Slide

One of the best parts of this automation is that when your data changes, you don’t need to redo everything — you can refresh the existing chart on the slide to reflect the new data. Since we added the chart in LINKED mode, the chart on the slide is essentially a live link to the Google Sheets chart.

Let’s simulate a data update. Say the Q4 sales number changed from 170 to 190 in the spreadsheet. Your Python code (or another process) can update the sheet’s values (using the Sheets API values().update or maybe you have an automated data pipeline feeding the spreadsheet). Once the underlying Google Sheets chart is updated, we just need to ask Slides to grab the latest version.

Refresh the chart in Slides via API: We’ll use a RefreshSheetsChartRequest in another Slides API call. This request simply needs the objectId of the chart shape in the presentation (remember, we set our chart’s objectId as "MyChart1" when inserting it). The API will then fetch the latest chart info from Sheets and update the slide. Here’s how to do it:

# (Assume the spreadsheet data was updated via Sheets API or manually at this point)

# Prepare the refresh request for the chart object on the slide
refresh_chart_request = {
   'refreshSheetsChart': {
       'objectId': 'MyChart1'  # the chart's objectId in Slides
   }
}
slides_service.presentations().batchUpdate(
   presentationId=PRESENTATION_ID,
   body={'requests': [refresh_chart_request]}
).execute()

print("Chart on slide refreshed with latest data!")

That’s it – the chart in your Google Slides deck now reflects the updated data from Google Sheets 🎉. The next time someone opens the presentation (or if you export it), they’ll see the new values. You didn’t have to manually copy or modify anything in the slide — your Python code handled it.

What happened under the hood? The refreshSheetsChart call tells Slides to sync the embedded chart with its source. Essentially, Slides goes, “Oh, this chart is linked to a spreadsheet; let me pull the latest version.” This is something you could also do by clicking the “Update” button on a linked chart in the Slides UI; doing it via API means you can integrate it into a script or even a CI/CD pipeline. For example, you could schedule a daily job that updates the spreadsheet’s data and refreshes the charts in your slides, ensuring reports are always current.

Additional Tips and Best Practices

  • Use Placeholders for Templates: If you have a slide template with placeholder text like "{{CHART1}}", you can use an API call (replaceAllShapesWithSheetsChart) to find that text and replace it with a chart. This is handy for generating multiple similar slides or presentations where you want to swap in different charts dynamical (Stack Overflow). In our example, we directly inserted the chart, but templating is great for more complex automation.
  • Error Handling: Always include error handling around your API calls. The Google API client will raise errors if, for instance, your IDs are wrong or you don’t have access. Wrap calls in try/except and log useful messages (e.g., “Spreadsheet not found or no permission”).
  • Authentication Scopes: As noted, use the least permissive scopes you need. We used broad read/write scopes for simplicity. In a production app that only updates existing charts, you might use read-only for Sheets. Be mindful of the OAuth consent screen if using broad scopes – users will need to trust your app with their data.
  • Rate Limits and Batching: Google APIs have usage limits. If generating many charts or slides, batch as many changes as reasonable into a single batchUpdate call to reduce HTTP reques (Google for Developers). The Slides API can take an array of requests (up to 1000 per batch). Similarly, you can batch updates in Sheets.
  • Explore the APIs: We touched just the basics. The Sheets API can do more complex chart types (pie charts, scatter plots, etc.) by adjusting the spec. The Slides API can do things like adding text boxes, images, formatting, and even creating slides from layouts. Don’t hesitate to check out the official documentation and experiment with different requests to extend your automation.

Conclusion

In this guide, we’ve seen how to go from raw data to an updated slide deck without lifting a finger on the Slides UI. We created a chart in Google Sheets, embedded it into Google Slides using Python, and even updated it on the fly. This kind of automation is a game-changer for teams that regularly produce reports, dashboards, or any data-driven presentations.

By leveraging the Google Slides API and Google Sheets API with Python, you can ensure your charts are always fresh and save countless hours of manual work. Now that you know how to create charts in Google Slides with Python and automate those tedious updates, it’s time to put it into practice.

Ready to give it a try? Grab your credentials, write some Python code, and let the APIs do the heavy lifting. Once you’ve set this up, you’ll wonder how you ever managed those slide decks by hand. Happy automating!

Written by:

Adam Khakhar

Co-founder & CTO
Book a a meeting with our founders