bauerji / flask-pydantic

flask extension for integration with the awesome pydantic package
MIT License
352 stars 56 forks source link

Validation of ResponseModel? #85

Open ScottSturdivant opened 7 months ago

ScottSturdivant commented 7 months ago

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?

bauerji commented 7 months ago

Hey, you would expect the error to be raised on runtime? I think mypy should catch this issue. Do you use some kind of static type checker?