Skip to main content

openapi-schema-pydantic

OpenAPI (v3) specification schema as Pydantic classes

Try me

from openapi_schema_pydantic import Info, OpenAPI, Operation, PathItem, Response

open_api = OpenAPI(
    info=Info(
        title="My own API",
        version="v0.0.1",
    ),
    paths={
        "/ping": PathItem(
            get=Operation(
                responses={
                    "200": Response(
                        description="pong"
                    )
                }
            )
        )
    }
)
print(open_api.json(by_alias=True, exclude_none=True, indent=2))

Result:

{
  "openapi": "3.0.3",
  "info": {
    "title": "My own API",
    "version": "v0.0.1"
  },
  "servers": [
    {
      "url": "/"
    }
  ],
  "paths": {
    "/ping": {
      "get": {
        "responses": {
          "200": {
            "description": "pong"
          }
        },
        "deprecated": false
      }
    }
  }
}

Use Pydantic classes as schema

  • The Schema Object in OpenAPI has definitions and tweaks in JSON Schema, which is hard to comprehend and define a good data class
  • Pydantic already has a good way to create JSON schema, let's not re-invent the wheel

The approach to deal with this:

  1. Use PydanticSchema objects to represent the Schema in OpenAPI object
  2. Invoke construct_open_api_with_schema_class to resolve the JSON schemas and references
from pydantic import BaseModel, Field

from openapi_schema_pydantic import Info, MediaType, OpenAPI, Operation, PathItem, RequestBody, Response
from openapi_schema_pydantic.util import PydanticSchema, construct_open_api_with_schema_class

def construct_base_open_api() -> OpenAPI:
    """Construct OpenAPI using data class"""
    return OpenAPI(
        info=Info(
            title="My own API",
            version="v0.0.1",
        ),
        paths={
            "/ping": PathItem(
                post=Operation(
                    requestBody=RequestBody(
                        content={
                            "application/json": MediaType(
                                schema=PydanticSchema(
                                    schema_class=PingRequest
                                )
                            )
                        }
                    ),
                    responses={
                        "200": Response(
                            description="pong",
                            content={
                                "application/json": MediaType(
                                    schema=PydanticSchema(
                                        schema_class=PingResponse
                                    )
                                )
                            }
                        )
                    }
                )
            )
        }
    )

class PingRequest(BaseModel):
    """Ping Request"""
    req_foo: str = Field(description="foo value of the request")
    req_bar: str = Field(description="bar value of the request")

class PingResponse(BaseModel):
    """Ping response"""
    resp_foo: str = Field(description="foo value of the response")
    resp_bar: str = Field(description="bar value of the response")

open_api = construct_base_open_api()
open_api = construct_open_api_with_schema_class(open_api)

# print the result openapi.json
print(open_api.json(by_alias=True, exclude_none=True, indent=2))

Result:

{
  "openapi": "3.0.3",
  "info": {
    "title": "My own API",
    "version": "v0.0.1"
  },
  "servers": [
    {
      "url": "/"
    }
  ],
  "paths": {
    "/ping": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PingRequest"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "description": "pong",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PingResponse"
                }
              }
            }
          }
        },
        "deprecated": false
      }
    }
  },
  "components": {
    "schemas": {
      "PingRequest": {
        "properties": {
          "req_foo": {
            "title": "Req Foo",
            "description": "foo value of the request",
            "type": "string"
          },
          "req_bar": {
            "title": "Req Bar",
            "description": "bar value of the request",
            "type": "string"
          }
        },
        "description": "Ping Request",
        "required": [
          "req_foo",
          "req_bar"
        ],
        "type": "object",
        "title": "PingRequest"
      },
      "PingResponse": {
        "properties": {
          "resp_foo": {
            "title": "Resp Foo",
            "description": "foo value of the response",
            "type": "string"
          },
          "resp_bar": {
            "title": "Resp Bar",
            "description": "bar value of the response",
            "type": "string"
          }
        },
        "description": "Ping response",
        "required": [
          "resp_foo",
          "resp_bar"
        ],
        "type": "object",
        "title": "PingResponse"
      }
    }
  }
}

Note

When using OpenAPI.json() function, arguments by_alias=True, exclude_none=True has to be in place. Otherwise the result json will not fit the OpenAPI standard.

# OK
open_api.json(by_alias=True, exclude_none=True, indent=2)

# Not good
open_api.json(indent=2)

License

MIT License

Metadata

Release files for openapi-schema-pydantic 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for openapi-schema-pydantic 0.1.1
File Size Uploaded
openapi-schema-pydantic-0.1.1.tar.gz 23.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for openapi-schema-pydantic 0.1.1
File Interpreter ABI Platform
openapi_schema_pydantic-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 59.6 kB

Release files / openapi-schema-pydantic-0.1.1.tar.gz

Download URL openapi-schema-pydantic-0.1.1.tar.gz
Size 23.1 kB
Tags Source
SHA-256 checksum
How to use checksums
94f56faec9c88d57b16b1849665e4edb8eea12c98319798921bf33cf21f92d6b
BLAKE2b-256 checksum
How to use checksums
a316f711f59a580fc3a72d97c3748ee3bbc7e81bb086770bdaddec3209fea258
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.3.0 requests-toolbelt/0.9.1 tqdm/4.46.0 CPython/3.8.1

Release files / openapi_schema_pydantic-0.1.1-py3-none-any.whl

Download URL openapi_schema_pydantic-0.1.1-py3-none-any.whl
Size 36.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8c576fe01d81557664d6e79592f31cbd72c6926b4a9ac16aca12037048e80e48
BLAKE2b-256 checksum
How to use checksums
1fb76bfa584ce5c80f316f3f40a5f63d189753d4fc198060291cc88a7b0835a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.3.0 requests-toolbelt/0.9.1 tqdm/4.46.0 CPython/3.8.1

Release history Release notifications | RSS feed

1.2.4

2 release files

1.2.3

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.0

2 release files

1.0.0

2 release files

0.3.0

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.2

2 release files

This release

0.1.1 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page