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,
some-domain.com
)/foo/bar/{rand_int}/foo-bar/
)?somethig=foo
)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 ( or str(Request.url)
), 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": str(request.url)}
In latest version of FastAPI (0.103.1)
using Request
module from from fastapi import Request
we can get the domain, path and query params
using
domain = request.base_url
path = request.url.path
query_params = request.query_params
example would be
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/foo/bar/{rand_int}/foo-bar/")
async def main(rand_int: int, request: Request):
domain = request.base_url
path = request.url.path
query_params = request.query_params
return {"domain": domain, "path": path, "query_params": query_params}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With