I have a code which has two endpoints. One is root and the other one is root with query parameters. However, when I call the second endpoint I am unable to get it called. It is always the first endpoint that gets called. Even if I change the order of endpoints, the second one is still unreachable.
from fastapi import APIRouter
router = APIRouter()
@router.get('/')
def index():
return 'Call like https://localhost:5000/?uname=xyz&[email protected]'
@router.get('/')
def index(uname,uemail):
return ('User Name is :' + uname + 'and User Email is: '+ uemail)
I am expecting the second function to be called, when the root path is called with query parameters.
As described in this answer and this answer, the order in which the endpoints are defined matters, as endpoints are evaluated in order. Hence, since both endpoints are using /
root path, only the first one would be called when issuing a request to http://localhost:8000/
, for instance.
What you could do is to define the query parameters as Optional
(see this answer for more details on Optional
parameters), and perform a check, inside the endpoint, on whether or not the user has included those parameters in the request, and respond accordingly. Note that for validating email addresses, you could use Pydantic's EmailStr
type (requires email-validator
to be installed), as shown here and here.
from fastapi import FastAPI
from typing import Optional
app = FastAPI()
@app.get('/')
def index(username: Optional[str] = None, email: Optional[str] = None):
if username and email:
return {'Username': username, 'Email': email}
else:
return 'Username and/or email are missing!'
Another solution would be to use custom exceptions, as described in this answer and this answer, as well as here, here and here.