Optinal request parameters fields/models where at least ONE OF MANY is required #8425
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI
app = FastAPI()
@app.post("/path")
async def demo_post(this: str | None = None, or_this: str | None = None):
return {
"message": this or or_this
}Description
Operating SystemLinux Operating System DetailsNo response FastAPI Version0.88.0 Python Version3.11.0 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
|
If you you only have 2 params you could use If you user You might also find this helpful: |
Beta Was this translation helpful? Give feedback.
-
|
Thank you @davismartens, your solution works for one field with different types/models. My question was about different root fields - with different names - for which indeed the links you posted proved insightful. Nonetheless, the solution they propose which is to be using a validator works inside a pydantic model. My original question is about making this work for FastAPI body parameters, is there a body-wide validator that one can define in FastAPI? |
Beta Was this translation helpful? Give feedback.
-
|
@gprieto I might be misunderstand you here... but can't you just use the pydantic model + validator as your body param? or are you asking something else? |
Beta Was this translation helpful? Give feedback.
-
|
AFAIK, openapi doesn't support such thing. Consider this approach: from typing import Literal
from fastapi.applications import FastAPI
from pydantic import BaseModel
class LessonWithExtra(BaseModel):
id: int
name: str
extra_field: str
app = FastAPI()
@app.post("/path")
async def demo_post(value: str, value_type: Literal["this", "that"]):
return {"message": f"{value_type} == {value}"}Instead of two optional |
Beta Was this translation helpful? Give feedback.
AFAIK, openapi doesn't support such thing.
Consider this approach:
Instead of two optional
thisandthatparameters define two required parameters. First of them is to pass the value and second defines type of value (thisorthat)