question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

ValueError in BaseModel for query parameters causes Internal Server Error

See original GitHub issue

Hi, we are using models to validate and parse query parameters. Rising ValueError in custom validator causes Internal Server Error, while it should be 422 with error description.


from pydantic import BaseModel, validator
from fastapi import Depends, FastAPI

app = FastAPI()


class QP(BaseModel):
    param_a: int = 2

    @validator('param_a')
    def validate_a(cls, v, values):
        raise ValueError('Bad parameter')


@app.get("/test_bad")
async def test_request(qp: QP = Depends()):
    # this one fails with Internal Server Error
    return 'Ok'


@app.post("/test_ok")
async def test_request(qp: QP):
    # this one works fine, responding with 422 and error description
    return 'Ok'

GET request to /test_bad or /test_bad?param_a=1 results in 500, calling /test_bad?param_a=a results in 422 which is ok (it fails before custom validator due to bad type). Using same model, but for body works as expected. (POST to /test_ok with body {"param_a":1} result in 422)

Environment

  • OS: macOS 10.15.6 (19G73), Darwin Kernel Version 19.6.0
  • FastAPI Version: 0.61.1
  • Pydantic Version: 1.6.1
  • Python version: 3.6.8 and 3.7.4

Additional context

Stacktrace:

INFO:     127.0.0.1:53141 - "GET /test_bad HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/project/dir/env/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py", line 389, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/project/dir/env/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/project/dir/env/lib/python3.7/site-packages/fastapi/applications.py", line 179, in __call__
    await super().__call__(scope, receive, send)
  File "/project/dir/env/lib/python3.7/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/project/dir/env/lib/python3.7/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/project/dir/env/lib/python3.7/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/project/dir/env/lib/python3.7/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/project/dir/env/lib/python3.7/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/project/dir/env/lib/python3.7/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/project/dir/env/lib/python3.7/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/project/dir/env/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/project/dir/env/lib/python3.7/site-packages/fastapi/routing.py", line 176, in app
    dependency_overrides_provider=dependency_overrides_provider,
  File "/project/dir/env/lib/python3.7/site-packages/fastapi/dependencies/utils.py", line 552, in solve_dependencies
    solved = await run_in_threadpool(call, **sub_values)
  File "/project/dir/env/lib/python3.7/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool
    return await loop.run_in_executor(None, func, *args)
  File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "pydantic/main.py", line 346, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for QP
param_a
  Bad parameter (type=value_error)

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
eseglemcommented, Oct 21, 2020

Using ValueError should automatically trigger a HTTPException in FastAPI. I wouldn’t change that part.

Depends is not for resolving Pydantic models, its for resolving functions. I would not expect them to behave the same. Using a Pydantic model to parse query params doesn’t appear to be supported, its for parsing JSON bodies.

You could probably do something like this:

def parse_params(request: Request):
    return QP(request.query_params._dict)

@app.get("/test_bad")
async def test_request(qp: QP = Depends(parse_params)):
    # this one fails with Internal Server Error
    return "Ok"

Probably now how its meant to be used, but could work.

0reactions
johnrazcommented, Dec 14, 2021

For what is worth, there is a workaround here: https://github.com/tiangolo/fastapi/issues/1474#issuecomment-803021344

Also, using Pydantic models should be considered valid to describe query parameters as the output of the validation is the same as eg: an Enum used to type a query param.

It would allow to keep consistency when doing more advanced validation for query parameters.

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI - Pydantic - Value Error Raises Internal Server Error
What I need to do is Raise ValueError with a Custom Status Code. Note - I know I can get the Job Done...
Read more >
Error in Messaging App: ValueError: Invalid field 'state' in leaf ...
Hello Piyush, I managed to execute the command now by 1. switching to the user running odoo Server: su odoo 2. Navigating to...
Read more >
tiangolo/fastapi - Gitter
Install Nginx and configure proxy_pass parameter in nginx.conf to specified port ... query param is empty / not set with the nice descriptive...
Read more >
Error Messages - SQLAlchemy 1.4 Documentation
Exception raised when the database encounters an internal error, e.g. the cursor is not valid anymore, the transaction is out of sync, etc....
Read more >
DataRobot Python API Documentation
Some earlier versions of setuptools will cause an error on importing ... DataRobot API can work behind a non-transparent HTTP proxy server.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found