Auto-sort using API

Options

I understand that as of now it is not possible to auto-sort columns in Smartsheet. But is there an API code that can be used to sort columns alphabetically?

Answers

  • kskarz
    kskarz ✭✭✭✭
    edited 01/29/24
    Options

    Hi @Hazika Reshi

    You can sort columns using API:

    https://smartsheet.redoc.ly/tag/rows#operation/rows-sort

    If you have a webhook in place you can have a auto-sort as soon as the data is saved in the sheet.

  • Laurie Mason
    Laurie Mason ✭✭✭✭
    Options

    Kskarz,

    I found an Python script on another thread that should work, but I keep getting an error message (below). Any suggestions?

    Error sorting sheet. Status code: 405

    "errorCode" : 1122,

    "message" : "Requested URL does not support this method: PUT",


    Here is the script I used:

    import requests

    import json


    # Smartsheet API access token

    access_token = {'YOUR API TOKEN HERE'}


    # Smartsheet sheet ID

    sheet_id = {'YOUR SHEET ID HERE'}


    # Define the endpoint for the API

    url = f'https://api.smartsheet.com/2.0/sheets/{sheet_id}/sort'


    # Define the headers

    headers = {

      'Authorization': f'Bearer {access_token}',

      'Content-Type': 'application/json'

    }


    # Define the sorting criteria

    sort_criteria = [

      {

        "columnId": {YOUR COLUMN ID HERE},

        "direction": "ASC" # or "DESC" for descending

      }

    ]


    # Define the payload

    payload = {

      "sortSpecifiers": sort_criteria

    }


    # Send the request to Smartsheet API

    response = requests.put(url, headers=headers, data=json.dumps(payload))


    # Check if the request was successful

    if response.status_code == 200:

      print("Sheet sorted successfully.")

    else:

      print(f"Error sorting sheet. Status code: {response.status_code}")

      print(response.text)

  • Laurie Mason
    Laurie Mason ✭✭✭✭
    edited 03/22/24
    Options

    @kskarz

    I figured out that you must use the post method instead instead of put. However, I am now getting a an error messages on the line below saying the payload "Object of type set is not JSON serializable".

    response = requests.putpost(url, headers=headers, data=json.dumps(payload))

    Do you have any ideas that could help?