Fastapi: OR / XOR Logic for required Query Parameters

Created on 5 Jul 2019  路  2Comments  路  Source: tiangolo/fastapi

Is it possible to add additional logic to the required query parameters?

let's say we have a simple endpoint where A and B are required (in a FastAPI sense)

@app.get('/api')
async def func(A: str,
                 B: str
                 ):

Can we now somehow use FastAPI in a way that A or B are required (OR logic)
or even A and not B or B and not A are required (XOR logic)
In both cases there would only be an error if non of the two (A,B) query parameters are set. In the XOR example also if both are set.

Is there a way to handle this additional logic by FastAPI?

e.g. pseudo code with overloading:

@app.get('/api')
async def func1(A: str,
                 B: str= None
                 ):

@app.get('/api')
async def func2(A: str =None,
                 B: str 
                 ):
question

Most helpful comment

You can validate it in dependency.

Also see this, may be useful for you.

from fastapi import FastAPI, Depends, Query, HTTPException
from typing import Optional

app = FastAPI()


async def validate(
    a: Optional[str] = Query(None), b: Optional[str] = Query(None)
) -> dict:
    if not a and not b:
        raise HTTPException(status_code=400, detail="must not provide both a and b")
    if a and b:
        raise HTTPException(status_code=400, detail="must provide a or b")

    return {"a": a, "b": b}


@app.get("/api")
async def func1(a_or_b: dict = Depends(validate)):
    return a_or_b

All 2 comments

You can validate it in dependency.

Also see this, may be useful for you.

from fastapi import FastAPI, Depends, Query, HTTPException
from typing import Optional

app = FastAPI()


async def validate(
    a: Optional[str] = Query(None), b: Optional[str] = Query(None)
) -> dict:
    if not a and not b:
        raise HTTPException(status_code=400, detail="must not provide both a and b")
    if a and b:
        raise HTTPException(status_code=400, detail="must provide a or b")

    return {"a": a, "b": b}


@app.get("/api")
async def func1(a_or_b: dict = Depends(validate)):
    return a_or_b

Thanks for the help here @Slyfoxy ! :cake: :bowing_man:

Thanks @renedlog for reporting back and closing the issue :+1:

Was this page helpful?
0 / 5 - 0 ratings