django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

How do I make trailing slashes optional?

Open taobojlen opened this issue 1 year ago • 2 comments

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?

taobojlen avatar Jan 20 '24 14:01 taobojlen

I'm also interested in a solution where you can easily make /api/foobar and /api/foobar/ coexist.

LouisDelbosc avatar Jan 29 '24 14:01 LouisDelbosc

@taobojlen @LouisDelbosc

you can try to achieve this with django middleware

  1. make sure all your apis ends with slash

  2. 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

  1. Add to settings.py
MIDDLEWARE = [
    # ...
    'path.to.yyour.middleware.add_slash',
    # ...
]

vitalik avatar Jan 29 '24 14:01 vitalik