Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Slack Web API SDK

Built with APIMatic License: MIT Python 3.10+

The Slack Web API SDK for Python provides access to the Slack Web API REST APIs from Python applications.

Tip

Looking for a specific signature, model, enum, or error type? This SDK ships a generated SDK map -- a lookup index of the SDK's entire Python surface. Consult it before scanning the source tree; details under SDK map.

One way to interact with the Slack platform is its HTTP RPC-based Web API, a collection of methods requiring OAuth 2.0-based user, bot, or workspace tokens blessed with related OAuth scopes.


Installation

Add the Python SDK to your project from its folder, with whichever package manager your project uses. Give each tool a path containing a slash, such as ../slack-web-api — a bare folder name is looked up on PyPI instead, and resolves to whatever project holds that name there:

pip install <path-to-sdk>
uv add <path-to-sdk>
poetry add <path-to-sdk>

Quick Start

Synchronous client

Construct SlackWebApiClient with keyword arguments, and call close() when you are done. Every argument is optional; the full list is in the SDK map.

from slack_web_api import SlackWebApiClient
from slack_web_api.auth import SlackAuthScope
from slack_web_api.core import AuthorizationCodeCredentials


def prompt(url: str) -> str:
    return input(f"Open {url}, then paste the code: ")


client = SlackWebApiClient(
    slack_auth=AuthorizationCodeCredentials[SlackAuthScope](
        client_id="YOUR_CLIENT_ID", redirect_uri="YOUR_REDIRECT_URI", prompt_for_authorization_code=prompt
    ),
)

# TODO: call endpoints here -- see api-reference.md

client.close()

Alternatively, scope it -- with SlackWebApiClient(...) as client: closes the pool on exit; see Best Practices.

Client is exported as an alias of SlackWebApiClient, so from slack_web_api import Client also works.

The SDK accepts every model-typed input in two interchangeable spellings, both type-checked: the typed model, or a plain dict with the same keys -- the OrDict and Model | ModelDict unions in the SDK map. Pick whichever suits the call site: the dict form needs no import, while the model form adds a keyword-checked constructor and editor completion.

Asynchronous client

AsyncSlackWebApiClient mirrors SlackWebApiClient with identical method names, and every endpoint method is a coroutine. It takes the same arguments, with some differences -- for example, the transport argument is custom_async_http_client.

from asyncio import run, to_thread

from slack_web_api import AsyncSlackWebApiClient
from slack_web_api.auth import SlackAuthScope
from slack_web_api.core import AsyncAuthorizationCodeCredentials


async def prompt(url: str) -> str:
    print(f"Open {url}")
    return await to_thread(input, "Paste the code: ")


async def main() -> None:
    client = AsyncSlackWebApiClient(
        slack_auth=AsyncAuthorizationCodeCredentials[SlackAuthScope](
            client_id="YOUR_CLIENT_ID", redirect_uri="YOUR_REDIRECT_URI", prompt_for_authorization_code=prompt
        ),
    )
    # TODO: call endpoints here, awaiting each -- see api-reference.md
    await client.aclose()


run(main())

Alternatively, scope it -- async with AsyncSlackWebApiClient(...) as client: closes the pool on exit. Only the async spelling is aclose, matching httpx2; see Best Practices.

AsyncClient is the exported alias. Each client accepts only its own transport argument and its own prompt flavour; passing the other's is a TypeError at runtime and an error under mypy.


Usage

Two generated references cover the SDK; each answers a different question:

Reference For
API Reference Usage guidance for a single parsed operation: client.<group>.<operation>(...) returns the typed payload and raises ApiError on any non-2xx, with .error the typed error body, or RawError for a status the operation does not document.
Raw API Reference The same for the raw variant: client.<group>.with_raw_response.<operation>(...) returns ApiResult[T, E] and never raises for an API error.

Both API references carry every one of the 253 operations, with a sync and an async sample and a parameter table each.

SDK map

This SDK ships a generated SDK map -- sdk-map.md -- a deterministic, lookup-oriented table of contents of the SDK's Python surface, generated by APIMatic alongside this SDK.

Consult the map before scanning or grepping the source: it answers call-level contract questions by lookup, and for anything it does not carry -- model shapes, enum values, an endpoint's route or behavioural prose -- it names the one source file to read. How to read the map itself, including the SDK-wide defaults its rows rely on, is stated at the top of sdk-map.md.

Error handling

Everything the SDK raises for a call derives from SdkError, which names the call as method and url (the path, never the query); the underlying exception is __cause__. No message carries a response body. The raw variant (.with_raw_response) returns an error status as a Failure instead of raising ApiError; the rest of the family raises in both modes.

from slack_web_api.core import ApiError, SdkConnectionError, SdkError

try:
    response = client.admin.admin_apps_approve("some example string", ContentType.APPLICATION_X_WWW_FORM_URLENCODED)
except ApiError as e:
    # An error status: the decoded body is e.error.
    print(e.status_code, e.error)
except SdkConnectionError as e:
    # No response, or the body could not be read.
    print(e, repr(e.__cause__))
except SdkError as e:
    # Anything else the SDK raises for a call.
    print(e)
except Exception as e:
    # Not a call failure: input refused before sending (ValueError), a handler you wrote raising, or a bug here.
    print(f"not a call failure: {e!r}")
    raise e
Exception When Extra attributes
ApiError[E] an error status error, status_code, headers
ResponseDecodeError a body that does not match its declared type status_code, headers
SdkConnectionError the request could not be sent, or the body could not be read
SdkTimeoutError a SdkConnectionError that timed out timeout
AuthSchemeError a credential could not be applied scheme_failures

Your own cancellation is never wrapped, and a value the SDK refuses before sending stays a ValueError. Each operation's typed error arms are on its SDK map page.

Logging

The SDK logs every HTTP exchange through Python's standard logging module, under the slack_web_api logger, and configures nothing itself: with no logging set up, nothing is printed unless SLACK_WEB_API_LOG is set. Turn it on as for any library:

import logging

logging.basicConfig()  # your application's handler; the root stays at WARNING
logging.getLogger("slack_web_api").setLevel(logging.INFO)  # the SDK's lines; DEBUG adds the dumps that logging_options turns on

Or set one environment variable before the process starts, for a run you cannot edit: SLACK_WEB_API_LOG=info writes the request and response lines, SLACK_WEB_API_LOG=debug adds the request headers, the request body and the response headers. If your application has configured logging, its handlers and format are used; otherwise the SDK writes to stderr.

Choose the detail with logging_options, a LoggingOptions from slack_web_api.core:

from slack_web_api import SlackWebApiClient
from slack_web_api.core import LoggingOptions

client = SlackWebApiClient(
    logging_options=LoggingOptions(log_request_headers=True, log_response_headers=True, log_request_body=True)
)

A plain dict with the same keys is accepted too, as for every model-typed argument (see Quick Start): logging_options={"log_request_headers": True}.

Option Default Effect
log_request_headers False Log the sent headers at DEBUG, masked.
log_response_headers False Log the received headers at DEBUG, masked.
log_request_body False Log the request body at DEBUG: its text when in memory, a description when streamed.
body_size_limit 32768 Bytes of a logged body kept before it is cut.
redaction_placeholder "REDACTED" What a hidden value prints as.
unmask_headers none Header names to show although they are not on the safe list.
mask_headers none Header names to hide although they are on the safe list.
mask_keys 11 credential names Query and form keys whose values are always hidden; naming a set replaces the default.

A single call can be quietened with request_options={"log_level": logging.WARNING}: records below that level are not written for that call. It never turns on a record the client's options leave off. Header, query and form values print REDACTED unless known safe; a JSON body is printed as sent, so enable log_request_body only where its content may be logged; a response body is never logged. The levels and every field are under Logging in the SDK map.

Hooks

A hook is your code run on every attempt of every request. before_request gets the request after it is built and authenticated, and returns the request to send. after_response gets the response and returns the one the call acts on: the same one, or your own object implementing HttpResponse. Subclass SdkHook and override either one, or pass plain functions keyed by the event they run on:

from dataclasses import replace

from slack_web_api import SlackWebApiClient
from slack_web_api.core import HookContext, HttpRequest, HttpResponse, SdkHook


# new_traceparent() and record() stand for your own tracer and metrics sink.
class Tracing(SdkHook):
    def before_request(self, request: HttpRequest, context: HookContext) -> HttpRequest:
        return replace(request, headers={**request.headers, "traceparent": new_traceparent()})

    def after_response(self, response: HttpResponse, context: HookContext) -> HttpResponse:
        record(context.method, context.url, response.status_code)
        return response


client = SlackWebApiClient(hooks=[Tracing()])


# Or plain functions, with nothing to subclass:
def add_tenant(request: HttpRequest, context: HookContext) -> HttpRequest:
    return replace(request, headers={**request.headers, "x-tenant": "acme"})


def print_status(response: HttpResponse, context: HookContext) -> HttpResponse:
    print(context.method, response.status_code)
    return response


client = SlackWebApiClient(hooks={"on_request": [add_tenant], "on_response": [print_status]})

A single call adds its own the same way, request_options={"hooks": {"on_request": [add_tenant]}} or {"hooks": [Tracing()]}: they run after the client's, never instead of them.

Two spellings, one per place. hooks takes a list of hook objects or the {"on_request": [...], "on_response": [...]} dict, on the client and in request_options alike — not a mix of the two in one place. A hook that keeps state between the request and its response is a class. A key other than those two is a type error, and is ignored at run time.

When they run. On every attempt, retries included, after authentication: the client's hooks, then the call's.

On AsyncSlackWebApiClient the same shape is AsyncSdkHook, whose methods are async def and take an AsyncHookContext and an AsyncHttpResponse; the dict takes async def functions under the same two keys, and a call's hooks go in AsyncRequestOptions. A hook of the other client's flavour is a type error, not a run-time check.

Changing the response. The retry decision and the result read the response the last hook returns; the log line shows what the server sent. A hook that reads the body must return a response that still carries it, and one that returns a different response must close the original or keep it inside.

Best Practices

Tip

Use a single SlackWebApiClient instance for the lifetime of your application and reuse it across all requests. Each instance owns its own connection pool, so an instance per request forfeits connection reuse and leaks pools that are never closed.

Match the disposal to the client's lifetime: an application-lifetime client is closed once at shutdown with close() / aclose(); where the lifetime fits a block, with SlackWebApiClient() as client: / async with AsyncSlackWebApiClient() as client: releases it automatically. Both are idempotent, but a closed client is not reusable: the next call raises. The client closes whatever transport it holds, including one you supplied via custom_http_client / custom_async_http_client; if you intend to reuse your own transport across clients, don't hand its lifetime to a with block.

Retries are on by default: a failed idempotent request — a retryable status or no response at all — is sent again up to three times before the call gives up. Pass retry_options=0 to turn it off, for instance in a test that stubs an error response; the policy and its defaults are under Retries in the SDK map.

License

This SDK is distributed under the MIT License.


Support

Refer to the API reference for detailed information on available operations with code samples.


About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages