Lostsoul
Lostsoul

Reputation: 26067

How can I use both required and optional path parameters in a FastAPI endpoint?

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?

Upvotes: 6

Views: 4141

Answers (1)

lsabi
lsabi

Reputation: 4496

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.

Upvotes: 8

Related Questions