Should URLPathVersioning with an optional version regex fallback to default_version

21 views
Skip to first unread message

Gideon Thomas

unread,
Jan 31, 2018, 4:41:09 PM1/31/18
to Django REST framework
Hey!

I wanted to check in here before filing an issue in the DRF repo just in case I was misunderstanding the purpose of default_version.

Suppose I have a url pattern like so:
url(r'^((?P<version>(v1|v2))/)?api/', my_view)

Note the `?` after the version regex. This was done so that during url resolution, `api/` would also match that url pattern along with `v1/api/` and `v2/api/`.

I have the following global rest framework settings:
REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
    'DEFAULT_VERSION': 'v2',
    'ALLOWED_VERSIONS': ['v1', 'v2',],
}

Expected Behavior
Hitting up `api/` would return the result of the `v2` version of `my_view`

Actual Behavior
Get back an invalid version exception in the response

After doing some investigating, it looks like when determining the version, DRF simply forwards all the `kwargs` passed to it by django during url resolution to the versioning function here. I noticed that the optional `version` named group will exist as a key in the `kwargs` but its value is `None`. Based on the logic in the function linked, it expects the `version` key not to exist and only then falls back to the default version.

My question is if this behavior is expected? If so, in what real case would you expect default version to be enforced (i.e. when will the `version` key not exist)? Also, any suggestions on how I would default to a version (globally vs. on a per-view basis is preferable) when no version is specified in the url is appreciated :)

TIA
Reply all
Reply to author
Forward
0 new messages