Python script can't retrieve specific Airtable field by ID - returns error but fetching all fields works

I’m having trouble with my Python code that connects to the Airtable API. When I try to retrieve a specific field using an identifier, it returns a ‘not found’ error. However, when I fetch all fields simultaneously, it works perfectly fine.

Here’s the code I’ve written:

from flask import Flask, render_template, request
import requests

app = Flask(__name__)

@app.route('/')
def home_page():
    return render_template('index.html')

@app.route('/data')
def get_data():
    record_id = request.args.get('record_id')
    api_endpoint = f"https://api.airtable.com/v0/appXYZ123/database/{record_id}"
    auth_headers = {
        "Authorization": "Bearer YOUR_TOKEN_HERE"
    }
    api_response = requests.get(api_endpoint, headers=auth_headers)
    json_data = api_response.json()
    
    target_field_value = json_data.get('fields', {}).get('record_id', 'Not found')
    
    print("Record ID:", record_id)
    print("API Response:", json_data)
    print("Status Code:", api_response.status_code)
    return render_template('data.html', target_field=target_field_value)

if __name__ == '__main__':
    app.run(debug=True)

When I change the code to retrieve all fields like this, it works:

api_response = requests.get(api_endpoint, headers=auth_headers)
json_data = api_response.json()

# Get all available fields
all_fields = json_data.get('fields', {})

I’ve attempted modifying the field format in Airtable and adjusting the code multiple times, but I still can’t determine what the issue is. Can anyone help me figure out what’s going wrong?

Your API endpoint construction is the problem. You’re using record_id as both the URL parameter and the field name you’re searching for - that’s creating confusion. Airtable’s API needs the actual record ID in the URL path, not a field name. Check that the record_id from your frontend is actually a valid Airtable record ID (they start with ‘rec’ plus alphanumeric characters). Also make sure your table name in the URL is right - ‘database’ looks pretty generic. Log the exact URL you’re building and compare it to Airtable’s expected format. Since fetching all fields works, your auth and base ID are fine. The issue’s probably how you’re building that specific record request.

you’re mixing up the record_id param with actual field names. when you do json_data.get('fields', {}).get('record_id', 'not found'), you’re looking for a field called ‘record_id’ - but that’s just the ID from your URL, not an airtable field. print all_fields.keys() first to see what fields exist, then use the right field name instead.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.