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)

More info about field alias:

OpenAPI version Field alias info
3.0.3 here

License

MIT License

Metadata

Release files for openapi-schema-pydantic 0.1.2

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.2
File Size Uploaded
openapi-schema-pydantic-0.1.2.tar.gz 23.3 kB Details

Built distribution (wheel)

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

Total release size: 60.0 kB

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

Download URL openapi-schema-pydantic-0.1.2.tar.gz
Size 23.3 kB
Tags Source
SHA-256 checksum
How to use checksums
f658b6294e2fc86dc5031a6b3b9ec356004c200991a17a345c58e17956a0b954
BLAKE2b-256 checksum
How to use checksums
6671745fead81ecd326e45e0b219a9b9d5c448bb0a83fe38498af7e621e2b77f
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.2-py3-none-any.whl

Download URL openapi_schema_pydantic-0.1.2-py3-none-any.whl
Size 36.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
aacc4458e33bf88469a2c2541565a508ee152a945d8b41396314bf01c1e05a7b
BLAKE2b-256 checksum
How to use checksums
33d58eb038583b9d3ed3a65b6b6ad2b7ba30f49ff44e7dd273992ac599222e3a
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

This release

0.1.2 This release

2 release files

0.1.1

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