Code Monkey home page Code Monkey logo

airtable-php's Introduction

Airtable PHP client

Installation

composer require zadorin/airtable-php

Usage

Basic setup

$apiKey = 'key***********';
$database = 'app***********';
$tableName = 'my-table';

$client = new \Zadorin\Airtable\Client($apiKey, $database);

You can find API key in your account settings and database name in API Docs.

Insert some rows

$client->table($tableName)
    ->insert([
        ['name' => 'Ivan', 'email' => '[email protected]'],
        ['name' => 'Peter', 'email' => '[email protected]']
    ])
    ->execute();

Fetch multiple rows

$recordset = $client->table($tableName)
    ->select('id', 'name', 'email') // you can use shortcut select('*') to fetch all columns
    ->where(['name' => 'Ivan', 'email' => '[email protected]'])
    ->orderBy(['id' => 'desc'])
    ->limit(10)
    ->execute();

var_dump($recordset->fetchAll()); // returns set of Record objects
var_dump($recordset->asArray()); // returns array of arrays

Fetch specific rows by record id

$recordset = $client->table($tableName)
    ->find('rec1*******', 'rec2*******')
    ->execute();

Iterate and update records

while ($record = $recordset->fetch()) {
    var_dump($record->getId()); // rec**********
    var_dump($record->getFields()); // [id => 1, name => Ivan, email => [email protected]]

    $record->setFields(['name' => 'Ivan the 1st']);
    $client->table($tableName)->update($record);
}

Pagination

$query = $client->table($tableName)
    ->select('*')
    ->orderBy(['id' => 'desc'])
    ->paginate(50); // limit(50) works the same. Default (and maximal) page size is 100

while ($recordset = $query->nextPage()) {
    var_dump($recordset->fetchAll());
}

Remove rows

$records = $client->table($tableName)
    ->select('id', 'email')
    ->where(['email' => '[email protected]'])
    ->execute()
    ->fetchAll();

$client->delete(...$records)->execute();

Complex filters

You can build complex formulas to filter records, but be careful, because formula applies to each record and can slow down your query.

Assume we prepared following query object:

$query = $client->table('my-table')->select('*');

Query builder

The following lines give the same results:

$query->where(['email' => '[email protected]']);
$query->where('email', '[email protected]');
$query->where('email', '=', '[email protected]');

You can use different logical operators:

$query->where('email', '!=', '[email protected]');
$query->where('code', '>', 100);

It's possible to concat multiple where statements:

$query->where([
    ['code', '>', 100],
    ['code', '<', 200],
]);

Or chain methods to achieve the same result:

$query->where('code', '>', 100)->andWhere('code', '<', 200);

Note you should chain andWhere() or orWhere() methods. Don't do this:

$query->where('code', '>', 100)->where('code', '<', 200);

Because client will use only last condition (code < 200).

OR-logic

$query->where('name', 'Ivan')->orWhere('id', 5);

Methods where(), andWhere(), orWhere() use the same signature, so you can combine them:

$query->where('code', '>', 100)
    ->andWhere('code', '<', 500)
    ->orWhere([
        ['code', '<', 100],
        ['id', '=', 5]
    ]);

Raw formula

You can see what exact formula was built:

$query->where([
    ['Code', '>', 100],
    ['Code', '<', 300]
])
->orWhere('Name', 'Qux');
    
$query->getFormula(); // OR(AND({Code}>'100', {Code}<'300'), {Name}='Qux')

Also you can filter records by raw formula:

$query->whereRaw("OR( AND({Code}>'100', {Code}<'300'), {Name}='Qux' )");

Note that library don't validate raw formulas so you can get exception from Airtable API.

Throttling

Airtable API is limited to 5 requests per second per base. Client uses simple throttling library to keep this limit.

You can disable this behavior:

$client = new \Zadorin\Airtable\Client($apiKey, $database);
$client->throttling(false);

Debug

Client keeps last request object so you can use this for debugging purposes.

Be careful with debug information because it contains all HTTP headers including authorization token

$recordset = $client->table($tableName)->select('*')->execute();
$request = $client->getLastRequest();

$request->getResponseCode(); // http code (int)
$request->getPlainResponse(); // response body (string)
$request->getResponseInfo(); // array provided by curl_getinfo()

Exceptions

All package exceptions inherits from common Zadorin\Airtable\Errors\AirtableError class.

Also you may be interested in Zadorin\Airtable\Errors\RequestError which contains last request instance:

try {
    $inserted = $client->table($tableName)->insert()->execute();
} catch (RequestError $e) {
    
    // catch Airtable responses here
    var_dump($e->getMessage());
    var_dump($e->getLastRequest()->getResponseInfo());

} catch (AirtableError $e) {

    // catch package errors. In that case it will be "No records specified for insert"

}

ToDo

[ ] Simple joins

[ ] Clean up code

Known problems

Client uses ext-curl to make requests and ext-json to encode/decode results. Make sure this php extensions installed and properly configured.

If you see SSL certificate problem: unable to get local issuer certificate you probably have to configure option curl.cainfo in your php.ini. Source

License and contributing

MIT License. Any feedback is highly appreciated โ€” welcome to issues.

If you want to send pull request make sure all tests are pass.

Tests

Copy this readonly test database into your Airtable account, then fill env variables specified in phpunit.xml.dist.

And finally run test suite:

./vendor/bin/pest

It's also recommended to use static analysis tool to avoid errors:

./vendor/bin/psalm

airtable-php's People

Contributors

eugenezadorin avatar

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.