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 spec2sdk.parsers.entities import DataType, StringDataType
from spec2sdk.generators.converters import converters
from spec2sdk.generators.entities import PythonType
from spec2sdk.generators.predicates import is_instance
from spec2sdk.generators.imports import Import
from spec2sdk.generators.models.entities import TypeRenderer
from spec2sdk.generators.models.renderers import render_root_model, renderers
from spec2sdk.main import generate


class EmailPythonType(PythonType):
    pass


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) -> EmailPythonType:
    return EmailPythonType(
        name=None,
        type_hint="EmailStr",
        description=data_type.description,
        default_value=data_type.default_value,
    )


@renderers.register(predicate=is_instance(EmailPythonType))
def render_email_field(py_type: EmailPythonType) -> TypeRenderer:
    return render_root_model(
        py_type,
        extra_imports=(Import(name="EmailStr", package="pydantic"),),
        content="EmailStr",
    )


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


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.202411031804.tar.gz (16.0 kB view details)

Uploaded Source

Built Distribution

spec2sdk-1.0.202411031804-py3-none-any.whl (23.0 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for spec2sdk-1.0.202411031804.tar.gz
Algorithm Hash digest
SHA256 42a0753086ddaa4c527061147511a34752e5da7b75ecd82de229a4a11ce22733
MD5 2f5f1a71685464b3ecfc42c2d82c9e0a
BLAKE2b-256 dc35dac5d9c8e55c481c1587f3108d02d802367f762ee33e8be5ec245e677c59

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for spec2sdk-1.0.202411031804-py3-none-any.whl
Algorithm Hash digest
SHA256 6a17946d8d569b3546e36ef97b0417d0f615c1c75c44e6cd7546fa6ae836a429
MD5 5ae10817d8002f573c1c67b68fcfcf1b
BLAKE2b-256 f4ce515c92910d0daa437c19b5d184a688f0b624895cb24253e37d0241c738c5

See more details on using hashes here.

Supported by

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