app_id = $app_id; $this->api_key = $api_key; } /** * List records */ public function list( $table, $options = array() ) { $query = build_query( $options ); // Build Airtable API URL $url = $this->endpoint . "/$this->app_id/$table?$query"; // Make API Call $response = wp_remote_get( $url, $this->get_request_args() ); return $this->validate_response( $response ); } /** * Get record */ public function get( $table, $record_id, $options = array() ) { $query = build_query( $options ); // Build Airtable API URL $url = $this->endpoint . "/$this->app_id/$table/$record_id?$query"; // Make API Call $response = wp_remote_get( $url, $this->get_request_args() ); return $this->validate_response( $response ); } /** * Create record */ public function create( $table, $data = array() ) { $data = wp_json_encode( array( 'records' => $data ) ); if ( false === $data ) { throw new Exception( 'Cannot encode data into json' ); } // Build Airtable API URL $url = $this->endpoint . "/$this->app_id/$table"; // Make API Call $response = wp_remote_post( $url, $this->get_request_args( array( 'body' => $data ) ) ); return $this->validate_response( $response ); } /** * Update record */ public function update() {} /** * Build request args */ protected function get_request_args( $args = array() ) { return array_merge( array( 'headers' => array( 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', ), 'timeout' => 15, ), $args ); } /** * Validate HTTP Response and returns data */ protected function validate_response( $response ) { if ( is_wp_error( $response ) ) { throw new Exception( sprintf( 'Airtable API: %s', $response->get_error_message() ) ); } // Check HTTP code $reponse_code = wp_remote_retrieve_response_code( $response ); if ( 200 !== $reponse_code ) { $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body ); if ( ! empty( $data->error ) ) { throw new Exception( sprintf( 'Airtable API: %s', ! empty( $data->error->message ) ? $data->error->message : $data->error ) ); } throw new Exception( sprintf( 'Airtable API: Received HTTP Error, code %s', $reponse_code ) ); } // Get JSON data from request body $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body ); if ( is_null( $data ) ) { throw new Exception( 'Airtable API: Couldnt decode JSON response' ); } return $data; } }