How to properly encode multiple sorting parameters in Airtable API requests?

I’m struggling with the Airtable API. I need to sort my data using multiple fields and directions. But I’m not sure how to encode this correctly in the URI.

Here’s what I’m trying to do:

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

function buildSortQuery(sortConfig) {
  let query = '';
  sortConfig.forEach((item, index) => {
    query += `&sort[${index}][column]=${encodeURIComponent(item.column)}`;
    query += `&sort[${index}][order]=${item.order}`;
  });
  return query;
}

let finalQuery = buildSortQuery(sortConfig);
console.log(finalQuery);

Is this the right way to do it? The API docs aren’t very clear on how to handle multiple sort parameters. Can anyone help me figure out the correct encoding for this? Thanks!

I’ve been working with the Airtable API for a while now, and I can tell you that handling multiple sort parameters can be tricky. Your approach is on the right track, but there’s a simpler way to do it. I’ve found that using the qs library makes this process much easier and less error-prone.

Here’s what I usually do:

const qs = require('qs');

const sortConfig = [
  { field: 'name', direction: 'asc' },
  { field: 'price', direction: 'desc' },
  { field: 'type', direction: 'asc' }
];

const query = qs.stringify({ sort: sortConfig }, { arrayFormat: 'brackets' });
console.log(query);

This generates a properly encoded query string that Airtable’s API can understand. Just make sure to install the qs library first (npm install qs). It’s been a lifesaver for me when dealing with complex query parameters. Hope this helps!

hey jackhero77, ur on the right track! i’ve used airtable api before and what u’ve got looks pretty close. just make sure to add the base url before ur query string. also, double-check the api docs for any specific formatting requirements. good luck with ur project mate!

Your approach is close, but there’s a more efficient way to handle multiple sort parameters in Airtable API requests. Instead of building the query string manually, consider using the URLSearchParams API. It’s more robust and handles encoding automatically. Here’s an improved version:

const sortConfig = [
  { field: 'name', direction: 'asc' },
  { field: 'price', direction: 'desc' },
  { field: 'type', direction: 'asc' }
];

const params = new URLSearchParams();
sortConfig.forEach((sort, index) => {
  params.append(`sort[${index}][field]`, sort.field);
  params.append(`sort[${index}][direction]`, sort.direction);
});

const finalQuery = params.toString();
console.log(finalQuery);

This method is cleaner and less error-prone. Remember to append this to your base URL when making the API request.