Sometimes you may need to pass the filepath as a path parameter. Most of the implementations do not support to pass filepaths in the url, but FastAPI support this feature.
You need to define a path parameter like below
/file/{filePath:path}
filePath points to the actual filepath and path specifies that the parameter should match any path.
Example
@app.get("/file/{filePath:path}")
def getFileByPath(filePath: str):
return {'received' : filePath}
filePath.py
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/")
def home():
return {"name" : "Hello World app", "version": "2.0.0"}
@app.get("/file/{filePath:path}")
def getFileByPath(filePath: str):
return {'received' : filePath}
Open the terminal and execute the command 'uvicorn filePath:app --reload'.
Open the url ‘http://127.0.0.1:8000/file/a/b/c.txt’ in browser, you will receive below output.
{"received":"a/b/c.txt"}
If you want the path to
contain a leading slash (/), url should be like ‘file//a/b/c.txt’ ‘ two slashes
between file and actual file path. Open the url ‘http://127.0.0.1:8000/file//a/b/c.txt’
in browser, you will receive below output.
{"received":"/a/b/c.txt"}
Previous Next Home
No comments:
Post a Comment