In fast api how can I use optional parameters?

I’ve read through the documentation and this doesn’t seem to be working for me. I followed this doc. But I’m not sure if it’s related to what I’m trying to do, I think this doc is for passing queries like this – site.com/endpoint?keyword=test

Here’s my goal: api.site.com/test/(optional_field)

so if someone goes to the ‘test’ endpoint then it defaults the optional field to a parameter but if they add something there then it takes that as a input.

With that said, here’s my code:

    @app.get("/company/{company_ticker}/model/{financialColumn}", dependencies=[Depends(api_counter)])
    async def myendpoint(
        company_ticker: str,
        financialColumn: Optional[str] = 'netincome',
        ..

        myFunction(company_ticker, financialColumn)

what I’m trying to do is if they just go to the endpoint without the optional flag then it defaults to ‘netincome’ but if they add something then financialColumn is set to that value.

Is there something I can do?

Answer

As far as I know, it won’t work the way you’ve set it up. Though you can try something like this:

@app.get("/company/{company_ticker}/model/", dependencies=[Depends(api_counter)])
@app.get("/company/{company_ticker}/model/{financialColumn}", dependencies=[Depends(api_counter)])
    async def myendpoint(
        company_ticker: str,
        financialColumn: Optional[str] = 'netincome'
        ):

        myFunction(company_ticker, financialColumn)

This way, if someone goes to "/company/{company_ticker}/model/" or "/company/{company_ticker}/model/blabla" the function myendpoint will handle the request.

Not sure if it works as you wish, but at the moment I cannot test it. Maybe later. Let me know.