2

I want to use a GET endpoint /Users with body parameters being either a person or country. I do not want to change the request call signature, but the parameters I am sending will be changed. Is this possible ?

class PersonInfo(AppUserInfo):
    id: int
    person: str


class CountryInfo(AppUserInfo):
    id: int
    country: str

@app.get("/Users")
def get_alias_api(personinfo: PersonInfo):
    return {"data": personinfo}

@app.get("/Users")
def get_alias_api(countryinfo: CountryInfo):
    return {"data": countryinfo}
Chris
  • 18,724
  • 6
  • 46
  • 80
Tanu
  • 1,286
  • 4
  • 16
  • 35

1 Answers1

0

Yup, just use a Union of input types:

from typing import Union

@app.get("/Users")
def get_alias_api(info: Union[CountryInfo, PersonInfo]):
    return {"data": info}

If you are using python3.10+, you can also use the pipe |:

@app.get("/Users")
def get_alias_api(info: CountryInfo | PersonInfo):
    return {"data": info}
vjabuilds
  • 74
  • 3