Issues with Authenticating the Airtable API When Adding a Field Using Python

I am a beginner seeking assistance with adding a new record to my Airtable database utilizing Python 3. The documentation provides the following curl commands:

$ curl -v -XPOST https://api.airtable.com/v0/restoftheurl \
-H "Authorization: Bearer My_API_Key" \
-H "Content-type: application/json" \
-d '{
  "fields": {
    "Item": "Headphone",
    "Quantity": "1",
    "Customer_ID": [
      "My_API_Key"
    ]
  }
}'

The Python code I attempted is:

import requests

api_endpoint = "https://api.airtable.com/v0/restoftheurl"

payload = {
    "Authorization": "Bearer My_API_Key",
    "Content-Type": "application/json",
    "fields": {
        "Item": "randomitem",
        "Quantity": "5",
        "Customer_ID": ["randomrecord"]
    }
}

response = requests.post(api_endpoint, json=payload)
print(response.json())

However, the resulting error is:

{'error': {'type': 'AUTHENTICATION_REQUIRED', 'message': 'Authentication required'}}

Could someone guide me on the correct way to authenticate this request or clarify what I may be doing incorrectly?

It looks like you’ve mixed up where the headers and the payload should go in your requests.post function. The Authorization and Content-Type should be set as headers, not included in the payload directly. Here’s how you should structure your request:

import requests

api_endpoint = "https://api.airtable.com/v0/restoftheurl"

headers = {
    "Authorization": "Bearer My_API_Key",
    "Content-Type": "application/json"
}

payload = {
    "fields": {
        "Item": "randomitem",
        "Quantity": "5",
        "Customer_ID": ["randomrecord"]
    }
}

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

By separating the headers and the payload, you should be able to authenticate successfully. Double-check that your API key is correct, as any typo will also cause authentication failures.