Skip to content
Advertisement

how to format cloudinary sort_by parameter to prevent error

hello stack overflow community,

I’m fetching my images from cloudinary and the post request is working fine, until I add the sort_by parameter to the URL. This will lead to an error based on the sort format. The official documentation describes the valid format as following:

“An array of string values representing a key value pair, where the key is the field to sort by and the value is the direction. Valid sort directions are asc or desc. If this parameter is not provided then the results are sorted by descending creation date. You can specify more than one sort_by parameter; results will be sorted according to the order of the fields provided.” https://cloudinary.com/documentation/search_api#parameters

But when I use a request URL like this one:

https://api.cloudinary.com/v1_1/daxl9cg/resources/search?max_results=3&sort_by=[{"created":"desc"}]

I’m getting the following error, because backslashes are added:

{
    "error": {
        "message": "Incorrect sort format "[{\"created\":\"desc\"}]", supported format [{"created":"desc"}]"
    }
}

I assume the backslashes want to escape the string quotations. Do you have an idea how to prevent this?

Thanks for your answer!

Advertisement

Answer

There are two things to address:

  1. The parameter you want to use is called created_at rather than created – which I see is also returned in the error response from Cloudinary. I would recommend reporting this discrepancy to Cloudinary by submitting a ticket via: https://support.cloudinary.com/hc/requests/new – so that the error message Cloudinary returns could be updated to correctly reflect the parameter name that is also in the Documentation.
  2. The value of sort_by is not quite right. When passed as part of the query string it should be: sort_by[][created_at]=desc in raw form and sort_by%5B%5D%5Bcreated_at%5D=desc after URL encoding the [].

With this in mind, the URL you want to query is (replacing the values marked with <PLACEHOLDER>):

https://<API_KEY>:<API_SECRET>@api.cloudinary.com/v1_1/<CLOUD_NAME>/resources/search?max_results=3&sort_by%5B%5D%5Bcreated_at%5D=desc

You can also send a POST request with JSON data as follows:

curl -X POST -H "Content-Type: application/json" 'https://<API_KEY>:<API_SECRET>@api.cloudinary.com/v1_1/<CLOUD_NAME>/resources/search' --data '{"max_results":3,"sort_by":[{"created_at":"desc"}]}'
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement