# Getting Started with Lark Base Python SDK
Welcome! This guide will help you get up and running with the Lark Base Python SDK in minutes.
## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Installation](#installation)
3. [Configuration](#configuration)
4. [Quick Start](#quick-start)
5. [First Steps](#first-steps)
6. [Next Steps](#next-steps)
## Prerequisites
Before you begin, ensure you have:
- **Python 3.8 or higher** installed
- A **Lark/Feishu account** with access to Lark Base
- A **Lark Open Platform app** (we'll create one if you don't have it)
## Installation
### Step 1: Navigate to the Python SDK directory
```bash
cd /Users/mdch/hype-dash/python
```
### Step 2: Install dependencies
```bash
pip install -r requirements.txt
```
This will install:
- `lark-oapi` - Official Lark Open API SDK
- `python-dotenv` - Environment variable management
- `requests` - HTTP client library
## Configuration
### Step 1: Create a Lark Open Platform App
1. Go to [Lark Open Platform](https://open.larksuite.com/)
2. Click "Create App" or use an existing app
3. Note your **App ID** and **App Secret** from the app credentials page
### Step 2: Enable Permissions
In your app's permission settings, enable:
- `bitable:app` - Manage base apps
- `bitable:app:readonly` - Read base apps
### Step 3: Get Your Base App Token
1. Open your Lark Base in a browser
2. Look at the URL: `https://xxx.larksuite.com/base/bascnXXXXXXXXXXXX`
3. Copy the `bascnXXXXXXXXXXXX` part - this is your app token
### Step 4: Create Environment File
Copy the example environment file:
```bash
cp .env.example .env
```
Edit `.env` with your credentials:
```env
LARK_APP_ID=cli_xxxxxxxxxxxxxxxx
LARK_APP_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
LARK_APP_TOKEN=bascnxxxxxxxxxxxxxxxxxxxxxxx
LOG_LEVEL=INFO
```
## Quick Start
### Verify Your Setup
Run the quick start script to verify everything is configured correctly:
```bash
python quickstart.py
```
You should see:
```
✓ All environment variables are set!
✓ Client initialized successfully
✓ Successfully connected to Lark Base
✓ Found X tables in your base
```
### Your First Script
Create a file called `my_first_script.py`:
```python
from dotenv import load_dotenv
import os
from lark_client import LarkBaseClient, LarkConfig
# Load environment variables
load_dotenv()
# Initialize client
config = LarkConfig(
app_id=os.getenv('LARK_APP_ID'),
app_secret=os.getenv('LARK_APP_SECRET'),
log_level='INFO'
)
client = LarkBaseClient(config)
# Get your app token
app_token = os.getenv('LARK_APP_TOKEN')
# List all tables
tables = client.list_tables(app_token)
print(f"Found {len(tables)} tables:")
for table in tables:
print(f" - {table['name']}")
```
Run it:
```bash
python my_first_script.py
```
## First Steps
### 1. Create a Table
```python
# Create a new table
table_id = client.create_table(
app_token=app_token,
table_name="My First Table",
default_view_name="All Items"
)
print(f"Created table: {table_id}")
```
### 2. Add Fields
```python
# Add a text field
name_field = client.create_field(
app_token=app_token,
table_id=table_id,
field_name="Name",
field_type=1 # Text
)
# Add a number field
price_field = client.create_field(
app_token=app_token,
table_id=table_id,
field_name="Price",
field_type=2 # Number
)
```
### 3. Create Records
```python
# Create a single record
record_id = client.create_record(
app_token=app_token,
table_id=table_id,
fields={
"Name": "Product A",
"Price": 99.99
}
)
print(f"Created record: {record_id}")
```
### 4. Read Records
```python
# Get all records
records = client.get_all_records(app_token, table_id)
print(f"Total records: {len(records)}")
for record in records:
print(f" {record['fields']['Name']}: ${record['fields']['Price']}")
```
### 5. Update Records
```python
# Update a record
client.update_record(
app_token=app_token,
table_id=table_id,
record_id=record_id,
fields={"Price": 79.99}
)
print("Record updated!")
```
## Next Steps
### Run the Examples
We've included three comprehensive examples:
#### 1. Basic Usage
```bash
python examples/basic_usage.py
```
Learn:
- Creating tables and fields
- CRUD operations
- Batch operations
- Filtering and pagination
#### 2. TikTok Data Sync
```bash
python examples/sync_tiktok_data.py
```
Learn:
- Syncing external data sources
- Data transformation
- Incremental updates
- Metrics calculation
#### 3. Batch Operations
```bash
python examples/batch_update.py
```
Learn:
- Bulk operations (100+ records)
- Data validation
- Field mapping
- Aggregation
- Parallel processing
### Use the Data Manager
For more advanced operations, use the `DataManager` class:
```python
from data_manager import DataManager
data_manager = DataManager(client)
# Upsert records (create or update)
result = data_manager.batch_upsert_records(
app_token=app_token,
table_id=table_id,
records=my_records,
key_field="ID"
)
print(f"Created: {result['created']}")
print(f"Updated: {result['updated']}")
```
### Create Dashboards
Once you have data in Lark Base, create dashboards using the TypeScript SDK:
```typescript
import { LarkDashboardClient, ChartBlockBuilder } from '@hypelab/hype-dash';
const client = new LarkDashboardClient({
apiKey: process.env.LARK_API_KEY
});
// Create a chart from your Python-synced data
const chart = ChartBlockBuilder.bar()
.dataSource(appToken, tableId)
.xAxis({ fieldName: 'Name' })
.yAxis([{ fieldName: 'Price', aggregation: AggregationType.SUM }])
.build();
```
Your dashboards will automatically update when you update the data via Python!
## Common Use Cases
### Sync Data from APIs
```python
import requests
def fetch_external_data():
response = requests.get('https://api.example.com/data')
return response.json()
# Transform and load
data = fetch_external_data()
result = data_manager.transform_and_load(
app_token=app_token,
table_id=table_id,
source_records=data,
transformer=my_transform_function,
key_field='id'
)
```
### Validate Before Loading
```python
validation = data_manager.validate_records(
records=my_records,
required_fields=['name', 'email'],
validators={
'email': lambda x: '@' in str(x),
'price': lambda x: x >= 0
}
)
if validation['valid_count'] > 0:
# Load only valid records
client.batch_create_records(
app_token,
table_id,
validation['valid_records']
)
```
### Schedule Regular Syncs
```python
from datetime import datetime, timedelta
import time
def sync_job():
last_sync = datetime.now() - timedelta(hours=1)
result = data_manager.sync_data_incremental(
app_token=app_token,
table_id=table_id,
data_source=fetch_external_data,
key_field='id',
timestamp_field='updated_at',
last_sync_time=last_sync
)
print(f"Synced {result['updated']} records")
# Run every hour
while True:
sync_job()
time.sleep(3600) # 1 hour
```
## Need Help?
### Documentation
- **README.md** - Comprehensive API reference
- **CHANGELOG.md** - Version history and features
- **Examples** - Three detailed example scripts
### Support
- GitHub Issues: https://github.com/hypelab/hype-dash/issues
- Email: dev@hypelab.com
### Common Issues
**Import Error**
```bash
pip install -r requirements.txt
```
**Authentication Error**
- Check your App ID and App Secret
- Verify permissions are enabled
- Ensure app token is correct
**Rate Limit Error**
```python
# Reduce rate limit
client = LarkBaseClient(config, rate_limit=5)
```
## What's Next?
You're now ready to:
1. Sync data from your external sources
2. Transform and validate data
3. Create automated data pipelines
4. Build dashboards that visualize your data
Happy coding!