Auto Sort sheet using API - Python

Options
Laurie Mason
Laurie Mason ✭✭✭✭
edited 03/05/24 in API & Developers

I have a code that should work to auto-sort my sheet, but I keep getting the message below. Others have used this script with no problem. Any advice would be greatly appreciated.

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)

Answers

  • Lee Joramo
    Lee Joramo ✭✭✭✭✭✭
    Options

    You need to use HTTP POST and not PUT. Change the line:

    # Send the request to Smartsheet API
    response = requests.put(url, headers=headers, data=json.dumps(payload))
    

    to

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

    Additionally, while there are times to directly program the API, I highly recommend using Smartsheet's SDK for your language if available. This will take care of many issue, such as retrying the API calls if your run into time outs due to too many calls. The Python SDK is here:

    Good Luck