django-ninja
django-ninja copied to clipboard
How do I make trailing slashes optional?
In my API, I'd like to make trailing slashes optional. I don't want to use Django's APPEND_SLASH, since the contents of POST requests will get lost in the redirect.
Instead, I think the most user-friendly approach is to make trailing slashes optional in my API: either /api/foobar and /api/foobar/ should return the same content.
Is it possible to achieve this with django-ninja?
I'm also interested in a solution where you can easily make /api/foobar and /api/foobar/ coexist.
@taobojlen @LouisDelbosc
you can try to achieve this with django middleware
-
make sure all your apis ends with slash
-
create middleware that will append slash to every request:
def add_slash(get_response):
def middleware(request):
if not request.path.endswith('/'):
request.path_info = request.path = f"{request.path}/"
return get_response(request)
return middleware
- Add to settings.py
MIDDLEWARE = [
# ...
'path.to.yyour.middleware.add_slash',
# ...
]