Skip to content

Validation of ResponseModel? #85

@ScottSturdivant

Description

@ScottSturdivant

Is it possible to validate that ResponseModel is what's returned? Hoping I've missed something obvious in the docs: I see query, body, and form, along with the ability to generate response_many.

Extending the sample app.py a tiny bit:

from typing import Optional
from flask import Flask, request
from pydantic import BaseModel

from flask_pydantic import validate

app = Flask("flask_pydantic_app")

class QueryModel(BaseModel):
  age: int

class ResponseModel(BaseModel):
  id: int
  age: int
  name: str
  nickname: Optional[str] = None

# Example 1: query parameters only
@app.route("/", methods=["GET"])
@validate()
def get(query: QueryModel) -> ResponseModel:
  age = query.age
  if age > 10:
      return {'asdf': False}. # This should NOT be a valid response
  return ResponseModel(
    age=age,
    id=0, name="abc", nickname="123"
    )

Now querying and getting a response that doesn't match the expected ResponseModel:

❯ curl 'http://localhost:5000/?age=1'
{"id":0,"age":1,"name":"abc","nickname":"123"}
❯ curl 'http://localhost:5000/?age=100'
{"asdf":false}

Was hoping that there was a way to ensure that an invalid response schema couldn't be returned. Any pointers?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions