mike-oakley / openapi-pydantic

Pydantic OpenAPI schema implementation
Other
48 stars 7 forks source link

[Question] Getting example to work #19

Closed chriskelly closed 1 year ago

chriskelly commented 1 year ago

I'm new to using custom json schemas (and to YAML in general). I'm trying to use your library (v0.3.1) with Pydantic v2 to provide useful descriptions for my user's yaml files. When I try your example, VSCode recognizes the schema, but nothing else seems to happen. There's no description on hover, no auto-completion suggestions, and no problems are raised if the wrong type is used. Am I making the wrong assumptions about the behavior that's supposed to happen or is there something wrong in my setup?

temporary.py schema creation module:

from pydantic import BaseModel, Field

from openapi_pydantic import OpenAPI
from openapi_pydantic.util import PydanticSchema, construct_open_api_with_schema_class

def construct_base_open_api() -> OpenAPI:
    # Note: for Pydantic 1.x, replace `model_validate` with `parse_obj`
    return OpenAPI.model_validate({
        "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
# Note: for Pydantic 1.x, replace `model_dump_json` with `json`
print(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2))

with open('temporary.json', 'w') as file:
    file.write(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2))

temporary.json output of temporary.py:

{
  "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": {
        "properties": {
          "req_foo": {
            "type": "string",
            "title": "Req Foo",
            "description": "foo value of the request"
          },
          "req_bar": {
            "type": "string",
            "title": "Req Bar",
            "description": "bar value of the request"
          }
        },
        "type": "object",
        "required": [
          "req_foo",
          "req_bar"
        ],
        "title": "PingRequest",
        "description": "Ping Request"
      },
      "PingResponse": {
        "properties": {
          "resp_foo": {
            "type": "string",
            "title": "Resp Foo",
            "description": "foo value of the response"
          },
          "resp_bar": {
            "type": "string",
            "title": "Resp Bar",
            "description": "bar value of the response"
          }
        },
        "type": "object",
        "required": [
          "resp_foo",
          "resp_bar"
        ],
        "title": "PingResponse",
        "description": "Ping response"
      }
    }
  }
}

temporary.yml file for testing with defined and undefined parameters:

# yaml-language-server: $schema=temporary.json

resp_foo: 24
PingRequest: 
  req_foo: 343

social_security_pension:
  trust_factor: 0.8
  pension_eligible: false
  strategy:
    early:
      enabled: true
    mid:
      enabled: true
      chosen: true
    late:
      enabled: false
    net_worth:
      enabled: true
      equity_target: 2800

screenshot showing temporary.json schema selected at bottom: image

Redhat YAML extension settings: image image image image

mike-oakley commented 1 year ago

Hi @chriskelly - not sure what the ask is here? Are you expecting VSCode to lint your YAML? You are generating an OpenAPI spec so not sure what you're expecting VSCode to do with that?

mike-oakley commented 1 year ago

OpenAPI is a spec for defining APIs, its not designed for general purpose YAML linting/validation - for that you just want to define a JSONSchema for your file

hathawsh commented 1 year ago

@chriskelly, try loading the generated spec into https://editor-next.swagger.io/ . You'll get good feedback there.

chriskelly commented 1 year ago

Gotcha, think that was a misunderstanding on my part. I am looking for a linting tool and thought I'd need OpenAPI for that. Didn't realize that Pydantic has their own schema generator, so I'll stick with that. Thanks!