{"id":1013,"hash":"7397e8c0d07538bff4ad7cf12767504012c41994cad6eb1ef90b5470d43e71e2","pattern":"FastAPI - Pydantic - Value Error Raises Internal Server Error","full_message":"I am using FastAPI with Pydantic.\n\nMy problem - I need to raise ValueError using Pydantic\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, validator\nfrom fastapi import Depends, HTTPException\n\napp = FastAPI()\n\nclass RankInput(BaseModel):\n\n    rank: int\n\n    @validator('rank')\n    def check_if_value_in_range(cls, v):\n        \"\"\"\n        check if input rank is within range\n        \"\"\"\n        if not 0 < v < 1000001:\n\n            raise ValueError(\"Rank Value Must be within range (0,1000000)\")\n            #raise HTTPException(status_code=400, detail=\"Rank Value Error\") - this works But I am looking for a solution using ValueError\n        return v\n\ndef get_info_by_rank(rank):\n    return rank\n\n@app.get('/rank/{rank}')\nasync def get_rank(value: RankInput = Depends()):\n    result = get_info_by_rank(value.rank)\n    return result\n\nthis piece of code gives Internal Server Error when a ValueError is raised\n\nINFO:     127.0.0.1:59427 - \"GET /info/?rank=-1 HTTP/1.1\" 500 Internal Server Error\nERROR:    Exception in ASGI application\nTraceback (most recent call last):\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py\", line 396, in run_asgi\n    result = await app(self.scope, self.receive, self.send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py\", line 45, in __call__\n    return await self.app(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/applications.py\", line 199, in __call__\n    await super().__call__(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/applications.py\", line 111, in __call__\n    await self.middleware_stack(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/middleware/errors.py\", line 181, in __call__\n    raise exc from None\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/middleware/errors.py\", line 159, in __call__\n    await self.app(scope, receive, _send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/exceptions.py\", line 82, in __call__\n    raise exc from None\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/exceptions.py\", line 71, in __call__\n    await self.app(scope, receive, sender)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py\", line 566, in __call__\n    await route.handle(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py\", line 227, in handle\n    await self.app(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py\", line 41, in app\n    response = await func(request)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/routing.py\", line 195, in app\n    dependency_overrides_provider=dependency_overrides_provider,\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/dependencies/utils.py\", line 550, in solve_dependencies\n    solved = await run_in_threadpool(call, **sub_values)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/concurrency.py\", line 34, in run_in_threadpool\n    return await loop.run_in_executor(None, func, *args)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/thread.py\", line 57, in run\n    result = self.fn(*self.args, **self.kwargs)\n  File \"pydantic/main.py\", line 400, in pydantic.main.BaseModel.__init__\npydantic.error_wrappers.ValidationError: 1 validation error for GetInput\nrank\n  ValueError() takes no keyword arguments (type=type_error)\nERROR:uvicorn.error:Exception in ASGI application\nTraceback (most recent call last):\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py\", line 396, in run_asgi\n    result = await app(self.scope, self.receive, self.send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py\", line 45, in __call__\n    return await self.app(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/fastapi/applications.py\", line 199, in __call__\n    await super().__call__(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/applications.py\", line 111, in __call__\n    await self.middleware_stack(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/middleware/errors.py\", line 181, in __call__\n    raise exc from None\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/middleware/errors.py\", line 159, in __call__\n    await self.app(scope, receive, _send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/exceptions.py\", line 82, in __call__\n    raise exc from None\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/exceptions.py\", line 71, in __call__\n    await self.app(scope, receive, sender)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py\", line 566, in __call__\n    await route.handle(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.py\", line 227, in handle\n    await self.app(scope, receive, send)\n  File \"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/starlette/routing.p","ecosystem":"pypi","package_name":"python-3.x","package_version":null,"solution":"If you're not raising an HTTPException then normally any other uncaught exception will generate a 500 response (an Internal Server Error). If your intent is to respond with some other custom error message and HTTP status when raising a particular exception - say, ValueError - then you can use add a global exception handler to your app:\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import JSONResponse\n\n@app.exception_handler(ValueError)\nasync def value_error_exception_handler(request: Request, exc: ValueError):\n    return JSONResponse(\n        status_code=400,\n        content={\"message\": str(exc)},\n    )\n\nThis will give a 400 response (or you can change the status code to whatever you like) like this:\n\n{\n    \"message\": \"Value Must be within range (0,1000000)\"\n}","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/68914523/fastapi-pydantic-value-error-raises-internal-server-error","votes":20,"created_at":"2026-04-19T04:52:10.777119+00:00","updated_at":"2026-04-19T04:52:10.777119+00:00"}