Flutter HTTP PUT Request to Airtable Returns 422 Error During Record Update

Encountering 422 Status Code When Updating Records in Airtable with Flutter

I can successfully retrieve and delete records from my Airtable database, but whenever I attempt to update a record, I receive a 422 error. This error is logged as an unhandled exception in the console.

Database Service (airtable_service.dart)

import 'package:http/http.dart' as http;
import 'package:myapp/models/employee_model.dart';
import 'package:myapp/config/app_config.dart';

class EmployeeService {
  final Uri baseUrl = Uri.https(
    "api.airtable.com",
    "/v0/${AppConfig.baseId}/employees",
    {"maxRecords": "100", "view": "Main view"},
  );

  Future<List<Employee>> fetchEmployees() async {
    final response = await http.get(
      baseUrl,
      headers: {"Authorization": "Bearer ${AppConfig.apiToken}"},
    );

    if (response.statusCode == 200) {
      var jsonData = jsonDecode(response.body);
      var records = jsonData['records'];
      List<Employee> employees = [];
      
      records.forEach((record) => {
        employees.add(
          Employee(
            recordId: record['id'],
            firstName: record['fields']['firstName'],
            lastName: record['fields']['lastName'],
            profileImage: record['fields']['profileImage'][0]['url'],
            status: record['fields']['status'],
            email: record['fields']['email'],
            position: record['fields']['position'],
            phone: record['fields']['phone'],
            rating: record['fields']['rating'],
            resume: record['fields']['resume'][0]['url'],
            latitude: record['fields']['latitude'].toDouble(),
            longitude: record['fields']['longitude'].toDouble(),
          ),
        )
      });

      return employees;
    } else {
      throw "Fetch failed";
    }
  }

  Future<String> removeEmployee(String recordId) async {
    final result = await http.delete(
      Uri.https("api.airtable.com", "/v0/${AppConfig.baseId}/employees/$recordId"),
      headers: {"Authorization": "Bearer ${AppConfig.apiToken}"},
    );

    if (result.statusCode == 200) {
      return recordId;
    } else {
      throw Exception(result.statusCode);
    }
  }

  Future<Employee> modifyEmployee(String recordId, String newRating) async {
    final result = await http.patch(
      Uri.https("api.airtable.com", "/v0/${AppConfig.baseId}/employees/$recordId"),
      headers: {
        "Authorization": "Bearer ${AppConfig.apiToken}",
        "Content-Type": "application/json",
      },
      body: jsonEncode({
        "fields": {
          "rating": newRating,
        }
      }),
    );

    if (result.statusCode == 200) {
      return Employee.fromJson(jsonDecode(result.body));
    } else {
      throw Exception(result.statusCode);
    }
  }
}

Does anyone know what could be causing this 422 error? I would greatly appreciate any insights!

Had this exact issue a few months back with Airtable. The 422 usually means you’re sending data that doesn’t match what the field expects.

You’re sending newRating as a string, but if your rating field is set up as a number in Airtable, it’ll reject it. Convert it first:

body: jsonEncode({
  "fields": {
    "rating": int.parse(newRating), // or double.parse() if it's a decimal
  }
}),

Also check your Airtable base settings - some fields have validation rules like min/max values.

Add some debug logging to see what’s actually wrong:

if (result.statusCode != 200) {
  print('Error body: ${result.body}');
  throw Exception(result.statusCode);
}

This’ll show you exactly what Airtable’s complaining about.

make sure ur ‘rating’ field name is exactly like it is in the Airtable schema - case matters. Also, try logging the full response body to get a better idea of what error Airtable is giving. A 422 means validation failed, so there might be an issue with your data.