Search code examples
django-rest-frameworkversioningdrf-spectacular

drf-spectacular not working when versioning is used (No operations defined in spec!)


Some weeks ago I installed drf-spectacular. Everything was working properly until I enabled versioning in DRF (Django Rest Framework).

I implemented AcceptHeaderVersioning and it was working correctly. But then I realized Swagger wasn't showing the endpoints at /docs/ and this message was shown: "No operations defined in spec!".

If I comment DEFAULT_VERSIONING_CLASS line in REST_FRAMEWORK settings, all endpoint are correctly shown in Swagger docs page (/docs/). However, it breaks my versioning: request.version = None.

I tested with AcceptHeaderVersioning, as well as with URLPathVersioning and NamespaceVersioning. Same result for all of them.

I read that AcceptHeaderVersioning was implemented a year ago. Link to the commit here.

But I also read that it was planned to change modify_for_versioning function and it could affect header versioning. Link to the function in plumbing module, here and conversation here. In fact, a lot of changes have been made to the module the last year, check here.

These are my DRF settings:

REST_FRAMEWORK = {
    # Auth
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],

    # Swagger/docs
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',

    # Pagination
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 5,

    # Testing
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',

    # Versioning
    # https://www.django-rest-framework.org/api-guide/versioning/#configuring-the-versioning-scheme
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning',
    'DEFAULT_VERSION': None,
    'ALLOWED_VERSIONS': None,
    'VERSION_PARAM': 'version',
}

Question

  1. Any idea of what I'm doing wrong? Any recommendation to make both work together (versioning and swagger)? Any suggestions?
  2. And BTW (this is secondary and not the main question): Is it possible to launch drf-spectacular tests into my own project?

Thanks in advance!


Solution

  • Question 1: Versioning works just fine. This is a common mistake. When SpectacularAPIView is versioned with AcceptHeaderVersioning (via DEFAULT_VERSIONING_CLASS), the request that fetches the schema from SpectacularAPIView likely does not contain the version header, and thus you only get unversioned endpoints (in your case none).

    Either explicitly request a versioned schema with /api/schema?version=v2 or set version manually with

    path('api/schema/', SpectacularAPIView.as_view(api_version='v2'), name='schema'),
    

    FAQ entry

    Where the magic happens and the order in which versions are used.

    Question 2: The python wheels do not include the tests. For that you would need to install the source package: https://pypi.org/project/drf-spectacular/#files