# openapi-schema-pydantic
[![PyPI](https://img.shields.io/pypi/v/openapi-schema-pydantic)](https://pypi.org/project/openapi-schema-pydantic/)
[![PyPI - License](https://img.shields.io/pypi/l/openapi-schema-pydantic)](https://github.com/kuimono/openapi-schema-pydantic/blob/master/LICENSE)
OpenAPI (v3) specification schema as [Pydantic](https://github.com/samuelcolvin/pydantic) classes.
The naming of the classes follows the schema in
[OpenAPI specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#schema).
## Installation
`pip install openapi-schema-pydantic`
## Try me
```python
from openapi_schema_pydantic import OpenAPI, Info, PathItem, Operation, Response
# Construct OpenAPI by pydantic objects
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:
```json
{
"openapi": "3.1.0",
"info": {
"title": "My own API",
"version": "v0.0.1"
},
"servers": [
{
"url": "/"
}
],
"paths": {
"/ping": {
"get": {
"responses": {
"200": {
"description": "pong"
}
},
"deprecated": false
}
}
}
}
```
## Take advantage of Pydantic
Pydantic is a great tool, allow you to use object / dict / mixed data for for input.
The following examples give the same OpenAPI result as above:
```python
from openapi_schema_pydantic import OpenAPI, PathItem, Response
# Construct OpenAPI from dict
open_api = OpenAPI.parse_obj({
"info": {"title": "My own API", "version": "v0.0.1"},
"paths": {
"/ping": {
"get": {"responses": {"200": {"description": "pong"}}}
}
},
})
# Construct OpenAPI with mix of dict/object
open_api = OpenAPI.parse_obj({
"info": {"title": "My own API", "version": "v0.0.1"},
"paths": {
"/ping": PathItem(
get={"responses": {"200": Response(description="pong")}}
)
},
})
```
## Use Pydantic classes as schema
- The [Schema Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#schemaObject)
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](https://pydantic-docs.helpmanual.io/usage/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
```python
from pydantic import BaseModel, Field
from openapi_schema_pydantic import OpenAPI
from openapi_schema_pydantic.util import PydanticSchema, construct_open_api_with_schema_class
def construct_base_open_api() -> OpenAPI:
return OpenAPI.parse_obj({
"info": {"title": "My own API", "version": "v0.0.1"},
"paths": {
"/ping": {
"post": {
"requestBody": {"content": {"application/json": {
"schema": PydanticSchema(schema_class=PingRequest)
}}},
"responses": {"200": {
"description": "pong",
"content": {"application/json": {
"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:
```json
{
"openapi": "3.1.0",
"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": {
"title": "PingRequest",
"required": [
"req_foo",
"req_bar"
],
"type": "object",
"properties": {
"req_foo": {
"title": "Req Foo",
"type": "string",
"description": "foo value of the request"
},
"req_bar": {
"title": "Req Bar",
"type": "string",
"description": "bar value of the request"
}
},
"description": "Ping Request"
},
"PingResponse": {
"title": "PingResponse",
"required": [
"resp_foo",
"resp_bar"
],
"type": "object",
"properties": {
"resp_foo": {
"title": "Resp Foo",
"type": "string",
"description": "foo value of the response"
},
"resp_bar": {
"title": "Resp Bar",
"type": "string",
"description": "bar value of the response"
}
},
"description": "Ping response"
}
}
}
}
```
## Notes
### Use of OpenAPI.json() / OpenAPI.dict()
When using `OpenAPI.json()` / `OpenAPI.dict()` function,
arguments `by_alias=True, exclude_none=True` has to be in place.
Otherwise the result json will not fit the OpenAPI standard.
```python
# 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.1.0 | [here](https://github.com/kuimono/openapi-schema-pydantic/blob/master/openapi_schema_pydantic/v3/v3_1_0/README.md#alias) |
| 3.0.3 | [here](https://github.com/kuimono/openapi-schema-pydantic/blob/master/openapi_schema_pydantic/v3/v3_0_3/README.md#alias) |
### Non-pydantic schema types
Some schema types are not implemented as pydantic classes.
Please refer to the following for more info:
| OpenAPI version | Non-pydantic schema type info |
| --------------- | ----------------------------- |
| 3.1.0 | [here](https://github.com/kuimono/openapi-schema-pydantic/blob/master/openapi_schema_pydantic/v3/v3_1_0/README.md#non-pydantic-schema-types) |
| 3.0.3 | [here](https://github.com/kuimono/openapi-schema-pydantic/blob/master/openapi_schema_pydantic/v3/v3_0_3/README.md#non-pydantic-schema-types) |
### Use OpenAPI 3.0.3 instead of 3.1.0
Some UI renderings (e.g. Swagger) still do not support OpenAPI 3.1.0.
It is allowed to use the old 3.0.3 version by importing from different paths:
```python
from openapi_schema_pydantic.v3.v3_0_3 import OpenAPI, ...
from openapi_schema_pydantic.v3.v3_0_3.util import PydanticSchema, construct_open_api_with_schema_class
```
## License
[MIT License](https://github.com/kuimono/openapi-schema-pydantic/blob/master/LICENSE)
Raw data
{
"_id": null,
"home_page": "https://github.com/kuimono/openapi-schema-pydantic",
"name": "openapi-schema-pydantic",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.6.1",
"maintainer_email": "",
"keywords": "",
"author": "Kuimono",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/8e/8f/9d2fd2d5a233d916c03d7463c0c0bc2a1bfffb91abee80ef2d3bd9b40cda/openapi-schema-pydantic-1.2.4.tar.gz",
"platform": null,
"description": "# openapi-schema-pydantic\n\n[![PyPI](https://img.shields.io/pypi/v/openapi-schema-pydantic)](https://pypi.org/project/openapi-schema-pydantic/)\n[![PyPI - License](https://img.shields.io/pypi/l/openapi-schema-pydantic)](https://github.com/kuimono/openapi-schema-pydantic/blob/master/LICENSE)\n\nOpenAPI (v3) specification schema as [Pydantic](https://github.com/samuelcolvin/pydantic) classes.\n\nThe naming of the classes follows the schema in \n[OpenAPI specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#schema).\n\n## Installation\n\n`pip install openapi-schema-pydantic`\n\n## Try me\n\n```python\nfrom openapi_schema_pydantic import OpenAPI, Info, PathItem, Operation, Response\n\n# Construct OpenAPI by pydantic objects\nopen_api = OpenAPI(\n info=Info(\n title=\"My own API\",\n version=\"v0.0.1\",\n ),\n paths={\n \"/ping\": PathItem(\n get=Operation(\n responses={\n \"200\": Response(\n description=\"pong\"\n )\n }\n )\n )\n },\n)\nprint(open_api.json(by_alias=True, exclude_none=True, indent=2))\n```\n\nResult:\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"My own API\",\n \"version\": \"v0.0.1\"\n },\n \"servers\": [\n {\n \"url\": \"/\"\n }\n ],\n \"paths\": {\n \"/ping\": {\n \"get\": {\n \"responses\": {\n \"200\": {\n \"description\": \"pong\"\n }\n },\n \"deprecated\": false\n }\n }\n }\n}\n```\n\n## Take advantage of Pydantic\n\nPydantic is a great tool, allow you to use object / dict / mixed data for for input.\n\nThe following examples give the same OpenAPI result as above:\n\n```python\nfrom openapi_schema_pydantic import OpenAPI, PathItem, Response\n\n# Construct OpenAPI from dict\nopen_api = OpenAPI.parse_obj({\n \"info\": {\"title\": \"My own API\", \"version\": \"v0.0.1\"},\n \"paths\": {\n \"/ping\": {\n \"get\": {\"responses\": {\"200\": {\"description\": \"pong\"}}}\n }\n },\n})\n\n# Construct OpenAPI with mix of dict/object\nopen_api = OpenAPI.parse_obj({\n \"info\": {\"title\": \"My own API\", \"version\": \"v0.0.1\"},\n \"paths\": {\n \"/ping\": PathItem(\n get={\"responses\": {\"200\": Response(description=\"pong\")}}\n )\n },\n})\n```\n\n## Use Pydantic classes as schema\n\n- The [Schema Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#schemaObject)\n in OpenAPI has definitions and tweaks in JSON Schema, which is hard to comprehend and define a good data class\n- Pydantic already has a good way to [create JSON schema](https://pydantic-docs.helpmanual.io/usage/schema/),\n let's not re-invent the wheel\n \nThe approach to deal with this:\n\n1. Use `PydanticSchema` objects to represent the `Schema` in `OpenAPI` object\n2. Invoke `construct_open_api_with_schema_class` to resolve the JSON schemas and references\n\n```python\nfrom pydantic import BaseModel, Field\n\nfrom openapi_schema_pydantic import OpenAPI\nfrom openapi_schema_pydantic.util import PydanticSchema, construct_open_api_with_schema_class\n\ndef construct_base_open_api() -> OpenAPI:\n return OpenAPI.parse_obj({\n \"info\": {\"title\": \"My own API\", \"version\": \"v0.0.1\"},\n \"paths\": {\n \"/ping\": {\n \"post\": {\n \"requestBody\": {\"content\": {\"application/json\": {\n \"schema\": PydanticSchema(schema_class=PingRequest)\n }}},\n \"responses\": {\"200\": {\n \"description\": \"pong\",\n \"content\": {\"application/json\": {\n \"schema\": PydanticSchema(schema_class=PingResponse)\n }},\n }},\n }\n }\n },\n })\n\nclass PingRequest(BaseModel):\n \"\"\"Ping Request\"\"\"\n req_foo: str = Field(description=\"foo value of the request\")\n req_bar: str = Field(description=\"bar value of the request\")\n\nclass PingResponse(BaseModel):\n \"\"\"Ping response\"\"\"\n resp_foo: str = Field(description=\"foo value of the response\")\n resp_bar: str = Field(description=\"bar value of the response\")\n\nopen_api = construct_base_open_api()\nopen_api = construct_open_api_with_schema_class(open_api)\n\n# print the result openapi.json\nprint(open_api.json(by_alias=True, exclude_none=True, indent=2))\n```\n\nResult:\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"My own API\",\n \"version\": \"v0.0.1\"\n },\n \"servers\": [\n {\n \"url\": \"/\"\n }\n ],\n \"paths\": {\n \"/ping\": {\n \"post\": {\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/PingRequest\"\n }\n }\n },\n \"required\": false\n },\n \"responses\": {\n \"200\": {\n \"description\": \"pong\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/PingResponse\"\n }\n }\n }\n }\n },\n \"deprecated\": false\n }\n }\n },\n \"components\": {\n \"schemas\": {\n \"PingRequest\": {\n \"title\": \"PingRequest\",\n \"required\": [\n \"req_foo\",\n \"req_bar\"\n ],\n \"type\": \"object\",\n \"properties\": {\n \"req_foo\": {\n \"title\": \"Req Foo\",\n \"type\": \"string\",\n \"description\": \"foo value of the request\"\n },\n \"req_bar\": {\n \"title\": \"Req Bar\",\n \"type\": \"string\",\n \"description\": \"bar value of the request\"\n }\n },\n \"description\": \"Ping Request\"\n },\n \"PingResponse\": {\n \"title\": \"PingResponse\",\n \"required\": [\n \"resp_foo\",\n \"resp_bar\"\n ],\n \"type\": \"object\",\n \"properties\": {\n \"resp_foo\": {\n \"title\": \"Resp Foo\",\n \"type\": \"string\",\n \"description\": \"foo value of the response\"\n },\n \"resp_bar\": {\n \"title\": \"Resp Bar\",\n \"type\": \"string\",\n \"description\": \"bar value of the response\"\n }\n },\n \"description\": \"Ping response\"\n }\n }\n }\n}\n```\n\n## Notes\n\n### Use of OpenAPI.json() / OpenAPI.dict()\n\nWhen using `OpenAPI.json()` / `OpenAPI.dict()` function,\narguments `by_alias=True, exclude_none=True` has to be in place.\nOtherwise the result json will not fit the OpenAPI standard.\n\n```python\n# OK\nopen_api.json(by_alias=True, exclude_none=True, indent=2)\n\n# Not good\nopen_api.json(indent=2)\n```\n\nMore info about field alias:\n\n| OpenAPI version | Field alias info |\n| --------------- | ---------------- |\n| 3.1.0 | [here](https://github.com/kuimono/openapi-schema-pydantic/blob/master/openapi_schema_pydantic/v3/v3_1_0/README.md#alias) |\n| 3.0.3 | [here](https://github.com/kuimono/openapi-schema-pydantic/blob/master/openapi_schema_pydantic/v3/v3_0_3/README.md#alias) |\n\n### Non-pydantic schema types\n\nSome schema types are not implemented as pydantic classes.\nPlease refer to the following for more info:\n\n| OpenAPI version | Non-pydantic schema type info |\n| --------------- | ----------------------------- |\n| 3.1.0 | [here](https://github.com/kuimono/openapi-schema-pydantic/blob/master/openapi_schema_pydantic/v3/v3_1_0/README.md#non-pydantic-schema-types) |\n| 3.0.3 | [here](https://github.com/kuimono/openapi-schema-pydantic/blob/master/openapi_schema_pydantic/v3/v3_0_3/README.md#non-pydantic-schema-types) |\n\n### Use OpenAPI 3.0.3 instead of 3.1.0\n\nSome UI renderings (e.g. Swagger) still do not support OpenAPI 3.1.0.\nIt is allowed to use the old 3.0.3 version by importing from different paths:\n\n```python\nfrom openapi_schema_pydantic.v3.v3_0_3 import OpenAPI, ...\nfrom openapi_schema_pydantic.v3.v3_0_3.util import PydanticSchema, construct_open_api_with_schema_class\n```\n\n## License\n\n[MIT License](https://github.com/kuimono/openapi-schema-pydantic/blob/master/LICENSE)\n",
"bugtrack_url": null,
"license": "",
"summary": "OpenAPI (v3) specification schema as pydantic class",
"version": "1.2.4",
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "a8e722abb5a10733bf8142984201aedf27d4a58f5810ebdfe9679f9876c7bf4d",
"md5": "c054fc4b2a6430fd4a468c52660222f9",
"sha256": "a932ecc5dcbb308950282088956e94dea069c9823c84e507d64f6b622222098c"
},
"downloads": -1,
"filename": "openapi_schema_pydantic-1.2.4-py3-none-any.whl",
"has_sig": false,
"md5_digest": "c054fc4b2a6430fd4a468c52660222f9",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.6.1",
"size": 90015,
"upload_time": "2022-06-29T12:46:33",
"upload_time_iso_8601": "2022-06-29T12:46:33.826728Z",
"url": "https://files.pythonhosted.org/packages/a8/e7/22abb5a10733bf8142984201aedf27d4a58f5810ebdfe9679f9876c7bf4d/openapi_schema_pydantic-1.2.4-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "8e8f9d2fd2d5a233d916c03d7463c0c0bc2a1bfffb91abee80ef2d3bd9b40cda",
"md5": "4e23392aa8851d6a3eb0f80adb8d648b",
"sha256": "3e22cf58b74a69f752cc7e5f1537f6e44164282db2700cbbcd3bb99ddd065196"
},
"downloads": -1,
"filename": "openapi-schema-pydantic-1.2.4.tar.gz",
"has_sig": false,
"md5_digest": "4e23392aa8851d6a3eb0f80adb8d648b",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.6.1",
"size": 54054,
"upload_time": "2022-06-29T12:46:35",
"upload_time_iso_8601": "2022-06-29T12:46:35.831876Z",
"url": "https://files.pythonhosted.org/packages/8e/8f/9d2fd2d5a233d916c03d7463c0c0bc2a1bfffb91abee80ef2d3bd9b40cda/openapi-schema-pydantic-1.2.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2022-06-29 12:46:35",
"github": true,
"gitlab": false,
"bitbucket": false,
"github_user": "kuimono",
"github_project": "openapi-schema-pydantic",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [],
"lcname": "openapi-schema-pydantic"
}