Help

How do I create a new field under the view and patch data to it

Topic Labels: API
595 0
cancel
Showing results for 
Search instead for 
Did you mean: 
guanxinwang
4 - Data Explorer
4 - Data Explorer

Hi,

I am building an application to get data from a view and attempting to patch it back to the view. However, I haven't found any endpoints to do it. First, I want to check whether the view has a field. If it doesn't, I shall create a new field and patch my data to the view. Any help is highly appreciated.

 

I am using Nest.js Axios, and here is my code:

  createField(baseId: string, tableId: string, field: string, token: string) {
    console.log('creating field...');
    // when I post, it gives me 422
    const url = `https://api.airtable.com/v0/meta/bases/${baseId}/tables/${tableId}/fields`;
    const headers = {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    };
    const body = JSON.stringify({
      fields: {
        name: field,
        type: 'singleLineText',
      },
    });
    this.http.post(url, body, { headers }).subscribe(res => {
      console.log(res);
    });
  }

And here is my code for patching the data:

  patchAirtable(
    promises: Array<any>,
    baseId: string,
    tableId: string,
    viewId: string,
    token: string,
  ) {

    console.log('patching airtable...');
    // patch one record
    // TODO: patch multiple records
    console.log(promises[0]);
    const id: string = promises[0].id;
    const field: string = promises[0].field;
    const value: string = promises[0].value.toString();
    const url = `https://api.airtable.com/v0/${baseId}/${tableId}/${id}`;
    console.log(url);
    const options = {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        records: [
          {
            id: id,
            fields: {
              [field]: value,
            },
          },
        ],
      }),
    };

    // https://api.airtable.com/v0/${baseId}/${tableId}?view=${viewId}
    this.getView(baseId, tableId, viewId, token).subscribe(res => {
      console.log('checking field exist...');
      console.log(res.data.records.map(record => record.fields));
      const fields = res.data.records.map(record => record.fields);
      if (Object.keys(fields).includes(field)) {
        console.log('field exist, patching...');
        this.http.patch(url, options).subscribe(res => {
          console.log(res);
        });
      } else {
        console.log('field not exist, creating...');
        this.createField(baseId, tableId, field, token);
      }
    });
  }
0 Replies 0