Skip to content

[Bug] Pydantic query validation with extra data not defined in model raise's KeyError #247

@sagarsabu-tait

Description

@sagarsabu-tait

Describe the bug
Using a pydantic model for query parameter validation fails if extra query parameters are passed to the route. This is not a pydantic validation failure (as by default pydantic ignores extra data passed to the model initializer).

Screenshots
image

To Reproduce

from sanic import Sanic, response, request
from pydantic import BaseModel
from sanic_ext import validate


class MyQueryData(BaseModel):
    name: str


app = Sanic("Example")


@app.get('/test')
@validate(query=MyQueryData)
async def handler(request: request.Request, query: MyQueryData):
    print(f"{query=}")
    return response.empty()
# Works as expected. Return 200 OK
curl <the-url>/test?name=abcd 

# Works as expected. validation error as require params not set
curl <the-url>/test

# Unexpected failure. Return 500
curl <the-url>/test?name=abcd&another=abcd

Expected behavior

Pydantic has model based settings for handling extra data being passed to model initializer. Let it handle the extra data accordingly
https://docs.pydantic.dev/2.7/api/config/#pydantic.config.ConfigDict.extra

# Expected behviour is to return 200 OK via silently ignoring extra data
curl <the-url>/test?name=abcd&another=abcd

Environment (please complete the following information):

  • OS: Ubuntu
  • Browser: N/A
  • Version
    sanic==23.12.0
    sanic-ext==23.12.0
    sanic-routing==23.12.0

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