Search code examples
pythonpython-3.xcurlairtable

Trouble authenticating Airtable API while creating a field with python


[newbie question]

I'm trying to create a new record in my Airtable base using python 3. The curl commands in the documentation are as follows:

$ 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 tried to use is:

import requests

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

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

r = requests.post(API_URL, data)
print(r.json())

Where the response is the error:

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

How am I supposed to properly authenticate this, or am I way of?


Solution

  • You need to distinguish the body (data) from the headers. Using the json named argument automatically set the content type to application/json :

    import requests
    
    API_URL = "https://api.airtable.com/v0/restoftheurl"
    
    headers = {
        "Authorization": "Bearer My_API_Key"
    }
    
    data = {
        "fields": {
            "Item": "randomitem",
            "Quantity": "5",
            "Customer_ID": ["randomrecord"]
        }
    }
    
    r = requests.post(API_URL, headers=headers, json=data)
    print(r.json())