Some simple examples of Smartsheet API using the Python SDK

jim99 picture jim99 · Mar 18, 2016 · Viewed 7.9k times · Source

I am newbie to the Smartsheet Python SDK. Using the sample code from the Smartsheets API doc as a starting point:

action = smartsheet.Sheets.list_sheets(include_all=True)
sheets = action.data

This code returns a response just fine.

I am now looking for some simple examples to iterate over the sheets ie:

for sheet in sheets:

then select a sheet by name

then iterate over the rows in the selected sheet and select a row.

for row in rows:

then retrieve a cell value from the selected row in the selected sheet.

I just need some simple samples to get started. I have searched far and wide and unable to find any simple examples of how to do this Thanks!

Answer

doron picture doron · Mar 24, 2016

As Scott said, a sheet could return a lot of data, so make sure that you use filters judiciously. Here is an example of some code I wrote to pull two rows but only one column in each row:

action = smartsheet.Sheets.get_sheet(SHEET_ID, column_ids=COL_ID, row_numbers="2,4")

Details on the available filters can be found here.

UPDATE: more code added in order to follow site etiquette and provide a complete answer.

The first thing I did while learning the API is display a list of all my sheets and their corresponding sheetId.

action = MySS.Sheets.list_sheets(include_all=True)
for single_sheet in action.data:
    print single_sheet.id, single_sheet.name

From that list I determined the sheetId for the sheet I want to pull data from. In my example, I actually needed to pull the primary column, so I used this code to determine the Id of the primary column (and also saved the non-primary column Ids in a list because at the time I thought I might need them):

PrimaryCol = 0
NonPrimaryCol = []
MyColumns = MySS.Sheets.get_columns(SHEET_ID)
for MyCol in MyColumns.data:
    if MyCol.primary:
        print "Found primary column", MyCol.id
        PrimaryCol = MyCol.id
    else:
        NonPrimaryCol.append(MyCol.id)

Lastly, keeping in mind that retrieving an entire sheet could return a lot of data, I used a filter to return only the data in the primary column:

MySheet = MySS.Sheets.get_sheet(SHEET_ID, column_ids=PrimaryCol)
for MyRow in MySheet.rows:
    for MyCell in MyRow.cells:
        print MyRow.id, MyCell.value