Metadata-Version: 2.4
Name: okapipy
Version: 0.2.0
Summary: Python OpenAPI Client Generator made OK
Project-URL: Homepage, https://github.com/ffaraone/okapipy
Project-URL: Repository, https://github.com/ffaraone/okapipy
Project-URL: Issues, https://github.com/ffaraone/okapipy/issues
Project-URL: Changelog, https://github.com/ffaraone/okapipy/releases
Author: Francesco Faraone
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Francesco Faraone
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: api,client,code-generation,generator,httpx,openapi,openapi3,pydantic,rest,swagger
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Code Generators
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: <4,>=3.12
Requires-Dist: datamodel-code-generator<1,>=0.26
Requires-Dist: devtools<0.13.0,>=0.12.2
Requires-Dist: jinja2<4,>=3
Requires-Dist: openapi-spec-validator<1,>=0.7
Requires-Dist: prance<26,>=23.6
Requires-Dist: pydantic<3.0.0,>=2.13.3
Requires-Dist: pyyaml<7,>=6.0
Requires-Dist: rich<15,>=13
Requires-Dist: spacy<4,>=3.7
Requires-Dist: typer<1,>=0.12
Description-Content-Type: text/markdown

<p align="center">
  <img src="https://raw.githubusercontent.com/ffaraone/okapipy/main/assets/logo.png" alt="okapipy" width="220" />
</p>

<h1 align="center">okapipy</h1>

[![CI](https://github.com/ffaraone/okapipy/actions/workflows/ci.yml/badge.svg)](https://github.com/ffaraone/okapipy/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/okapipy.svg)](https://pypi.org/project/okapipy/)
[![Python versions](https://img.shields.io/pypi/pyversions/okapipy)](https://pypi.org/project/okapipy/)
[![License](https://img.shields.io/pypi/l/okapipy)](https://github.com/ffaraone/okapipy/blob/main/LICENSE)
[![Docs](https://img.shields.io/badge/docs-ffaraone.github.io%2Fokapipy-5b3621?labelColor=2c1a10)](https://ffaraone.github.io/okapipy/)

[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=ffaraone_okapipy&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=ffaraone_okapipy)
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=ffaraone_okapipy&metric=coverage)](https://sonarcloud.io/component_measures?id=ffaraone_okapipy&metric=coverage)
[![Maintainability](https://sonarcloud.io/api/project_badges/measure?project=ffaraone_okapipy&metric=sqale_rating)](https://sonarcloud.io/component_measures?id=ffaraone_okapipy&metric=sqale_rating)
[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/pre-commit/pre-commit)
[![Checked with mypy](https://img.shields.io/badge/mypy-checked-blue.svg)](http://mypy-lang.org/)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)

A Python OpenAPI client generator that lifts the flat list of paths in an
OpenAPI 3.x document into a hierarchical tree of **Namespaces**, **Collections**,
**Resources**, **Singletons**, and **Actions**, and emits a strongly-typed,
async/sync Pydantic v2 client from it.

📚 **Full documentation:** <https://ffaraone.github.io/okapipy/> — installation,
quick start, client usage, rules and extensions, strategies, code customization,
template overrides, and a full API reference.

## Installation

okapipy requires Python 3.12+ and uses [uv](https://docs.astral.sh/uv/) for
dependency management.

```bash
uv add okapipy            # add to an existing project
# or, for one-off use:
uvx okapipy --help
```

The first NLP-dependent run downloads the spaCy `en_core_web_sm` model
(~12 MB) into `./.spacy/`. To pre-warm it:

```bash
uv run okapipy nlp fetch en
```

## Usage

Parse a spec into its structural tree (path or http(s) URL accepted):

```bash
uv run okapipy spec parse openapi.yaml --output tree.yaml
```

Generate a full client project:

```bash
uv run okapipy spec generate openapi.yaml \
    --output ./my-client \
    --package acme.commerce \
    --client-class CommerceClient
```

This writes a complete Python project under `./my-client` with a
regeneratable base layer (`src/acme/commerce/base/...`) and a one-shot user
layer of subclass stubs you can safely customize. Re-running the command
refreshes the base layer while preserving your edits in the user layer.

Useful flags:

- `--rules path/to/rules.yaml` — project-local overrides for namespace
  assignment, segment kind, and operation exclusion (mirrors the
  `x-okapipy-*` extensions; rules-file values win on conflict).
- `--strip-prefix /api/v1` — drop a base prefix from every path before
  classification.
- `--no-models` (alias `--without-models`) — skip emitting `base/models.py`
  and drop every model import from the generated client. Operations end up
  untyped (raw dicts in / out). Useful when `datamodel-code-generator`
  can't process the spec's schemas, or when the consumer prefers to bring
  their own types.
- `--check` — CI dry-run: report drift and stale files, exit non-zero on
  any change.

## How paths become a tree

okapipy walks each OpenAPI path one segment at a time and assigns each segment
one of five kinds:

| Kind          | What it represents                                  | Example path                          |
| ------------- | --------------------------------------------------- | ------------------------------------- |
| **Namespace** | A folder-style grouping (no operations of its own)  | `/commerce/...`, `/auth/...`          |
| **Collection**| A plural endpoint that lists/creates                | `/orders`, `/users`                   |
| **Resource**  | A single item within a collection (after `{id}`)    | `/orders/{id}`                        |
| **Singleton** | A resource with no enclosing collection             | `/me`, `/health`, `/users/{id}/avatar`|
| **Action**    | A non-CRUD verb endpoint                            | `/login`, `/orders/{id}/submit`       |

Classification runs in this order: `{id}`-shaped segments are resources,
explicit `x-okapipy-kind` hints win next, then the namespace registry, then
spaCy POS/morphology. When everything else is silent the segment defaults to
a collection.

HTTP methods are routed to fixed slots:

| Terminal kind | GET        | POST     | PUT      | PATCH            | DELETE   |
| ------------- | ---------- | -------- | -------- | ---------------- | -------- |
| Collection    | `fetch`    | `create` | dropped  | dropped          | dropped  |
| Resource      | `retrieve` | dropped  | `update` | `partial_update` | `delete` |
| Singleton     | `retrieve` | dropped  | `update` | `partial_update` | `delete` |
| Action        | appended to `Action.operations` (one Action holds every method on its path) |

Operations that don't fit (e.g. `POST /orders/{id}` without an action hint)
are dropped with a warning rather than coerced into something synthetic — opt
them in with `x-okapipy-kind: action` if you want them.

## OpenAPI extensions

You decorate the spec with `x-okapipy-*` keys to override the heuristics. All
extensions are optional; small/well-named specs often need none.

### `x-okapipy-ns` (root level)

Declares which top-level path segments are folders. Without this, a singular
noun like `commerce` or `auth` would be classified as a namespace only when
the heuristic guesses correctly — the registry makes it deterministic.

```yaml
openapi: 3.0.0
info:
  title: Commerce API
  version: 1.0.0
x-okapipy-ns:
  - commerce
  - commerce/internal
  - settings
paths:
  /commerce/orders:           # → Namespace(commerce) → Collection(Orders)
    get: ...
  /commerce/internal/audit:   # nested namespaces are fine
    get: ...
```

Leading slashes are tolerated (`/commerce` and `commerce` are equivalent).

### `x-okapipy-kind` (path-item or operation level)

Forces a segment's classification when NLP can't disambiguate. Allowed values:
`namespace`, `collection`, `singleton`, `action`.

```yaml
paths:
  /me:
    x-okapipy-kind: singleton  # /me is a Singleton, not a Namespace
    get:
      summary: Return the current user
    patch:
      summary: Update the current user

  /orders/{id}/submit:
    post:
      x-okapipy-kind: action   # operation-level: route this POST to a synthetic Action

  /staff:                      # spaCy treats "staff" as singular → namespace by default
    x-okapipy-kind: collection
    get: ...
```

Path-item-level hints classify the *segment* (and propagate to other paths
that walk through the same prefix — declaring `/me` as a singleton once is
enough for `/me/notifications`, `/me/refresh`, etc., to see it). Operation-level
`x-okapipy-kind: action` is narrower: it routes a single method to a
synthetic Action without changing the segment's classification.

### `x-okapipy-exclude` (path-item level)

Skips operations during parsing — useful for endpoints you don't want in the
generated client (admin-only, deprecated migration endpoints, internal
debugging routes).

```yaml
paths:
  /internal/debug:
    x-okapipy-exclude: "*"           # drop every method on this path

  /orders/{id}:
    x-okapipy-exclude: [DELETE]      # drop just DELETE; keep GET / PUT / PATCH
    get: ...
    delete: ...
```

Method names are case-insensitive.

### `x-okapipy-paginated` (path-item or operation level)

Overrides whether a list-shaped operation is treated as paginated by the
generator. Defaults to `true`. Set it to `false` for endpoints that return a
bounded list (e.g. enum-like reference data).

```yaml
paths:
  /currencies:
    x-okapipy-paginated: false       # the full list is short and fixed
    get:
      responses:
        '200':
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Currency'
```

## Singletons

A **Singleton** is a resourceful endpoint with no enclosing collection: there
is exactly one of it, and CRUD verbs apply directly to it. Common cases:

- `/me`, `/self` — the authenticated user
- `/health`, `/status`, `/version` — service introspection
- `/users/{id}/avatar` — a sub-singleton owned by a parent resource

Singletons must opt in with `x-okapipy-kind: singleton`. Without the hint, a
single-noun segment like `me` would be classified as a Namespace because
spaCy can't tell the two apart from the segment alone. Once declared, the
Singleton accepts the same CRUD verbs as a Resource (`GET → retrieve`,
`PUT → update`, `PATCH → partial_update`, `DELETE → delete`) and may host
nested collections, sub-singletons, or actions.

```yaml
paths:
  /me:
    x-okapipy-kind: singleton
    get: { summary: Return the current user, responses: { '200': ... } }
    patch: { summary: Update the current user, responses: { '200': ... } }

  /users/{id}/avatar:
    x-okapipy-kind: singleton    # sub-singleton under the User resource
    parameters: [{ name: id, in: path, required: true, schema: { type: string } }]
    get: ...
    put: ...
    delete: ...
```

The generated client surfaces these as direct attributes — `client.me.retrieve()`,
`client.users(id).avatar.update(...)` — rather than going through a
collection.

## Root and namespace-level actions

Verb endpoints can attach at the root of the API or directly under a
namespace. Plenty of real-world specs do this (`/login`, `/logout`,
`/password-reset`, `/auth/refresh`), and okapipy does not require a wrapper
collection for them.

```yaml
paths:
  /login:
    post: ...                         # → APIModel.actions[Login]
  /password-reset:
    post: ...                         # multi-token verb-phrase → Action
  /auth/refresh:
    post: ...                         # → Namespace(auth).actions[Refresh]
```

Detection notes:

- **Multi-token kebab segments** with a non-plural head (e.g. `password-reset`,
  `force-reimport`) are detected as verb-phrases by spaCy directly.
- **Single-token API verbs** that small spaCy models mistag as nouns (`login`,
  `logout`, `refresh`, `revoke`, `verify`, `subscribe`, `unsubscribe`,
  `activate`, `deactivate`, `enable`, `disable`, `archive`, `publish`, `ping`,
  …) are caught by an English-language registry.
- Anything outside that set should use `x-okapipy-kind: action` to be safe.

Naming follows the breadcrumb of singular collection names — namespaces don't
contribute. So `/login` becomes `Login`, `/auth/refresh` becomes `Refresh`,
and `/users/{id}/avatar` becomes `UserAvatar`. Cross-namespace name
collisions (e.g. `/web/login` and `/admin/login` would both be `Login`) are
left to the generator to disambiguate.

## Rules file

The rules file is a **project-local override layer**. Use it when you don't
own the OpenAPI document but still need to fix classifications, exclude
endpoints, or declare namespaces. It mirrors the spec extensions; rules-file
values win on every conflict.

Pass it via `--rules`:

```bash
uv run okapipy spec parse openapi.yaml --rules okapipy.rules.yaml
```

The file is local-only (no URLs) and accepts JSON or YAML:

```yaml
# Same shape as x-okapipy-ns at the root of the spec.
x-okapipy-ns:
  - commerce
  - commerce/internal
  - settings

paths:
  # Path-item-level kind override (mirrors x-okapipy-kind on a path).
  /staff:
    x-okapipy-kind: collection

  # Force /me to be a singleton even though the upstream spec is silent.
  /me:
    x-okapipy-kind: singleton

  # Per-method override (mirrors x-okapipy-kind on an operation).
  /orders/{id}/submit:
    post:
      x-okapipy-kind: action

  # Per-method pagination override.
  /currencies:
    x-okapipy-paginated: false

  # Drop every method on a path…
  /internal/debug:
    x-okapipy-exclude: "*"

  # …or just selected methods.
  /orders/{id}:
    x-okapipy-exclude: [DELETE]
```

Allowed `x-okapipy-kind` values: `namespace`, `collection`, `action`,
`singleton`. Unknown values are rejected at load time with the path that
contains them.
