Skip to content
Advertisement

How to get current path in FastAPI with domain?

I have a simple route as below that written in FastAPI,

from fastapi import FastAPI

app = FastAPI()


@app.get("/foo/bar/{rand_int}/foo-bar/")
async def main(rand_int: int):
    return {"path": f"https://some-domain.com/foo/bar/{rand_int}/foo-bar/?somethig=foo"}

How can I get the current path “programmatically” with,

  • domain (some-domain.com)
  • path (/foo/bar/{rand_int}/foo-bar/)
  • and query parameters (?somethig=foo)

Advertisement

Answer

We can use the Request.url-(starlette doc) API to get the various URL properties. To get the absolute URL, we need to use the Request.url._url private API , as below

from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/foo/bar/{rand_int}/foo-bar/")
async def main(rand_int: int, request: Request):
    return {"raw_url": request.url._url}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement