Python script failing to authenticate with Airtable API when adding new field

Hey everyone, I’m new to working with APIs and I’m stuck trying to add a new record to my Airtable base using Python. I’ve looked at the curl commands in the docs, but I can’t figure out how to translate them into Python code.

Here’s what I’ve tried so far:

import requests

url = 'https://api.airtable.com/v0/mybaseurl'

payload = {
    'fields': {
        'Product': 'Earbuds',
        'Amount': '3',
        'User_ID': ['some_id']
    }
}

headers = {
    'Authorization': 'Bearer MY_SECRET_KEY',
    'Content-Type': 'application/json'
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())

But I keep getting an authentication error. What am I doing wrong? How do I properly set up the authentication for this API request in Python? Any help would be much appreciated!

I encountered a similar issue when I first started working with the Airtable API. Here’s what helped me resolve it:

First, double-check your API key. Make sure you’re using the correct one and that it has the necessary permissions for the base you’re trying to access.

Next, ensure your base URL is correct. It should look something like this: ‘https://api.airtable.com/v0/appXXXXXXXXXXXXXX/Table%20Name

Also, try adding the ‘Content-Type’ header to your request:

headers = {
‘Authorization’: f’Bearer {YOUR_API_KEY}',
‘Content-Type’: ‘application/json’
}

If you’re still having issues, try using the Airtable Python wrapper. It simplifies the process and handles authentication for you:

from airtable import Airtable

airtable = Airtable(‘YOUR_BASE_ID’, ‘YOUR_TABLE_NAME’, api_key=‘YOUR_API_KEY’)
airtable.insert({‘Product’: ‘Earbuds’, ‘Amount’: ‘3’, ‘User_ID’: [‘some_id’]})

Hope this helps! Let me know if you need any further clarification.

hey mate, i had similar probs. check ur base url, it shud include the table name at the end. like this:

url = ‘https://api.airtable.com/v0/appXXXXXXXXXXXXXX/YourTableName

also make sure ur api key is correct. if that dont work, try the airtable python wrapper. its way easier

I’ve encountered this issue before. The problem likely lies in your base URL. It should include both your base ID and table name, like this:

url = ‘https://api.airtable.com/v0/appXXXXXXXXXXXXXX/YourTableName

Replace ‘appXXXXXXXXXXXXXX’ with your actual base ID and ‘YourTableName’ with the name of the table you’re targeting.

Also, ensure your API key is correct and has the necessary permissions. If you’re still facing issues, consider using the official Airtable Python client. It simplifies API interactions and handles authentication automatically.

Remember to keep your API key secure and never share it publicly.