If you are looking to exclude a field from JSON schema, use SkipJsonSchema:
from pydantic.json_schema import SkipJsonSchema
from pydantic import BaseModel
class MyModel(BaseModel):
visible_in_sch: str
not_visible_in_sch: SkipJsonSchema[str]
You can find out more in docs.
Answer from alpintrekker on Stack OverflowPydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
The SkipJsonSchema annotation can be used to skip an included field (or part of a field's specifications) from the generated JSON schema. See the API docs for more details. Custom types (used as field_name: TheType or field_name: Annotated[TheType, ...
GitHub
github.com › pydantic › pydantic › issues › 8150
SkipJsonSchema does not do anything · Issue #8150 · pydantic/pydantic
November 16, 2023 - from pydantic import BaseModel from pydantic.json_schema import SkipJsonSchema from typing import Union class ModelA(BaseModel): a: Union[int, SkipJsonSchema[None]] class ModelB(BaseModel): a: int print(ModelA.model_json_schema()) print(ModelB.model_json_schema()) # output looks the same for both: # {'properties': {'a': {'title': 'A', 'type': 'integer'}}, 'required': ['a'], 'title': 'ModelA', 'type': 'object'} # {'properties': {'a': {'title': 'A', 'type': 'integer'}}, 'required': ['a'], 'title': 'ModelB', 'type': 'object'}
Author antazoey
Medium
skaaptjop.medium.com › how-i-use-pydantic-unrequired-fields-so-that-the-schema-works-0010d8758072
How I use Pydantic unrequired fields without defaults | by Will van der Leij | Medium
May 22, 2024 - from pydantic import BaseModel, Field from pydantic.json_schema import SkipJsonSchema def pop_default_from_schema(s): s.pop('default', None) class Address(BaseModel): street: str city: str class Person(BaseModel): address: Address | SkipJsonSchema[None] = Field(default=None, json_schema_extra=pop_default_from_schema) The json_schema_extra allows us to supply a callable which simply pops any ‘default’ reference in the schema dict for that field.
GitHub
github.com › pydantic › pydantic › pull › 6653
✨ Add `SkipJsonSchema` annotation by Kludex · Pull Request #6653 · pydantic/pydantic
from typing import Annotated from pydantic import BaseModel, Field from pydantic.json_schema import SkipJsonSchema class Model(BaseModel): x: Annotated[int | SkipJsonSchema[None], Field(json_schema_extra=lambda x: x.pop('default'))] = None print(Model.model_json_schema()) #> {'properties': {'x': {'title': 'X', 'type': 'integer'}}, 'title': 'Model', 'type': 'object'}
Author pydantic
GitHub
github.com › pydantic › pydantic › issues › 11757
`SkipJsonSchema` on a recursive model breaks `model_json_schema` on unrelated models · Issue #11757 · pydantic/pydantic
from typing import Annotated from pydantic import BaseModel, Field from pydantic.json_schema import SkipJsonSchema class GraphNode(BaseModel): children: list["GraphNode"] class WithGraph(BaseModel): graph: GraphNode print("before skip", WithGraph.model_json_schema()) class WithoutGraph(BaseModel): graph_node: Annotated[GraphNode, Field(exclude=True), SkipJsonSchema()] print("after skip", WithGraph.model_json_schema()) print(GraphNode.model_json_schema())
PyPI
pypi.org › project › fh-pydantic-form
fh-pydantic-form · PyPI
By default, fields marked with SkipJsonSchema are hidden from forms, but you can selectively show specific ones using the keep_skip_json_fields parameter. from pydantic.json_schema import SkipJsonSchema class DocumentModel(BaseModel): title: str content: str # Hidden by default - system fields document_id: SkipJsonSchema[str] = Field( default_factory=lambda: f"doc_{uuid4().hex[:12]}", description="Internal document ID" ) created_at: SkipJsonSchema[datetime.datetime] = Field( default_factory=datetime.datetime.now, description="Creation timestamp" ) version: SkipJsonSchema[int] = Field( default=
» pip install fh-pydantic-form
GitHub
github.com › pydantic › pydantic › issues › 11500
SkipJsonSchema annotation affects model's fields validation · Issue #11500 · pydantic/pydantic
February 27, 2025 - When using SkipJsonSchema annotation on None part of a field annotation, an additional validation error none_required is added to the field's error message ... from pydantic import BaseModel from pydantic.json_schema import SkipJsonSchema class A1(BaseModel): a: str | None = None class A2(BaseModel): a: str | SkipJsonSchema[None] = None A1(a=1) #pydantic_core._pydantic_core.ValidationError: 1 validation error for A1 #a # Input should be a valid string [type=string_type, input_value=1, input_type=int] # For further information visit https://errors.pydantic.dev/2.10/v/string_type A2(a=1) #a.str
Author zoola969
Top answer 1 of 2
2
After digging a bit deeper into the pydantic code I found a nice little way to prevent this. There is a method called field_title_should_be_set(...) in GenerateJsonSchema which can be subclassed and provided to model_json_schema(...).
I'm not sure if the way I've overwritten the method is sufficient for each edge case but at least for this little test class it works as intended.
from pydantic import BaseModel
from pydantic._internal._core_utils import is_core_schema, CoreSchemaOrField
from pydantic.json_schema import GenerateJsonSchema
class Test(BaseModel):
a: int
class GenerateJsonSchemaWithoutDefaultTitles(GenerateJsonSchema):
def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool:
return_value = super().field_title_should_be_set(schema)
if return_value and is_core_schema(schema):
return False
return return_value
json_schema = Test.model_json_schema(schema_generator=GenerateJsonSchemaWithoutDefaultTitles)
assert "title" not in json_schema["properties"]["a"]
2 of 2
1
You can do it in following way with Pydantic v2:
from pydantic import BaseModel, ConfigDict
def my_schema_extra(schema: dict[str, Any]) -> None:
for prop in schema.get('properties', {}).values():
prop.pop('title', None)
class Model(BaseModel):
a: int
model_config = ConfigDict(
json_schema_extra=my_schema_extra,
)
print(Model.schema_json())
Netlify
field-idempotency--pydantic-docs.netlify.app › usage › schema
Schema - pydantic
from enum import Enum from pydantic import BaseModel, Field class FooBar(BaseModel): count: int size: float = None class Gender(str, Enum): male = 'male' female = 'female' other = 'other' not_given = 'not_given' class MainModel(BaseModel): """ This is the description of the main model """ foo_bar: FooBar = Field(...) gender: Gender = Field(None, alias='Gender') snap: int = Field( 42, title='The Snap', description='this is the value of snap', gt=30, lt=50, ) class Config: title = 'Main' # this is equivilant of json.dumps(MainModel.schema(), indent=2): print(MainModel.schema_json(indent=2))