Skip to content
Advertisement

How to redirect to dynamic URL inside a FastAPI endpoint?

I’m doing a feature where the user on their profile page makes changes (not related to the user model). Everything is implemented through static HTML templates. I need the user to click on the button and return to the same page (i.e., their profile page) after processing the request.

Html template

JavaScript

endpoints.py

JavaScript

profile.py

JavaScript

But I can’t find anywhere how to do a redirect similar to the logic that applies to templates. For example:

JavaScript

Advertisement

Answer

You can use url_for() function and pass the (**kwargs) path parameters.

JavaScript

To add query params

In case you had to pass query params as well, you could use the following code (make sure to import urllib). Alternatively, you could use the CustomURLProcessor, as described in this and this answer (which pretty much follows the same approach).

If the endpoint expected query params, for example:

JavaScript

you could use:

JavaScript

or even use:

JavaScript

Update

Another solution would be to use Starlette’s starlette.datastructures.URL, which now provides a method to include_query_params. Example:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement