How can I get current path?
In nsidnev/fastapi-realworld-example-app, a Dependency function get_article_by_slug_from_path uses Path(..., min_length=1) to get current path, why?
The path operation contains get_article_by_slug_from_path
@router.post("", response_model=CommentInResponse,)
async def create_comment_for_article(
comment_create: CommentInCreate = Body(..., embed=True, alias="comment"),
article: Article = Depends(get_article_by_slug_from_path),
) -> CommentInResponse:
the dependency function get_article_by_slug_from_path
async def get_article_by_slug_from_path(
slug: str = Path(..., min_length=1),
user: Optional[User] = Depends(get_current_user_authorizer(required=False)),
) -> Article:
Hi!
Path is a special function that helps to get the value from the request URL. Here it is used because this dependency is then applied to some other routes to get the article by slug. If you need to get the path from the URL after the host, then you can pass a request to the FastAPI route (or dependency). After that, you can take path from URL from starlette.requests.Request if this is what you need:
from fastapi import FastAPI
from starlette.requests import Request
app = FastAPI()
@app.get("/path")
async def my_route(request: Request) -> None:
print(request.url.path)
Thanks for the discussion here, @nsidnev! :clap: :bow:
And thanks @scil for coming back to close the issue :+1:
Most helpful comment
Hi!
Pathis a special function that helps to get the value from the request URL. Here it is used because this dependency is then applied to some other routes to get the article by slug. If you need to get the path from the URL after the host, then you can pass a request to theFastAPIroute (or dependency). After that, you can take path from URL fromstarlette.requests.Requestif this is what you need: