How to capture arbitrary paths at one route in FastAPI?

2024/11/20 1:40:32

I'm serving React app from FastAPI by mounting

app.mount("/static", StaticFiles(directory="static"), name="static")@app.route('/session')
async def renderReactApp(request: Request):return templates.TemplateResponse("index.html", {"request": request})

by this React app get served and React routing also works fine at client side but as soon as client reloads on a route which is not defined on server but used in React app FastAPI return not found to fix this I did something as below.

  • @app.route('/network')
  • @app.route('/gat')
  • @app.route('/session')

async def renderReactApp(request: Request):return templates.TemplateResponse("index.html", {"request": request})

but it seems weird and wrong to me as I need to add every route at the back-end as well as at frontend.

I'm sure there must be something like Flask @flask_app.add_url_rule('/<path:path>', 'index', index) in FastAPI which will server all arbitrary path

Answer

Since FastAPI is based on Starlette, you can use what they call "converters" with your route parameters, using type path in this case, which "returns the rest of the path, including any additional / characers."

See https://www.starlette.io/routing/#path-parameters for reference.

If your react (or vue or ...) app is using a base path, you can do something like this, which assigns anything after /my-app/ to the rest_of_path variable:

@app.get("/my-app/{rest_of_path:path}")
async def serve_my_app(request: Request, rest_of_path: str):print("rest_of_path: "+rest_of_path)return templates.TemplateResponse("index.html", {"request": request})

If you are not using a unique base path like /my-app/ (which seems to be your use case), you can still accomplish this with a catch-all route, which should go after any other routes so that it doesn't overwrite them:

@app.route("/{full_path:path}")
async def catch_all(request: Request, full_path: str):print("full_path: "+full_path)return templates.TemplateResponse("index.html", {"request": request})

(In fact you would want to use this catch-all regardless in order to catch the difference between requests for /my-app/ and /my-app)

https://en.xdnf.cn/q/26368.html

Related Q&A

Changing the active class of a link with the twitter bootstrap css in python/flask

I got the following html snippet from my page template.html.<ul class=nav><li class="active"><a href=/>Home</a></li><li><a href=/lorem>Lorem</a>…

overwriting a spark output using pyspark

I am trying to overwrite a Spark dataframe using the following option in PySpark but I am not successfulspark_df.write.format(com.databricks.spark.csv).option("header", "true",mode=…

How to patch a constant in python

I have two different modules in my project. One is a config file which containsLOGGING_ACTIVATED = FalseThis constant is used in the second module (lets call it main) like the following:if LOGGING_ACTI…

Python script for minifying CSS? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Saving numpy array to txt file row wise

I have an numpy array of forma = [1,2,3]which I want to save to a .txt file such that the file looks like:1 2 3If I use numpy.savetxt then I get a file like:1 2 3There should be a easy solution to this…

I want Python argparse to throw an exception rather than usage

I dont think this is possible, but I want to handle exceptions from argparse myself.For example:import argparse parser = argparse.ArgumentParser() parser.add_argument(--foo, help=foo help, required=Tru…

Pass Variable from python (flask) to HTML in render template?

The web server works (python flask) but when I go to the website, where the value of animal should be (dog) it shows the variable name animal. (There is more to the code but this is the most simplistic…

How to clear console in sublime text editor

How to clear console in sublime text editor. I have searched on internet too..But cant find proper shortcut for that. Please provide info

YAML loads 5e-6 as string and not a number

When I load a number with e form a JSON dump with YAML, the number is loaded as a string and not a float.I think this simple example can explain my problem.import json import yamlIn [1]: import jsonIn …

How to get rid of grid lines when plotting with Seaborn + Pandas with secondary_y

Im plotting two data series with Pandas with seaborn imported. Ideally I would like the horizontal grid lines shared between both the left and the right y-axis, but Im under the impression that this is…