Registry / web-framework / spectree

spectree

JSON →
library2.0.1pypypi✓ verified 85d ago

Spectree is a Python library that helps generate OpenAPI documents and validate requests and responses using Python type annotations. It leverages Pydantic for data model definitions and supports various web frameworks like Flask, Quart, Falcon, and Starlette. The library is actively maintained, with the current version being 2.0.1, and typically releases minor fixes after major version updates.

pip install spectree
INSTALL
IMPORT
SIG · SPECTREE
S
spectree
web-frameworkpythonv2.0.1
Install
3.3s avg
Import
553ms
Disk
26MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.0.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.940 runs
installs and imports cleanly · install 0.0s · import 0.570s · 28.1MB
glibc
py 3.103.940 runs
installs and imports cleanly · install 3.3s · import 0.537s · 28MB
26MB installed
● package 26MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SpecTree
from spectree import SpecTree
from spectree.spec import SpecTree
While `SpecTree` is defined in `spectree.spec`, the public API exports it directly from `spectree`.
Response
from spectree import Response
from flask import Response
`spectree.Response` is for OpenAPI schema declaration, not the web framework's HTTP response object.
BaseModel
from pydantic import BaseModel
from pydantic.v1 import BaseModel
Spectree v2.0.0+ is incompatible with Pydantic v1. Ensure you import from `pydantic` (Pydantic v2) directly.

This quickstart demonstrates how to integrate `spectree` with Flask to validate incoming query parameters and define the response schema using Pydantic models. It sets up an API endpoint that creates a user and automatically generates OpenAPI documentation.

from flask import Flask, request from pydantic import BaseModel, Field from spectree import SpecTree, Response app = Flask(__name__) api = SpecTree('flask', app=app, title='User API', version='1.0.0') class UserQuery(BaseModel): name: str = Field(..., description='User name') age: int = Field(..., gt=0, lt=150, description='User age') class UserResponse(BaseModel): message: str user_id: int @app.route('/user', methods=['POST']) @api.validate(query=UserQuery, resp=Response(HTTP_200=UserResponse), tags=['User']) def create_user(): # The validated 'query' data is available in request.context.query user_data = request.context.query user_id = 123 # Simulate user creation return {'message': f'User {user_data.name} created', 'user_id': user_id} # Access OpenAPI docs at /apidoc/redoc, /apidoc/swagger, or /apidoc/scalar # To run: FLASK_APP=your_app_file.py flask run
Debug
Known issues
breakingSpectree v2.0.0 introduced breaking changes by dropping support for Pydantic v1 and Python 3.9. Your application will fail to run if you upgrade spectree to v2+ while still using Pydantic v1 or Python 3.9.
fix
Upgrade Pydantic to v2 (`pip install -U pydantic`) and ensure your project runs on Python 3.10 or newer. If you must use Pydantic v1, pin `spectree` to `<2.0.0` (e.g., `pip install 'spectree<2'`).
affects: >=2.0.0
gotchaMixing Pydantic v1 and v2 models in the same application, or passing a Pydantic v1 model as an attribute to a Pydantic v2 model, can lead to runtime `ValidationError`s that are difficult to debug.
fix
Avoid mixing Pydantic v1 and v2 models. If migrating, ensure all models are converted to Pydantic v2. Use tools like `bump-pydantic` to aid in migration if your codebase is large.
affects: >=2.0.0
gotchaIn Pydantic v2 (required by `spectree` v2+), fields annotated with `typing.Optional[Type]` are now 'required but can be `None`' unless a default value (e.g., `None`) is explicitly provided. This is a change from Pydantic v1 behavior.
fix
For optional fields that should have `None` as a default, explicitly set `Field(default=None)` or assign `None` as the default value in your Pydantic `BaseModel`. Example: `my_field: Optional[str] = None` or `my_field: Optional[str] = Field(default=None)`.
affects: >=2.0.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pydantic.v1'
Your application is attempting to import `pydantic.v1.BaseModel` (or other v1 components) while `spectree` v2+ is installed, which expects Pydantic v2.
fix
Upgrade Pydantic to v2 (`pip install -U pydantic`) and update your Pydantic model imports from `pydantic.v1` to `pydantic`. If you need Pydantic v1, you must downgrade `spectree` to a version before 2.0.0 (e.g., `pip install 'spectree<2'`).
TypeError: 'NoneType' object is not callable (or similar related to Optional fields in Pydantic v2)
In Pydantic v2, `Optional[Type]` fields without an explicit `None` default are treated as required fields that can accept `None`. If the input JSON omits this field, Pydantic raises an error.
fix
Ensure that any Pydantic fields you intend to be truly optional (i.e., not present in the input) are explicitly given a default value of `None`. Example: `my_field: Optional[str] = None`.
spectree.exceptions.InvalidPathParameter: Parameter 'user_id' in path '/user/<user_id>' is not annotated in endpoint 'get_user'
You have defined a path parameter in your framework's route (e.g., Flask's `<user_id>`) but have not included it as a type-hinted parameter in your decorated endpoint function, or `spectree` could not correctly parse it.
fix
Ensure that all path parameters in your route string are present as annotated arguments in your function signature, e.g., `@app.route('/user/<int:user_id>') def get_user(user_id: int):`. Spectree uses these annotations to generate the OpenAPI path parameters.
Upgrade
Version history
2.0.1latest on PyPI · released Dec 16, 2025
Audit
Dependencies
pydanticrequiredCore dependency for defining data models and validation schemas. Spectree v2.0.0+ requires Pydantic v2.
flaskoptionalRequired for Flask integration if using 'flask' backend. Choose your web framework backend accordingly.
quartoptionalRequired for Quart integration if using 'quart' backend.
falconoptionalRequired for Falcon integration if using 'falcon' or 'falcon-asgi' backend.
starletteoptionalRequired for Starlette integration if using 'starlette' backend.
Agent activity
21 hits · last 30 days
node
20
Resources
spectree — pip install spectree · libregistry