Skip to main content

Feishu OpenPlatform Server SDK for Python

中文

The Feishu Open Platform provides server-side APIs for messaging, contacts, approval, sheets, Base, and many other product capabilities. This SDK wraps the repeated platform work around API calls, including token management, request signing, encryption/decryption, event dispatching, and typed request/response models.

Documentation

Installation

pip install lark-oapi

Python 3.8 or later is required.

Basic Usage

import lark_oapi as lark
from lark_oapi.api.im.v1 import *

client = lark.Client.builder() \
    .app_id("cli_xxx") \
    .app_secret("your_app_secret") \
    .build()

request = CreateMessageRequest.builder() \
    .receive_id_type("chat_id") \
    .request_body(CreateMessageRequestBody.builder()
        .receive_id("oc_xxx")
        .msg_type("text")
        .content("{\"text\":\"hello world\"}")
        .build()) \
    .build()

response = client.im.v1.message.create(request)

ClientAssertion Keyless Mode

For self-built apps that use an external signing service, the SDK can fetch tenant tokens with client_assertion instead of app_secret. The SDK does not generate, parse, sign, or store JWT private keys; your provider supplies the final assertion string.

import os

import lark_oapi as lark
from lark_oapi.core.client_assertion import ClientAssertionToken


class EnvClientAssertionProvider:
    def retrieve_token(self, aud: str) -> ClientAssertionToken:
        return ClientAssertionToken(os.environ["LARK_CLIENT_ASSERTION"])


client = lark.Client.builder() \
    .app_id(os.environ["LARK_APP_ID"]) \
    .client_assertion_provider(EnvClientAssertionProvider()) \
    .build()

If you use a custom OpenAPI domain, also configure oauth_base_url(...) so the SDK can derive the OAuth audience correctly. Keyless mode is for self-built apps only and does not support AppAccessToken-only APIs.

One-Click App Registration

lark_oapi.register_app creates an app through the OAuth device flow. It returns a verification URL in on_qr_code; render the URL as a QR code or show it as a link for the user to open in Feishu/Lark.

import lark_oapi as lark

def on_qr_code(info):
    print(info["url"])


result = lark.register_app(
    on_qr_code=on_qr_code,
    app_preset={
        "avatar": [
            "https://example.com/a.png",
            "https://example.com/b.webp",
        ],
        "name": "{user}'s app",
        "desc": "Created by the business platform",
    },
)

print(result["client_id"])

Custom scopes/events/callbacks and updating an existing app

When creating an app, use addons to incrementally request scopes, event subscriptions, and callbacks on top of the platform base template. They are pre-filled into the confirm page shown after the user scans the QR code, and take effect once the user confirms:

result = lark.register_app(
    on_qr_code=on_qr_code,
    addons={
        "scopes": {
            "tenant": ["im:message:send_as_bot"],
            "user": ["calendar:calendar:read"],
        },
        "events": {"items": {"tenant": ["im.message.receive_v1"]}},
        "callbacks": {"items": ["card.action.trigger"]},
    },
    create_only=True,
)

lark.register_app(
    on_qr_code=on_qr_code,
    app_id="cli_xxx",
    addons={"scopes": {"tenant": ["drive:drive.metadata:readonly"]}},
)

Notes:

  • addons is additive only: items are merged on top of the base template; base permissions can never be removed.
  • addons.preset picks the base template: omitted or True keeps the default base template, while False switches to the minimal base template so the final config only contains what addons declares. With "preset": False, an addons without any incremental item is also valid.
  • Only the 5 public config types are supported: tenant/user scopes, tenant/user events, and callbacks. Sensitive config such as event request URLs, security.*, or encrypt keys cannot travel through addons.
  • The SDK validates the shape, not the item names; names unknown to the platform catalog are ignored by the confirm page.

For a real manual E2E run without mocked registration responses:

python3 samples/registration/app_preset_live_e2e.py --open

register_app parameters

Parameter Description Type Required Default
on_qr_code Callback when the verification URL is ready. Receives {"url": str, "expire_in": int} function Yes -
on_status_change Callback on polling status changes. Status values include polling, slow_down, domain_switched function No -
source Source identifier appended to the QR URL as python-sdk/{source} string No python-sdk
cancel_event threading.Event used to cancel sync polling threading.Event No -
domain Custom Feishu accounts base URL string No https://accounts.feishu.cn
lark_domain Custom Lark accounts base URL used when tenant brand is Lark string No https://accounts.larksuite.com
app_preset Pre-fill values for the app-creation page. All fields are optional; users can still edit them on the page. Pass raw values; the SDK URL-encodes them automatically dict No -
app_preset.avatar App avatar URL(s). 1-6 URLs supported; the first one is selected by default. Allowed formats are handled by the Web page: png / jpg / jpeg / webp / gif string or list[string] No -
app_preset.name App name. Supports the {user} placeholder, replaced by the Web page with the scanning user's name string No -
app_preset.desc App description. Supports the {user} placeholder string No -
addons Incremental scopes/events/callbacks pre-filled into the confirm page, effective after user confirmation dict No -
addons.preset Base template switch. Omitted or True keeps the default base template; False switches to the minimal base template so the app only carries the configs explicitly declared in addons bool No True
addons.scopes.tenant App-identity scopes, e.g. im:message:send_as_bot list[string] No -
addons.scopes.user User-identity scopes, e.g. calendar:calendar:read list[string] No -
addons.events.items.tenant App-identity events, e.g. im.message.receive_v1 list[string] No -
addons.events.items.user User-identity events, e.g. calendar.calendar.event.changed_v4 list[string] No -
addons.callbacks.items Callbacks, e.g. card.action.trigger list[string] No -
create_only When True, the landing page only allows creating a new app and hides the select-existing-app entry. Takes precedence over app_id when both are set bool No -
app_id App ID (cli_ prefix) of an existing app. When set, the flow updates that app's config; carried on the QR URL as clientID string No -

Legacy Channel Module

lark_oapi.channel is the legacy Channel entry point kept for compatibility during the migration window. New Channel features ship in lark-channel-sdk with the lark_channel import path; critical fixes for existing lark_oapi.channel users are evaluated for backport until 2027-06-02.

lark-channel-sdk can be installed alongside lark-oapi. Its SecurityConfig defaults to compatibility mode so migrated bots can roll out with audit mode before strict enforcement. See the migration guide for the full checklist.

pip install lark-channel-sdk
from lark_channel import FeishuChannel

Existing legacy import example:

import asyncio
import os

from lark_oapi.channel import FeishuChannel

channel = FeishuChannel(
    app_id=os.environ["LARK_APP_ID"],
    app_secret=os.environ["LARK_APP_SECRET"],
)

async def on_message(msg):
    await channel.send(
        msg.chat_id,
        {"text": f"echo: {msg.content_text}"},
    )

channel.on("message", on_message)

asyncio.run(channel.connect())

Channel documentation:

Examples

More composite API examples and business scenario samples are available in oapi-sdk-python-demo.

License

MIT

Contact Us

Click Server SDK in the upper right corner of the documentation page and submit feedback.

Webhook authentication

When no EncryptKey is configured and a nonempty VerificationToken is explicitly supplied, the SDK validates the token before invoking event or callback handlers: top-level token for v1 and header.token for v2. Missing, null, empty, non-string, or mismatched tokens are rejected. Challenge responses also validate explicitly configured verification tokens.

Leaving both credentials empty retains the previous behavior. Encrypted events retain existing decryption and signature checks, and WebSocket clients continue using trusted internal dispatch.

Rollback: reverting this change restores the validation gap for explicitly configured VerificationTokens. Keep independent webhook authentication in place before rolling back.

Runtime webhook credentials

Register a combined provider while building the handler:

handler = (lark.EventDispatcherHandler.builder("", "")
    .webhook_credentials_provider(credential_store.get_webhook_credentials)
    .build())

The provider is called once per HTTP webhook (events, callbacks, and challenge), before decryption and validation. It is not called while building the handler or by trusted WebSocket dispatch. The returned pair overrides static credentials for that request only; the next request sees updates. The example store method returns a lark.WebhookCredentials value and reads the complete pair atomically from a thread-safe local cache. Providers must return promptly, with caller-owned timeouts for any I/O. Empty strings retain legacy empty-configuration behavior. Invalid results and exceptions reject the request without static fallback, and original exception details are not logged or returned. Provider registration is initialization-only. Monitor acquisition latency and failures in the provider. Remove the provider registration to return to static credentials.

WebSocket connection host and handshake headers

domain controls HTTP endpoint discovery. The optional connection host replaces only the WebSocket URL host[:port], preserving scheme, path and query. Default DNS and TLS/SNI follow the resulting hostname; existing custom transport settings still apply. Domains below are placeholders.

client = lark.ws.Client(
    os.environ["APP_ID"], os.environ["APP_SECRET"],
    domain="https://bootstrap.example.com",
    connection_host="websocket.example.com:443",
    connection_headers={"X-Route": "events"},
    event_handler=event_handler,
)

Handshake headers are copied at initialization and for each handshake, including reconnects, and are never forwarded to endpoint discovery. Omitting both settings preserves existing behavior. Host, Connection, Upgrade and Sec-WebSocket-* cannot be overridden through headers. Basic host checks reject empty values, schemes/paths and query parameters; other address and header settings are passed to the underlying libraries without additional SDK format checks. These basic host and reserved-header checks run before network I/O (Start returns an error in Go; construction/build throws in other SDKs). Use trusted developer configuration, not headers/hosts supplied by an end-user request.

Metadata

Release files for lark-oapi 1.7.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lark-oapi 1.7.5
File Size Uploaded
lark_oapi-1.7.5.tar.gz 2.4 MB Details

Built distribution (wheel)

Table of built distributions (wheels) for lark-oapi 1.7.5
File Interpreter ABI Platform
lark_oapi-1.7.5-py3-none-any.whl Python 3 none any Details

Total release size: 10.1 MB

Release files / lark_oapi-1.7.5.tar.gz

Download URL lark_oapi-1.7.5.tar.gz
Size 2.4 MB
Tags Source
SHA-256 checksum
How to use checksums
81258795e7cfc5ef797e71aff14435359a2abaf698ef0e6f9d3857fe08b719ab
BLAKE2b-256 checksum
How to use checksums
08da8dc51e0e808b7f84c4598869a057aa46f0c0f8d27872e0ff87a6512f3b93
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / lark_oapi-1.7.5-py3-none-any.whl

Download URL lark_oapi-1.7.5-py3-none-any.whl
Size 7.7 MB
Tags Python 3
SHA-256 checksum
How to use checksums
ff70fd5cdf436e26d80bf903fdd7a80cbdbd71981b87ce4c2aa49bb95fc96020
BLAKE2b-256 checksum
How to use checksums
217b54d1df1f73ac1339b7df051982d386223202add5560a97839cf6326e6adc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release history Release notifications | RSS feed

This release

1.7.5 This release

2 release files

1.7.4

2 release files

1.7.3

2 release files

1.7.2

2 release files

1.7.1

2 release files

1.7.0

1 release file

1.6.9

1 release file

1.6.8

1 release file

1.6.7

1 release file

1.6.6

1 release file

1.6.5

2 release files

1.6.4

2 release files

1.6.3

2 release files

1.6.2

2 release files

1.6.1

2 release files

1.6.0

2 release files

1.5.5

1 release file

1.5.4

1 release file

1.5.3

1 release file

1.5.2

1 release file

1.5.1

1 release file

1.4.24

1 release file

1.4.23

2 release files

1.4.22

2 release files

1.4.21

2 release files

1.4.20

2 release files

1.4.19

2 release files

1.4.18

2 release files

1.4.17

2 release files

1.4.16

2 release files

1.4.15

2 release files

1.4.14

2 release files

1.4.12

2 release files

1.4.10

2 release files

1.4.9

2 release files

1.4.8

2 release files

1.4.6

2 release files

1.4.5

2 release files

1.4.3

2 release files

1.4.0

2 release files

1.3.6

2 release files

1.3.5

2 release files

1.3.4

2 release files

1.3.3

2 release files

1.3.1

2 release files

1.3.0

2 release files

1.2.10

2 release files

1.2.9

2 release files

1.2.8

2 release files

1.2.7

2 release files

1.2.6

2 release files

1.2.5

2 release files

1.2.4

2 release files

1.2.3

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.0.28

2 release files

1.0.26

2 release files

1.0.25

2 release files

1.0.24

2 release files

1.0.23

2 release files

1.0.21

2 release files

1.0.19

2 release files

1.0.18

2 release files

1.0.17

2 release files

1.0.16

2 release files

1.0.15

2 release files

1.0.9

2 release files

1.0.8

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.5

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page