The provided code effectively restricts Swagger documentation to API endpoints by filtering paths to include only those with the '/api/' prefix. It also demonstrates the customization of Swagger UI settings for a more user-friendly experience.

class ApiOnlySchemaView(get_schema_view()):
    def get_schema(self, request):
        schema = super().get_schema(request)
        # Filter the paths to show only the ones with '/api/' prefix
        api_paths = {
            path: schema['paths'][path] for path in schema['paths'] if '/api/' in path
        }
        schema['paths'] = api_paths
        return schema

    # Optional: Customize the Swagger UI settings
    def get_ui_settings(self):
        return {
            'deepLinking': True,
            'persistAuthorization': True,
            'displayRequestDuration': True,
            'docExpansion': 'none',
        }

Explanation:

  • get_schema_view(): This function is used to generate a schema view for Swagger documentation.
  • get_schema(self, request): This method overrides the default behavior of get_schema_view to filter paths.
  • api_paths = { path: schema['paths'][path] for path in schema['paths'] if '/api/' in path }: This line iterates through the paths in the schema and creates a new dictionary api_paths containing only the paths with '/api/' prefix.
  • schema['paths'] = api_paths: This line updates the schema with the filtered paths.
  • get_ui_settings(self): This method allows customizing the Swagger UI settings.

Benefits:

  • Clearer Documentation: By displaying only API endpoints, the Swagger documentation becomes more focused and less cluttered.
  • Improved User Experience: The customized Swagger UI settings enhance navigation and readability, making it easier for users to understand the API.

Note: This approach assumes that all API endpoints are prefixed with '/api/'. If this is not the case, adjust the filtering logic accordingly.