Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current path in FastAPI with domain?

Tags:

python

fastapi

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)
like image 216
JPG Avatar asked Sep 08 '25 03:09

JPG


2 Answers

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)}
like image 118
JPG Avatar answered Sep 10 '25 08:09

JPG


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}
like image 33
sahasrara62 Avatar answered Sep 10 '25 07:09

sahasrara62