Get list of sheets and latest sheet in google spreadsheet api v4 in Python

Nobody has asked about this on SO for the PHP library yet, but I just wanted to add this answer here as this is the first Google result for related questions.

<?php

$sheets = array();

// ... load library and set up client ...
$service = new Google_Service_Sheets($client);

$response = $service->spreadsheets->get($spreadsheetId);
foreach($response->getSheets() as $s) {
    $sheets[] = $s['properties']['title'];
}

return $sheets;

?>

You can get a list of sheets by using the "get" method on spreadsheets:

sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheets = sheet_metadata.get('sheets', '')
title = sheets[0].get("properties", {}).get("title", "Sheet1")
sheet_id = sheets[0].get("properties", {}).get("sheetId", 0)

For python.

service = build('sheets', 'v4', credentials=creds)

sheet_metadata = service.spreadsheets().get(spreadsheetId=SHEET_ID).execute()

properties = sheet_metadata.get('sheets')
for  item in properties:

   if item.get("properties").get('title') == 'SHEET_TITILE':
       sheet_id = (item.get("properties").get('sheetId'))

print (sheet_id)

For those looking for a nodejs solution:

const { google } = require("googleapis")

// Assuming auth has already been generated
const getSheets = async (auth, spreadsheetId) => {
  const sheets = google.sheets({version: "v4", auth});
  const result = (await sheets.spreadsheets.get({ 
    spreadsheetId 
  })).data.sheets.map((sheet) => {
    return sheet.properties.title
  })
  return result
}

This is what gets returned from await sheets.spreadsheets.get({ spreadsheetId })

Then, using this type, I map over the result of data.sheets and return all of titles.

It looks like it returns the titles in order of how they are on the actual google sheet.

If you're trying to generate the auth token, then look here