-
-
Notifications
You must be signed in to change notification settings - Fork 32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Question] optional fields in openapi body from dataclass vs validate #42
Comments
I think it ultimately is a bug in need of fixing to properly read more information from the dataclass if it is available. |
🥳 It works, thank you! I do have another corner case where a request does have only one optional parameter. Example: from dataclasses import dataclass, field
from typing import Optional
from sanic import Sanic
from sanic.log import logger
from sanic.response import json
from sanic_ext import openapi, validate
app = Sanic("Test")
@dataclass
class Test:
bar: Optional[str] = field(default_factory=str)
@app.post("/")
@openapi.body({"application/json": Test})
@validate(Test)
async def test(request, body: Test):
return json({"message": "Hello world!"}) If i omit the body completely, the validation fails again due to the request does not have a body (None):
Stacktrace:
Passing an empty body works:
Any way to specify a fallback for a |
Ah, nevermind, read through the docs again and found a convenient way to create a dummy body using a middleware. from dataclasses import dataclass, field
from typing import Optional
from sanic import Sanic
from sanic.response import json
from sanic_ext import openapi, validate
app = Sanic("Test")
@dataclass
class Test:
bar: Optional[str] = field(default_factory=str)
@app.middleware("request")
async def dummy_body_if_empty(request):
if not request.body:
request.body = b'{}'
@app.post("/")
@openapi.body({"application/json": Test})
@validate(Test)
async def test(request, body: Test):
return json({"message": "Hello world!"}) |
Description
Not sure if it's related to sanic-ext at all or just missing understanding of dataclasses on my side ;)
I'm trying to describe and validate a json body w/ optional parameters.
This renders as request body describing foobar as object or nullable.
Validation now fails when foobar is omitted (correct so far)
Now, if i set a default for
foobar
likethe request works as expected:
But now API docs renders as
object
withoutnullable
:Question
How can i combine the two? Show
foobar
asnullable
in docs and pass validation w/ parameter omitted?Do i need 2 seperate dataclasses?
Also, is it possible to show
foobar
as list of strings in the docs instead of object (derives fromOptional
, i guess).Versions
The text was updated successfully, but these errors were encountered: