1

I'm using Airtable db to fetch data against an input. I want to fetch data from database against that input but I'm not aware how to achieve that.

Here's my fetch API call function

const fetchData = async e => {
    e.preventDefault();

fetch(`https://api.airtable.com/v0/${process.env.AIRTABLE_BASE_ID}/${process.env.AIRTABLE_TABLE_NAME}`, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.API_KEY}`,
      },
    })
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error('Something went wrong');
        }
    })
    .then(rawResponse => {
    console.log(rawResponse);
    })
    .catch(error => {
    customToast.error('Something went wrong.');
    console.log('Error', error);
    });
  };
Hasham Minhas
  • 436
  • 3
  • 13

1 Answers1

1

The Airtable API has two different GET methods. One will return a list of records and if you don't include any query parameters, it will eventually give you all records for the specified table. The other GET method takes an Airtable Record ID and returns just that record.

One of the query parameters for the list GET request is called filterByFormula. You can provide a valid Airtable formula that evaluates to true/false and the API will only return records for which the formula evaluates to true.

One of the easiest ways is to simply compare the field in Airtable against the value you are interested in like:

{My Field Name}='My Field Value'

The GET request would look something like:

fetch(
  `https://api.airtable.com/v0/${process.env.AIRTABLE_BASE_ID}/${process.env.AIRTABLE_TABLE_NAME}?filterByFormula={My Field Name}='My Field Value'`, 
  {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.API_KEY}`,
    },
  }
)
.then(response => {
  if (response.ok) {
    return response.json();
  } else {
    throw new Error('Something went wrong');
  }
})
.then(rawResponse => {
  console.log(rawResponse);
})
.catch(error => {
  customToast.error('Something went wrong.');
  console.log('Error', error);
});

For more complex comparisons, Airtable does support a variety of text comparison functions like FIND and it also has functions for handling regular expressions.

This will return a list of records, even if there is only one record in the list. If the field you are comparing to might contain duplicate values, then you need to handle the situation where the API response contains more than one record and decide what to do.

TheF1rstPancake
  • 2,318
  • 17
  • 17