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.

FastAPI - Pydantic - ValueError Raises Internal Server Error

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

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

app = FastAPI()

class RankInput(BaseModel):

    rank: int

    @validator('rank')
    def check_if_value_in_range(cls, v):
        """
        check if input rank is within range
        """
        if not 0 < v < 1000001:

            raise ValueError("Rank Value Must be within range (0,1000000)")
            #raise HTTPException(status_code=400, detail="Value Must be within range (0,1000000)")
        return v

def get_info_by_rank(rank):
    return rank

@app.get('/rank/{rank}')
async def get_rank(value: RankInput = Depends()):
    result = get_info_by_rank(value.rank)
    return result


Description

  • This Throws an Internal Server Error when Input is out of Range for a GET Request

  • Can we customize the Model to Raise a ValueError with a Custom Status Code Example - raise ValueError(status_code=400, detail="Value Must be within range (0,1000000)")

  • I know we can do this by raising an HTTPException like raise HTTPException(status_code=400, detail="Value Must be within range (0,1000000)")

Log

INFO:     127.0.0.1:59427 - "GET /info/?rank=-1 HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/routing.py", line 195, in app
    dependency_overrides_provider=dependency_overrides_provider,
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/dependencies/utils.py", line 550, in solve_dependencies
    solved = await run_in_threadpool(call, **sub_values)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool
    return await loop.run_in_executor(None, func, *args)
  File "/Library/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 400, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for GetInput
rank
  ValueError() takes no keyword arguments (type=type_error)
ERROR:uvicorn.error:Exception in ASGI application
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/routing.py", line 195, in app
    dependency_overrides_provider=dependency_overrides_provider,
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/dependencies/utils.py", line 550, in solve_dependencies
    solved = await run_in_threadpool(call, **sub_values)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool
    return await loop.run_in_executor(None, func, *args)
  File "/Library/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 400, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for GetInput
rank
  ValueError() takes no keyword arguments (type=type_error)

Operating System

macOS

Operating System Details

macOS 11.4

FastAPI Version

0.68.1

Python Version

Python 3.7.7

Additional Context

I posted the question on StackOverflow - https://stackoverflow.com/questions/68914523/pydantic-value-error-raises-internal-server-error

I did find a few questions on GitHub for the same but No clear answer was available.

Thank you for taking a look in advance.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:3
  • Comments:6

github_iconTop GitHub Comments

2reactions
henricarcommented, Oct 13, 2021

I am facing the same issue.

When using a POST with the class as the body, the validation works as expected - RequestValidationError is raised.

When using a GET with the class (using Depends()) as the query parameters, if the validation fails, it raises an Internal Server Error (Instead of the RequestValidationError we are expecting, ValidationError is raised). Adding an exception handler to ValidationError instead of RequestValidationError “solves” the issue, but may expose other problems, like explained in the page @Acerinth linked.

Is there a known workaround?

Seems there are already other issues opened: https://github.com/tiangolo/fastapi/issues/2180, https://github.com/tiangolo/fastapi/issues/1474

Raising HTTPException did not work for me; ValidationExceptionError somewhat worked, but it removed the possibility to show more than a single validation problem at once.

This seems to be the closest workaround I’ve found so far: https://github.com/tiangolo/fastapi/issues/1474#issuecomment-803021344

0reactions
MarkusSintonencommented, Feb 24, 2022

I can confirm that I’m facing the exact same issue and that https://github.com/tiangolo/fastapi/issues/1474#issuecomment-803021344 fixes it but is definitely not nice.

Gave another suggestion there https://github.com/tiangolo/fastapi/issues/1474#issuecomment-1049987786 which seems to also work.

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI - Pydantic - Value Error Raises Internal Server Error
If you're not raising an HTTPException then normally any other uncaught exception will generate a 500 response (an Internal Server Error ).
Read more >
Handling Errors - FastAPI
When a request contains invalid data, FastAPI internally raises a RequestValidationError . And it also includes a default exception handler for it. To...
Read more >
FastAPI - Pydantic - Value Error Raises Internal Server Error
I am using FastAPI with Pydantic. My problem - I need to raise ValueError using Pydantic from fastapi import FastAPI from pydantic import ......
Read more >
FastAPI Python Tutorial - 8: Raise error responses - YouTube
Welcome to our FastAPI Python Tutorial series. You'll build a basic API using FastAPI as a practice project.In this Part 8 video, ...
Read more >
FASTAPI error code 500: internal server error - Reddit
The error is because you tried to access an attribute ( .comment ) of an uninitialized object ( UserInput ). This could be...
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