Designing Python Apis logo

Designing Python Apis

Community
wdm0006
designing-python-apis

Designs intuitive Python library APIs following principles of simplicity, consistency, and discoverability. Handles public re-exports, API evolution, deprecation, breaking changes, and error handling. Use when designing or reviewing a library API, exposing a symbol from a package __init__, or managing API versioning and deprecations.

Overview

Publisherwdm0006
Repositorypython-skills
Skill namedesigning-python-apis
Stars
111
Forks
17
Bundled files
2
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 2 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by wdm0006 on GitHub. Read the source before you install it.

Installation

Install the Designing Python Apis AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/wdm0006/python-skills/tree/main/skills/python/api-design
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wdm0006/python-skills.git /tmp/python-skills
mkdir -p .claude/skills
cp -r /tmp/python-skills/skills/python/api-design .claude/skills/designing-python-apis
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Designing Python Apis in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Designing Python Apis on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Designing Python Apis is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Python API Design

Core Principles

  1. Simplicity: Simple things simple, complex things possible
  2. Consistency: Similar operations work similarly
  3. Least Surprise: Behave as users expect
  4. Discoverability: Find via autocomplete and help

Progressive Disclosure Pattern

python
# Level 1: Simple functions
from mylib import encode, decode
result = encode(37.7749, -122.4194)

# Level 2: Configurable classes
from mylib import Encoder
encoder = Encoder(precision=15)

# Level 3: Low-level access
from mylib.internals import BitEncoder

Naming Conventions

python
# Actions: verbs
encode(), decode(), validate()

# Retrieval: get_*
get_user(), get_config()

# Boolean: is_*, has_*, can_*
is_valid(), has_permission()

# Conversion: to_*, from_*
to_dict(), from_json()

Error Handling

python
class MyLibError(Exception):
    """Base exception with helpful messages."""
    def __init__(self, message: str, *, hint: str = None):
        super().__init__(message)
        self.hint = hint

# Usage
raise ValidationError(
    f"Latitude must be -90 to 90, got {lat}",
    hint="Did you swap latitude and longitude?"
)

Fail Loud, Not Silent

The most expensive bugs are the ones where failure is indistinguishable from success. A caller who gets no error assumes everything worked. These patterns all turned a real failure into a silent wrong answer in shipped code — guard against every one.

Don't write the success sentinel on the failure path. An except block that sets the same state a successful run would makes failed jobs look complete.

python
# BAD — any failure is reported to the user as a finished result.
try:
    result = run_job()
    status = "READY"
except Exception:
    status = "READY"        # failure now looks identical to success

# GOOD — distinct terminal states; the UI/caller can react.
try:
    result = run_job()
    status = "READY"
except Exception:
    log.exception("job failed")
    status = "ERROR"

Don't swallow distinct failures into one generic message. A broad except Exception that returns "error: something went wrong" (or worse, an empty result) collapses parse errors, missing files, and bugs into the same opaque string — undebuggable and often mistaken for "no problems found." Catch the specific exceptions you can handle; let the rest propagate.

An empty/partial result is not an error signal. Returning [], an empty DataFrame, or "what I fetched before the connection dropped" looks like a valid answer. Pagination that returns partial pages on a mid-stream RequestError, then gets aggregated as if complete, produces silently wrong analytics. Either raise, or return an explicit "incomplete" marker the caller must check — never let truncation masquerade as the full set.

Meter external work where it actually happens. A quota or request budget charged once around list_all_items() undercounts whenever that helper follows pagination internally: one budget unit can hide ten HTTP requests. Spend at the lowest shared request boundary so every page, retry, and detail fetch is counted.

python
# BAD — the helper may issue an unbounded number of requests.
budget.spend()
items = client.list_all_items()

# GOOD — pagination cannot bypass the meter.
def request(method, url, *, budget, **kwargs):
    budget.spend()
    return http.request(method, url, **kwargs)

Keep the budget above the raw HTTP call if cache hits should be free, and below retry logic if every retry consumes provider quota. Test with a fake paginated transport that returns multiple pages and assert both the result values and the exact number of budget spends; a one-page fake cannot prove this contract.

A no-op on unexpected input is a silent corruption. Code that skips columns of the wrong type, ignores a key it doesn't recognize, or continues past a file it can't parse — with no error and no report — leaves the caller believing the operation applied. If you can't act on an input, say so (raise, warn, or return a per-item error list); don't quietly do nothing.

Validation errors must not leave partial mutations behind. An inplace=True API that renames caller-owned columns and only then validates another argument can raise the right exception while still corrupting the caller's next operation. Validate every parameter and precondition before the first mutation. When work cannot be validated up front, stage it on a copy and commit only after success.

python
# BAD — invalid max_fraction still changes the caller's dataframe.
def detect(data, *, max_fraction=0.1, inplace=True):
    target = data if inplace else data.copy()
    target.rename(columns={"time": "timestamp"}, inplace=True)
    if not 0 < max_fraction < 0.5:
        raise ValueError("max_fraction must be between 0 and 0.5")
    return analyze(target)

# GOOD — the error path is side-effect free.
def detect(data, *, max_fraction=0.1, inplace=True):
    if not 0 < max_fraction < 0.5:
        raise ValueError("max_fraction must be between 0 and 0.5")
    target = data if inplace else data.copy()
    target.rename(columns={"time": "timestamp"}, inplace=True)
    return analyze(target)

Pin the contract in tests: snapshot caller-owned state, trigger a late validation error with inplace=True, and assert the object is unchanged. Testing only the exception type misses the damaging half of this bug.

python
before = frame.copy(deep=True)
with pytest.raises(ValueError, match="max_fraction"):
    detect(frame, max_fraction=0.5, inplace=True)
pd.testing.assert_frame_equal(frame, before)

Filtering down to empty must never read as "all clear." When you narrow a rule set, check set, or work list and the filter yields nothing, an "evaluate all → 0 problems" path reports a perfect score while actually checking nothing. Guard the empty case explicitly:

python
selected = [r for r in rules if r.category in requested]
if not selected:                       # empty filter ≠ everything passed
    raise ValueError(f"no rules match {requested!r}")

Never fabricate a fallback that looks real. Substituting sample/random data when a fetch fails (so the UI "has something to show") presents invented numbers as genuine. Surface the failure instead; a visible error beats a plausible lie.

Don't discard the real output on a non-zero exit. A subprocess wrapper that returns f"Error: {stderr}" whenever returncode != 0 loses the answer for tools that exit non-zero by design and write results to stdout — reporting a successful run as an empty "Error: ". Inspect stdout and the actual exit semantics before deciding it failed.

Test the public import path, not only the implementation module

A package can expose two functions with the same name and only one can work:

python
# mylib/__init__.py
def initialize_parser() -> None:
    pass                         # stale placeholder

# mylib/parser.py
def initialize_parser() -> None:
    global _parser
    _parser = build_parser()     # real implementation

Internal tests that import mylib.parser.initialize_parser all pass, while the documented from mylib import initialize_parser call does nothing. This is an API break even though neither definition is individually invalid.

Re-export the canonical object instead of wrapping or copying it:

python
# mylib/__init__.py
from .parser import initialize_parser

__all__ = ["initialize_parser"]

Then test through the path users are told to import. An identity assertion is a cheap drift guard, and one behavior assertion proves the public route performs the required initialization:

python
import mylib
from mylib import parser

def test_public_initializer_is_canonical():
    assert mylib.initialize_parser is parser.initialize_parser
    mylib.initialize_parser()
    assert parser.is_initialized()

Apply the behavior check to convenience exports, compatibility adapters, console entry-point targets, and documented import snippets. Use identity only when the public name is intended to be a direct alias. Testing only the leaf module proves the implementation; it says nothing about whether the public API reaches it.

Deprecation

Deprecate gracefully: warn now, document the removal version, and remove only in a major release. The warning mechanics (including deprecating parameters, classes, and modules) and the migration-guide template are owned by the managing-python-releases skill — see ../release-management/MIGRATION.md.

Anti-Patterns

python
# Bad: Boolean trap
process(data, True, False, True)

# Good: Keyword arguments
process(data, validate=True, cache=False)

The mutable-default-argument trap (def f(x: list = [])) is covered by the improving-python-code-quality skill.

For detailed patterns, see:

Review Checklist

Naming:
- [ ] Clear, self-documenting names
- [ ] Consistent patterns throughout
- [ ] Boolean params read naturally

Parameters:
- [ ] Minimal required parameters
- [ ] Sensible defaults
- [ ] Keyword-only after positional clarity

Exports:
- [ ] Direct package exports reference the canonical implementation, not a stale stub
- [ ] Tests import through the documented public path and assert real behavior

Errors:
- [ ] Custom exceptions with context
- [ ] Helpful error messages
- [ ] Documented in docstrings
- [ ] Failures fail loud — no success sentinel on the error path
- [ ] Empty/partial results never masquerade as a complete answer
- [ ] No silent no-ops or fabricated fallback data
- [ ] Validation failures leave caller-owned inputs unchanged

Learn More

This skill is based on the Ergonomics section of the Guide to Developing High-Quality Python Libraries by Will McGinnis. See these posts for deeper coverage:

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Designing Python Apis AI skill do?

Designs intuitive Python library APIs following principles of simplicity, consistency, and discoverability. Handles public re-exports, API evolution, deprecation, breaking changes, and error handling. Use when designing or reviewing a library API, exposing a symbol from a package __init__, or managing API versioning and deprecations.

Why use Designing Python Apis on TypingMind?

Because you install it once and use it with any model. Designing Python Apis is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Designing Python Apis in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/wdm0006/python-skills/tree/main/skills/python/api-design. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Designing Python Apis?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Designing Python Apis?

As many as you like. As long as a model supports skills, you can use Designing Python Apis with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Designing Python Apis AI skill free?

Yes. It is published on GitHub by wdm0006 under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇