Code Monkey home page Code Monkey logo

airtable.py's Introduction

Airtable.py: Python API wrapper for Airtable

Python interface to the Airtable's REST API - https://airtable.com -Build Status

For javascript enthusiasts: https://github.com/Airtable/airtable.js

Installation

Airtable Python uses Requests.py: make sure you have it installed by running

$ pip install requests

Getting started

Once you have created a new base and a new table through the Web interface, you're ready to start using Airtable Python.

import airtable
at = airtable.Airtable('BASE_ID', 'ACCESS_TOKEN')
at.get('TABLE_NAME')

Here's an example of response from the Restaurant's example base

{u'records': [
  {u'fields': {u'Diet': u'Kosher or Halal',
    u'Friendly Restaurants': [u'recr0ITqq9C1I92FL', u'recGeAJLw0ZkbwdXZ'],
    u'Icon': [{u'filename': u'no-pig.jpg',
      u'id': u'attzKGOBbjndOx0FU',
      u'size': 34006,
      u'thumbnails': {u'large': {u'height': 202,
        u'url': u'https://dl.airtable.com/trmtq3BaRoa0sWnyffWZ_large_no-pig.jpg',
        u'width': 256},
       u'small': {u'height': 36,
        u'url': u'https://dl.airtable.com/yzuRv5CyRs2PVH4fDvCe_small_no-pig.jpg',
        u'width': 46}},
      u'type': u'image/jpeg',
      u'url': u'https://dl.airtable.com/DyGOjAASze6AIkQxFpDv_no-pig.jpg'}],
    u'People': [u'Annie', u'Maryam']},
   u'id': u'rec5sD6mBBd0SaXof'},
   ...

API Reference

The available methods closely mimic the REST API:

Get

Given a table name, fetched one or multiple records.

at.get(table_name, record_id=None, limit=0, offset=None,
       filter_by_formula=None, view=None, max_records=0, fields=[])

where

table_name (required) is a string representing the table name
record_id (optional) is a string, which fetches a specific item by id. If not specified, all items are fetched
limit (optional) is an integer, and it can only be specified if record_id is not present, and limits the number of items fetched (see pageSize in the AirTable documentation)
offset is a string representing the record id from which we start the offset
filter_by_formula (optional) is a string to filter the retrieving records (see filterByFormula in the AirTable documentation)
max_records (optional) is the total number of records that will be returned (see maxRecords in the AirTable documentation)
fields (optional) is a list of strings with the field names to be returned

Iterate

Given a table name, fetched all records.

at.iterate(table_name, batch_size=0, filter_by_formula=None,
       view=None, max_records=0, fields=[])

where

table_name (required) is a string representing the table name
batch_size (optional) is an integer specifying the number of records to fetch per request. The default (0) uses the API default, which is (as of 2016-09) 100.
limit (optional) is an integer, and it can only be specified if record_id is not present, and limits the number of items fetched (see pageSize in the AirTable documentation)
filter_by_formula (optional) is a string to filter the retrieving records (see filterByFormula in the AirTable documentation)
view  (optional) is a string representing the name or ID of a view in the table. If set, only the records in that view will be returned. The records will be sorted according to the order of the view.
max_records (optional) is the total number of records that will be returned (see maxRecords in the AirTable documentation)
fields (optional) is a list of strings with the field names to be returned

Note: this returns a generator instead, which you can use to loop each record:

# example with similar results of at.get
result = { "records": [] }
for r in self.at.iterate(self.table, fields=fields):
    result["records"].append(r)

Create

Creates a new entry in a table, and returns the newly created entry with its new ID.

at.create(table_name, data)

where

table_name (required) is a string representing the table name
data (required) is a dictionary containing the fields and the respective values

Update

Updates some fields in a specific entry in the table. Fields which are not explicitly included will not get updated

at.update(table_name, record_id, data)

where

table_name (required) is a string representing the table name
record_id (required) is a string representing the item to update
data (required) is a dictionary containing the fields (and the respective values) to be updated

Update All

Like the previous method, but updates all fields, clearing the ones that are not included in the request.

at.update_all(table_name, record_id, data)

Delete

Delete a specific record from the table

at.delete(table_name, record_id)

where

table_name (required) is a string representing the table name
record_id (required) is a string representing the item to update

Release

To release, tag the Git repo with a new version number, push that tag to GitHub then Travis CI will do the rest.

airtable.py's People

Contributors

brunobraga avatar h avatar jan-san avatar josephbestjames avatar lathomas64 avatar mattnewport avatar meli-lewis avatar nicocanali avatar pcorpet avatar ramyala avatar strayduy avatar zozoens31 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

airtable.py's Issues

ModuleNotFoundError

Hi, I am using Windows where pip install requests was completed successfully. On the first line of my code as below I get the error.

from airtable import airtable

ModuleNotFoundError Traceback (most recent call last)
in
----> 1 from airtable import airtable

ModuleNotFoundError: No module named 'airtable'

Airtable client's get method does not work for me

Code:
at_client = airtable.Airtable("Beta testing", AIRTABLE_TOKEN)
at_client.get("People")

Error:
Traceback (most recent call last): File "/Users/andrasnagy/Desktop/sensae/code_base/projects/slack-app/main.py", line 22, in <module> at_client.get("People") File "/Users/andrasnagy/Desktop/sensae/code_base/projects/slack-app/.venv/lib/python3.11/site-packages/airtable/airtable.py", line 133, in get return self.__request('GET', url, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/andrasnagy/Desktop/sensae/code_base/projects/slack-app/.venv/lib/python3.11/site-packages/airtable/airtable.py", line 107, in __request error_type=error_json.get('type', str(r.status_code)), ^^^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'get'

I did check the type of "at_client", and as expected, it is of type "<class 'airtable.airtable.Airtable'>". Anyone has seen this issue already?

Accelerated need to limit large url requests to “list records”, with alternative POST version

Hi! Fred here again, from the Airtable API team. Another update is that as part of recent infrastructure improvements to airtable.com, we needed to accelerate enforcement of rejecting any requests whose request URLs exceed 16k characters. The changes described below are in effect today.

  • Q: What endpoints does this affect?
    • The 16k character limit applies to all current and future API request URLs
    • Based on our internal audit of current usage, this primary impacts the “list records” endpoint, which is a GET request to /v0/{baseId}/{tableIdOrName} (https://airtable.com/developers/web/api/list-records)
  • Q: What is the impact of this change?
    • The vast majority of our API requests have remained well under the 16k character limit, and would not be affected
    • However, requests exceeding this limit will now be rejected, so we expect some calls to now require an update to handle the large cases. For example, requests whose query parameter for filterbyFormula is long enough to make the overall URL length to exceed that character limit
    • Therefore, we recommend either switching entirely to the alternative detailed below, or switching to it when you can detect that a request URL will exceed the 16k character limit
  • Q: What is the alternative?
  • Q: Why the urgency for this change?
    • I apologize for the inconvenience due to the accelerated timeline here. While we originally planned to start this enforcement in January 2023, we needed to deploy this change recently this week, as part of required infrastructure improvements to maintain the stability of our public API

Early heads up: switching away from user API keys

Hi! I’m Fred, an engineer on the Airtable API team. I’m writing here to share some plans we have to move away from user API keys, with a goal of communicating it early so you have time to triage and prioritize work needed.

First, some context. We recently published a new developer doc site, and announced two new authentication methods, as well as new endpoints and capabilities those methods support: https://airtable.com/developers/web/api/changelog#anchor-2022-11-15

Since these new authentication methods (personal access tokens and OAuth integration access tokens) are much more secure than the current user API key authentication method, we are limiting the new endpoints and capabilities to only be available to the new methods.

The medium term plan is to deprecate user API keys. We are still working on the exact details, but the deprecation period will last 1 year, and we expect it to begin at the start of next year (Jan 2023).

Based on this we recommend preparing to support the new API token format:

Only fetches 99 items.

It will only fetch 99 items for me.
I have a 157 on my airtable.
Other than that, I think it works fine.

at = airtable.Airtable('appua4wbLWf65hiXG/', 'my_api_key')
clients = at.get('Clients')

print clients

Support for typecast

As per API documentation typecast option to be set as true to add new multiple select array of strings. Can this option be added in the client create method ?

FieldName: Tags
Type: Multiple select
array of strings
Array of selected option names.

When creating or updating records, if a choice string does not exactly match an existing option, the request will fail with an INVALID_MULTIPLE_CHOICE_OPTIONS error unless the typecast parameter is enabled. If typecast is enabled, a new choice will be created if one does not exactly match.

dyld: lazy symbol binding failed

When running the curl

"https://api.airtable.com/v0/..." -H "Authorization: Bearer ...,

there is an error:

dyld: lazy symbol binding failed: Symbol not found: _SSL_CTX_set_alpn_protos
  Referenced from: /Users/.../anaconda/bin/../lib/libcurl.4.dylib
  Expected in: /Users/.../anaconda/bin/../lib/libssl.1.0.0.dylib

dyld: Symbol not found: _SSL_CTX_set_alpn_protos
  Referenced from: /Users/.../anaconda/bin/../lib/libcurl.4.dylib
  Expected in: /Users/.../anaconda/bin/../lib/libssl.1.0.0.dylib

airtable can not interpret Collections.OrderedDict

If you obtain a record with say attachments which are returned in an ordered dictionary, you have to convert them into a dictionary for them to be updated via at.update() for example. Why not just put the objects in a dictionary in the first place so they are update compatible? When you query airtable for records, there is no ordering mechanism and records are jumbled anyway so I'm not sure for the need of Collections.OrderedDict. It basically just means you have to do some preprocessing as found here to convert the nested ordered dict to a normal dict. Thanks!

Update image issue

Hi,

Thanks so much for this repository! Really nice 👍

I'm trying to update images (attachments in AirTable), but there's an error when doing this. Here's the code:

data = { "Image" : {"url": "https://url.image.com/asset.3246874.jpg"}} 
at.update('test', "9876dlafjkl", data)

as you see the image requires nested information about the image. The only requirement is the URL. Others are optional.

Here's the error i'm getting. Unfortunately the error after this tells nothing.

HTTPError                                 Traceback (most recent call last)
C:\Continuum\Anaconda\envs\company-image-retreiver\lib\site-packages\airtable-0.3.1-py3.6.egg\airtable\airtable.py in __request(self, method, url, params, payload)
     58                 message = None
---> 59                 r.raise_for_status()
     60             except requests.exceptions.HTTPError as e:

C:\Continuum\Anaconda\envs\company-image-retreiver\lib\site-packages\requests\models.py in raise_for_status(self)
    927         if http_error_msg:
--> 928             raise HTTPError(http_error_msg, response=self)
    929 

HTTPError: 422 Client Error: Unprocessable Entity for url: https://api.airtable.com/v0/xxxxxxxxxxxxxxxxxx`

HTTPError 422 according to AirTable:
Invalid Request The request data is invalid. This includes most of the base-specific validations. You will receive a detailed error message and code pointing to the exact issue.

Unfortunately there is no detailed error message pointing to the exact issue.

Hope you can help! What's going wrong with updating the images?

Maybe Add generators to your code

I'm working with a client using your api, And I'm having problems with it.
everything is working fine but it needs a little improvement, instead of getting an entire table with the at.get attribute try to code a generator that will provide a records to work on when looping throught an entire base

Submit to PyPI

Hi, I was wondering if you could submit this package to PyPI so that I could add it to my requirements.txt with the rest of my dependencies? Thanks for this library!

Add support for searching

This is more of a heads up that we pushed out new API capabilities. Airtable/airtable.js@08e6e76

We now accept a formula to filter records and an array of field/direction pairs to sort by.

The limit is deprecated in favor of pageSize and maxRecords.

code error : "from .params import AirtablePar"

I would like to use airtable API python. I installed it on Linux Ubuntu and I use pycharm.

with "import airtable" or "from airtable.airtable import Airtable"
I have a code error : "from .params import AirtablePar" ImportError: cannot import name 'AirtablePar'

and pycharm exit, code error 1.

Could I have help ? Thanks a lot !

no module Airtable

hi,

I have installed your module by doing
"pip install airtable"

that worked fine.

however no module call Airtable is to be found:

from airtable import Airtable
Traceback (most recent call last):
File "", line 1, in
ImportError: cannot import name 'Airtable'

what's the issue?

thx

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.