How to use the pydantic.Schema function in pydantic

To help you get started, we’ve selected a few pydantic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tiangolo / fastapi / tests / test_tutorial / test_body_fields / test_tutorial001.py View on Github external
import pytest
from starlette.testclient import TestClient

from body_fields.tutorial001 import app

# TODO: remove when removing support for Pydantic < 1.0.0
try:
    from pydantic import Field  # noqa
except ImportError:  # pragma: nocover
    import pydantic

    pydantic.Field = pydantic.Schema


client = TestClient(app)


openapi_schema = {
    "openapi": "3.0.2",
    "info": {"title": "Fast API", "version": "0.1.0"},
    "paths": {
        "/items/{item_id}": {
            "put": {
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {"application/json": {"schema": {}}},
                    },
github nsidnev / fastapi-realworld-example-app / app / models / article.py View on Github external
from .rwmodel import RWModel


class ArticleFilterParams(RWModel):
    tag: str = ""
    author: str = ""
    favorited: str = ""
    limit: int = 20
    offset: int = 0


class ArticleBase(RWModel):
    title: str
    description: str
    body: str
    tag_list: List[str] = Schema([], alias="tagList")


class Article(DateTimeModelMixin, ArticleBase):
    slug: str
    author: Profile
    favorited: bool
    favorites_count: int = Schema(..., alias="favoritesCount")


class ArticleInDB(DBModelMixin, Article):
    pass


class ArticleInResponse(RWModel):
    article: Article
github kemingy / flaskerk / examples / nested.py View on Github external
from flask import Flask, request
from pydantic import BaseModel, Schema
from typing import List
from random import random, randint

from flaskerk import Flaskerk


class Category(BaseModel):
    label: int = Schema(
        ...,
        ge=0,
        lt=10,
        description='label index for categories',
    )
    score: List[float]


class Response(BaseModel):
    res: List[Category] = Schema(..., max_items=128)


class Data(BaseModel):
    text: List[str] = Schema(
        ...,
        max_items=128,
github tiangolo / fastapi / fastapi / dependencies / utils.py View on Github external
def get_param_field(
    *,
    param: inspect.Parameter,
    param_name: str,
    default_field_info: Type[params.Param] = params.Param,
    force_type: params.ParamTypes = None,
    ignore_default: bool = False,
) -> ModelField:
    default_value = Required
    had_schema = False
    if not param.default == param.empty and ignore_default is False:
        default_value = param.default
    if isinstance(default_value, FieldInfo):
        had_schema = True
        field_info = default_value
        default_value = field_info.default
        if (
            isinstance(field_info, params.Param)
            and getattr(field_info, "in_", None) is None
        ):
            field_info.in_ = default_field_info.in_
        if force_type:
            field_info.in_ = force_type  # type: ignore
    else:
        field_info = default_field_info(default_value)
    required = default_value == Required
    annotation: Any = Any
    if not param.annotation == param.empty:
        annotation = param.annotation
github kemingy / flaskerk / examples / predict.py View on Github external
from flask import Flask, request, jsonify
from pydantic import BaseModel, Schema
from typing import List

from flaskerk import Flaskerk


class Data(BaseModel):
    """
    This is the description of the data model.
    """
    name: str
    limit: int = Schema(5, gt=1, lt=10, description='xxx')
    size: List[int] = []
    text: str = Schema(..., max_length=100)  # ... means no default value

    class Config:
        schema_extra = {
            'examples': [
                {
                    'name': 'user',
                    'size': [2, 3, 4],
                    'text': 'Hello World',
                }
            ]
        }


class Response(BaseModel):
    """
    basic response model
github aiogram / aiogram / aiogram / _telegram / types.py View on Github external
can_set_sticker_set: typing.Optional[bool] = None
    """True, if the bot can change the group sticker set. Returned only in getChat."""


class Message(pydantic.BaseModel):
    """
    This object represents a message.

    Source: https://core.telegram.org/bots/api#message
    """

    message_id: int
    """Unique message identifier inside this chat"""

    from_user: typing.Optional[types.User] = pydantic.Schema(None, alias="from")
    """Sender, empty for messages sent to channels"""

    date: int
    """Date the message was sent in Unix time"""

    chat: types.Chat
    """Conversation the message belongs to"""

    forward_from: typing.Optional[types.User] = None
    """For forwarded messages, sender of the original message"""

    forward_from_chat: typing.Optional[types.Chat] = None
    """For messages forwarded from channels, information about the original channel"""

    forward_from_message_id: typing.Optional[int] = None
    """For messages forwarded from channels, identifier of the original message in the channel"""
github tiangolo / fastapi / docs / tutorial / src / tutorial34.py View on Github external
from fastapi import Body, FastAPI
from pydantic import BaseModel, Schema

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = Schema(None, title="The description of the item", max_length=300)
    price: float = Schema(..., gt=0, description="The price must be greater than zero")
    tax: float = None


@app.put("/items/{item_id}")
async def update_item(*, item_id: int, item: Item = Body(..., embed=True)):
    results = {"item_id": item_id, "item": item}
    return results
github dmontagu / fastapi_client / example / client / models.py View on Github external
from typing import Any  # noqa
from typing import List, Optional

from pydantic import BaseModel, Schema
from typing_extensions import Literal


class ApiResponse(BaseModel):
    code: "Optional[int]" = Schema(None, alias="code")  # type: ignore
    type: "Optional[str]" = Schema(None, alias="type")  # type: ignore
    message: "Optional[str]" = Schema(None, alias="message")  # type: ignore


class Category(BaseModel):
    id: "Optional[int]" = Schema(None, alias="id")  # type: ignore
    name: "Optional[str]" = Schema(None, alias="name")  # type: ignore


class Order(BaseModel):
    id: "Optional[int]" = Schema(None, alias="id")  # type: ignore
    pet_id: "Optional[int]" = Schema(None, alias="petId")  # type: ignore
    quantity: "Optional[int]" = Schema(None, alias="quantity")  # type: ignore
    ship_date: "Optional[datetime]" = Schema(None, alias="shipDate")  # type: ignore
    status: 'Literal["placed", "approved", "delivered"]' = Schema(None, alias="status")  # type: ignore
    complete: "Optional[bool]" = Schema(None, alias="complete")  # type: ignore


class Pet(BaseModel):
    id: "Optional[int]" = Schema(None, alias="id")  # type: ignore
    category: "Optional[Category]" = Schema(None, alias="category")  # type: ignore
    name: "str" = Schema(..., alias="name")  # type: ignore
    photo_urls: "List[str]" = Schema(..., alias="photoUrls")  # type: ignore