3

I am trying to create a folder traversing api with fastapi. Say I have an end point like this:

@root_router.get("/path/{path}")
def take_path(path):
    logger.info("test %s", path)
    return path

If I do to the browser and call "URL:PORT/path/path"

it returns "path", easy. But if I try "URL:PORT/path/path/path" the code doesnt even get to the logger. I guess that makes sense as the API doesnt have that end point in existence. But it DOES exist on my server. I have figured out other ways to do this, i.e. pass the path as an array of params and rebuld in code with / separator, but passing params in url feels a bit clunky, if I can move through the paths in the url the same as my server, that would be ideal. Is this doable?

Thanks.

ScipioAfricanus
  • 1,331
  • 6
  • 18
  • 39

1 Answers1

5

Add :path to your parameter:

@root_router.get("/path/{path:path}")
async def take_path(path: str):
    logger.info("test %s", path)
    return path

Notice that this is a Starlette feature.

FireAphis
  • 6,650
  • 8
  • 42
  • 63
  • wow, that worked. thanks. This is the correct way to do it, yes? Any recommendations? I am using angular to call in the api and serve files. – ScipioAfricanus Mar 24 '20 at 16:26
  • @ScipioAfricanus In general this API design is discouraged. OpenAPI, for example, doesn't even allow defining something like this. I'd recommend passing the path as a query parameter. However if you decide to continue with the current design, this is the standard way to go. – FireAphis Mar 25 '20 at 09:38