How to properly encode multiple sort fields and directions in Airtable API URL

I’m trying to figure out how to correctly encode multiple sort fields and directions in the Airtable API URL. I have a sorting object with several fields and directions, but I’m not sure how to properly include them in the query string.

Here’s an example of what I’m working with:

const sortingCriteria = [
  { column: 'name', order: 'asc' },
  { column: 'price', order: 'desc' },
  { column: 'type', order: 'asc' }
];

I’ve attempted to build the query string like this:

let queryParams = '';

sortingCriteria.forEach(criteria => {
  queryParams += `&sort[0][column]=${encodeURIComponent(criteria.column)}&sort[0][order]=${criteria.order}`;
});

console.log(queryParams);

But this doesn’t seem to work correctly. Can someone help me understand how to properly encode multiple sort fields and directions for the Airtable API URL? Thanks in advance!

Having dealt with Airtable API sorting issues, I can offer some insight. The key is to use array notation in your query string to handle multiple sort criteria. Here’s a more efficient approach:

const queryParams = sortingCriteria.map((criteria, index) => 
  `sort[${index}][field]=${encodeURIComponent(criteria.column)}&sort[${index}][direction]=${criteria.order}`
).join('&');

const finalUrl = `${baseUrl}?${queryParams}`;

This method uses map() to create an array of encoded parameters, then joins them with ‘&’. It’s cleaner and avoids potential issues with string concatenation. Remember to prepend your base URL before making the API call. Also, double-check Airtable’s documentation for any recent changes in parameter naming conventions.

hey there! i’ve done this before. u need to use different indexes for each sort field. try this:

const params = sortingCriteria.map((c, i) => 
  `sort[${i}][field]=${encodeURIComponent(c.column)}&sort[${i}][direction]=${c.order}`
).join('&');

this should work better. good luck with ur project!

I’ve worked through this problem before when integrating with the Airtable API. Your current method is reusing the same sort index, which means only the last criterion ends up in the query string. Instead, you need to use a different index for each sorting field.

Here’s an updated version of your code:

let queryParams = '';
sortingCriteria.forEach((criteria, index) => {
  queryParams += `&sort[${index}][field]=${encodeURIComponent(criteria.column)}&sort[${index}][direction]=${criteria.order}`;
});

By using the index in the URL, each sort criterion gets its own spot. Also, note the change from ‘column’ and ‘order’ to ‘field’ and ‘direction’ to align with Airtable’s expected parameters. Append this string to your base URL to correctly form the API call.