List[str] for Query with size validation generate wrong openapi #9083
-
First check
Examplefrom typing import List
import uvicorn
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/test")
async def test(query: List[str] = Query(None, min_length=5, max_length=20)):
return query
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8080, debug=True)DescriptionAdding string validation to query of List[str] generates wrong openAPI schema:
When i expected Environment
|
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 2 replies
-
|
The OpenAPI behaviour is correct. It performs what is called "client-side validation", so stuff like the min/max length of an array is validated by the OpenAPI webui before sending the request. Theorically, there's an option in Swagger (https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/?sbsearch=validatorUrl) that should disable this validation, when setting a config variable named "validatorUrl" to null - but I don't really know how to set it from FastAPI (if possible) - (source: swagger-api/swagger-ui#630) |
Beta Was this translation helpful? Give feedback.
-
|
I expected that it will validate the string length and not the string and array length. |
Beta Was this translation helpful? Give feedback.
-
|
@syniex That's right, my bad! I think we can workaround this problem using pydantic's constr as following: from typing import List
import uvicorn
from fastapi import FastAPI, Query
from pydantic import constr
app = FastAPI()
@app.get("/test")
async def test(query: List[constr(min_length=5, max_length=20)] = Query(None)):
return query
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8080, debug=True)Still, that's far from ideal. It does not seem to be a way to define the Query() of the items inside the array - at least I found nothing about it on FastAPI docs. |
Beta Was this translation helpful? Give feedback.
-
|
I've done some investigation.
|
Beta Was this translation helpful? Give feedback.
-
|
I confirm this still happens with fastapi 0.79.0. Unfortunately the workaround is incomplete, as it does not work with MyPy. However, the OpenAPI spec is generated correctly. None of the options described in pydantic/pydantic#156 (comment) or https://stackoverflow.com/a/67871116/1413687 worked for me |
Beta Was this translation helpful? Give feedback.
-
|
I will investigate it tomorrow. |
Beta Was this translation helpful? Give feedback.
-
|
It's still there, You can't use Query with min/max length in fastapi, and rest of the solutions also won't work bcz GET method won't support the Body! @tiangolo Kindly help here |
Beta Was this translation helpful? Give feedback.
The example above doesn't work in current version.
But the following example works: