You could use a dependency, which is a function that can take all the same parameters that an endpoint can take. Inside the dependency function, you could perform the required checks to ensure that the user has provided only one of the optional parameters. If so, return a dictionary back to the endpoint, including the parameters and their values, which can help you find which parameter (and its value) was used by the client. Otherwise, if values for more than one parameters were provided, you could raise an HTTPException
, informing the user for the restrictions applied to that endpoint.
Please note that the example below uses the Optional
keyword from the typing
module (as shown in the example provided in your question) to declare optional parameters. However, in Python 3.10+, one could also use, for instance, guid: str | None = None
. In either case, the most important part to make a parameter optional is the part = None
. Please have a look at this answer and this answer to find more details and all the available options to make parameters optional in FastAPI.
Working Example
from fastapi import FastAPI, Depends, HTTPException
from typing import Optional
app = FastAPI()
def params(
guid: Optional[str] = None,
code: Optional[str] = None,
path: Optional[str] = None,
):
if sum(i is not None for i in [guid, code, path]) != 1:
raise HTTPException(400, 'Please provide only one of either guid, code or path')
else:
return {'guid': guid, 'code': code, 'path': path}
@app.get('/')
def main(d: dict = Depends(params)):
for k, v in d.items():
if v:
return {k: v}