0b01001001 / spectree

API spec validator and OpenAPI document generator for Python web frameworks.
https://0b01001001.github.io/spectree/
Apache License 2.0
324 stars 75 forks source link

AssertionError: invalid pydantic.BaseModel when using pydantic.BaseModel subclass in spectree.Response #382

Closed kenichi-cg closed 1 day ago

kenichi-cg commented 1 week ago

Describe the bug

When specifying a subclass of pydantic.BaseModel in spectree.Response, an AssertionError: invalid pydantic.BaseModel is raised. This issue seems to be caused by the assertion at line 87 in spectree/response.py, which checks the model using issubclass(model, BaseModel). Despite importing BaseModel from spectree._pydantic, the assertion does not use the is_base_model() function from spectree._pydantic, which would correctly identify pydantic.BaseModel subclasses.

To Reproduce

  1. Create a Flask application with pydantic and spectree.
  2. Define a response model using pydantic.BaseModel.
  3. Use the response model in spectree.Response.
  4. Run the Flask application and make a request to the endpoint.

Example code:

from flask import Flask, jsonify
from pydantic import BaseModel, Field
from spectree import Response, SpecTree

class MyResponse(BaseModel):
    message: str = Field(..., description="response message")

app = Flask(__name__)
spec = SpecTree('flask')

@app.route('/hello', methods=['GET'])
@spec.validate(resp=Response(HTTP_200=MyResponse))
def hello():
    return jsonify(message='hello world')

if __name__ == '__main__':
    spec.register(app)
    app.run(debug=True)

Expected behavior

The response model should be validated correctly without raising an AssertionError.

The spectree version

Additional context

The issue seems to be caused by the assertion at line 87 in spectree/response.py, which checks the model using issubclass(model, BaseModel). A potential fix could be to adjust the assertion to use the is_base_model() function from spectree._pydantic to correctly identify pydantic.BaseModel subclasses.

kemingy commented 1 week ago

Related to #329

So far, it only support v1, let me check if we can support both.

kemingy commented 1 day ago

Hi @kenichi-cg you can try it with v1.4.1. It should work now.