John Difool
John Difool

Reputation: 5702

Dealing with versioning using URLPathVersioning in Django 2

I've been having some troubles lately trying to set my REST API to use path versioning.

I have the code in my_app/urls.py with:

def ping():
    return "pong"


API_PREFIX = r'^(?P<version>(v1))'

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(f'^{API_PREFIX}/ping/$', get_json(ping))) # assume that get_json returns the right thing
]

I added this lines to settings.py in the same directory:

REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning'
    'DEFAULT_VERSION': 'v1',
    'ALLOWED_VERSIONS': ('v1',),
}

This doesn't work if I do a GET localhost:8000/v1/ping/. Is a f string able to include regex syntax or is the problem somewhere else? I tried fr'^{(API_PREFIX}}/ping/$' and that didn't work either.

Bonus question: In the ping function, how can I access and check the version number passed in the path (1 in that case, but will change over time)?

Upvotes: 2

Views: 750

Answers (1)

John Difool
John Difool

Reputation: 5702

I found out the problem. This paragraph from the docs outlines the problem I was facing;

Using unnamed regular expression groups¶ As well as the named group syntax, e.g. (?P[0-9]{4}), you can also use the shorter unnamed group, e.g. ([0-9]{4}).

This usage isn’t particularly recommended as it makes it easier to accidentally introduce errors between the intended meaning of a match and the arguments of the view.

> In either case, using only one style within a given regex is recommended. When both styles are mixed, any unnamed groups are ignored and only named groups are passed to the view function.

Upvotes: 1

Related Questions