[Python] How to define two different routes/paths for the same endpoint function in FastAPI?

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    I don't want to define the scraperaia endpoint funciton below again. I just want to call the same scraperaia function for the second route/path as well.

    @app.get("/drogaraia")
    def scraperaia(urlbase="https://www.drogaraia.com.br/medicamentos",maximodepaginas=10):

    listaprincipal= []
    pagina=2
    contador=1

    while pagina<maximodepaginas:
    testeurl= ((urlbase)+".html?p="+str(pagina))
    page = requests.get(testeurl)
    results= BeautifulSoup(page.content,"html.parser")
    remedios = results.find_all("div",class_="container")

    for remedio in remedios:
    try:
    link=(remedio.find("a", class_="show-hover"))['href']
    preco=remedio.find(class_="price").getText().strip()
    titulo=(remedio.find("a", class_="show-hover")).getText()
    categoria=urlbase.rsplit('/',1)[-1]
    listaremedio=[{'link':link,'preco':preco,'titulo':titulo,'categoria':categoria}]
    listaprincipal.extend(listaremedio)

    except:
    pass

    contador=contador+1

    pagina=pagina+1
    return(listaprincipal)


    @app.get("/drogaraia/medicamentos/monitores-e-testes/teste-de-controle-glicemicos")
    scraperaia(urlbase="https://www.drogaraia.com.br/medicamentos/monitores-e-testes/teste-de-controle-glicemicos",maximodepaginas=10)


    Error message:

    scraperaia(urlbase="https://www.drogaraia.com.br/medicamentos/monitores-e-testes/teste-de-controle-glicemicos",maximodepaginas=10)
    ^^^^^^^^^^
    SyntaxError: invalid syntax


    I don't see how can the syntax be wrong. I have tried not assigning the variables inside the scraperaia() function, like so:

    urlbase="https://www.drogaraia.com.br/medicamentos/monitores-e-testes/teste-de-controle-glicemicos"
    maximodepaginas=10
    scraperaia(urlbase,maximodepaginas)


    and it still doesn't work.

    Continue reading...

Compartilhe esta Página