Skip to main content

Generate Pydantic models and API client code from OpenAPI 3.x specifications

Project description

Usage

From command line

spec2sdk --input path/to/api.yml --output-dir path/to/output-dir/

From the code

from pathlib import Path
from spec2sdk.main import generate

generate(url=Path("path/to/api.yml").absolute().as_uri(), output_dir=Path("path/to/output-dir/"))

Open API specification requirements

Operation ID

operationId must be specified for each endpoint to generate meaningful method names. It must be unique among all operations described in the API.

Input

paths:
  /health:
    get:
      operationId: healthCheck
      responses:
        '200':
          description: Successful response

Output

class APIClient:
    def health_check(self) -> None:
        ...

Inline schemas

Inline schemas should be annotated with the schema name in the x-schema-name field that doesn't overlap with the existing schema names in the specification.

Input

paths:
  /me:
    get:
      operationId: getMe
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                x-schema-name: User
                type: object
                properties:
                  name:
                    type: string
                  email:
                    type: string

Output

class User(Model):
    name: str | None = Field(default=None)
    email: str | None = Field(default=None)

Enum variable names

Variable names for enums can be specified by the x-enum-varnames field.

Input

components: 
  schemas:
    Direction:
      x-enum-varnames: [ NORTH, SOUTH, WEST, EAST ]
      type: string
      enum: [ N, S, W, E ]

Output

from enum import StrEnum

class Direction(StrEnum):
    NORTH = "N"
    SOUTH = "S"
    WEST = "W"
    EAST = "E"

Custom types

Register Python converters and renderers to implement custom types.

Input

components: 
  schemas: 
    User:
      type: object
      properties:
        name:
          type: string
        email:
          type: string
          format: email
from pathlib import Path
from typing import Sequence

from spec2sdk.openapi.entities import DataType, StringDataType
from spec2sdk.models.converters import converters, get_common_fields
from spec2sdk.models.entities import PythonType
from spec2sdk.models.imports import Import
from spec2sdk.main import generate


class EmailType(PythonType):
    @property
    def type_hint(self) -> str:
        return self.name or "EmailStr"

    @property
    def imports(self) -> Sequence[Import]:
        return (
            Import(name="EmailStr", package="pydantic"),
            *((Import(name="RootModel", package="pydantic"),) if self.name else ()),
        )

    def render(self) -> str:
        return f"{self.name} = RootModel[EmailStr]" if self.name else ""


def is_email_format(data_type: DataType) -> bool:
    return isinstance(data_type, StringDataType) and data_type.format == "email"


@converters.register(predicate=is_email_format)
def convert_email_field(data_type: StringDataType) -> EmailType:
    return EmailType(**get_common_fields(data_type))


if __name__ == "__main__":
    generate(url=Path("api.yml").absolute().as_uri(), output_dir=Path("output"))

Output

from pydantic import EmailStr, Field

class User(Model):
    name: str | None = Field(default=None)
    email: EmailStr | None = Field(default=None)

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spec2sdk-1.0.202501311119.tar.gz (15.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spec2sdk-1.0.202501311119-py3-none-any.whl (21.7 kB view details)

Uploaded Python 3

File details

Details for the file spec2sdk-1.0.202501311119.tar.gz.

File metadata

  • Download URL: spec2sdk-1.0.202501311119.tar.gz
  • Upload date:
  • Size: 15.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.3 Linux/6.8.0-1020-azure

File hashes

Hashes for spec2sdk-1.0.202501311119.tar.gz
Algorithm Hash digest
SHA256 840856959f5a3f14f70209f27113bf0181180671257ce07199440de86939c9f9
MD5 cf0b5073ec8024897329e2751bf1b516
BLAKE2b-256 04206b83d0a4ac8552c7df400aa9256e60c50517d301eeab6676d8e402eb8d36

See more details on using hashes here.

File details

Details for the file spec2sdk-1.0.202501311119-py3-none-any.whl.

File metadata

  • Download URL: spec2sdk-1.0.202501311119-py3-none-any.whl
  • Upload date:
  • Size: 21.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.3 Linux/6.8.0-1020-azure

File hashes

Hashes for spec2sdk-1.0.202501311119-py3-none-any.whl
Algorithm Hash digest
SHA256 a99341a5a60b1e5e75ec64b4c01426e638536f74fab54af98b06d839f3305878
MD5 5bbbe53c1cff71a1048c42d745f589af
BLAKE2b-256 67f5880767bd61b352edb0fde5a44f6292dab8a6c84f3b04f73396b85bad6dac

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page