diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py index 58788bc234..1df132ce32 100644 --- a/rest_framework/schemas/openapi.py +++ b/rest_framework/schemas/openapi.py @@ -32,39 +32,30 @@ def get_info(self): return info - def get_paths(self, request=None): - result = {} - - paths, view_endpoints = self._get_paths_and_endpoints(request) - - # Only generate the path prefix for paths that will be included - if not paths: - return None + def get_schema(self, request=None, public=False): + """ + Generate a OpenAPI schema. + """ + self._initialise_endpoints() + # Iterate endpoints generating per method path operations. + # TODO: …and reference components. + paths = {} + _, view_endpoints = self._get_paths_and_endpoints(None if public else request) for path, method, view in view_endpoints: if not self.has_view_permissions(path, method, view): continue + operation = view.schema.get_operation(path, method) # Normalise path for any provided mount url. if path.startswith('/'): path = path[1:] path = urljoin(self.url or '/', path) - result.setdefault(path, {}) - result[path][method.lower()] = operation - - return result - - def get_schema(self, request=None, public=False): - """ - Generate a OpenAPI schema. - """ - self._initialise_endpoints() - - paths = self.get_paths(None if public else request) - if not paths: - return None + paths.setdefault(path, {}) + paths[path][method.lower()] = operation + # Compile final schema. schema = { 'openapi': '3.0.2', 'info': self.get_info(), diff --git a/tests/schemas/test_openapi.py b/tests/schemas/test_openapi.py index 03eb9de7a9..8a723b85d9 100644 --- a/tests/schemas/test_openapi.py +++ b/tests/schemas/test_openapi.py @@ -659,7 +659,7 @@ def test_paths_construction(self): generator = SchemaGenerator(patterns=patterns) generator._initialise_endpoints() - paths = generator.get_paths() + paths = generator.get_schema()["paths"] assert '/example/' in paths example_operations = paths['/example/'] @@ -676,7 +676,7 @@ def test_prefixed_paths_construction(self): generator = SchemaGenerator(patterns=patterns) generator._initialise_endpoints() - paths = generator.get_paths() + paths = generator.get_schema()["paths"] assert '/v1/example/' in paths assert '/v1/example/{id}/' in paths @@ -689,7 +689,7 @@ def test_mount_url_prefixed_to_paths(self): generator = SchemaGenerator(patterns=patterns, url='/api') generator._initialise_endpoints() - paths = generator.get_paths() + paths = generator.get_schema()["paths"] assert '/api/example/' in paths assert '/api/example/{id}/' in paths @@ -707,6 +707,15 @@ def test_schema_construction(self): assert 'openapi' in schema assert 'paths' in schema + def test_schema_with_no_paths(self): + patterns = [] + generator = SchemaGenerator(patterns=patterns) + + request = create_request('/') + schema = generator.get_schema(request=request) + + assert schema['paths'] == {} + def test_schema_information(self): """Construction of the top level dictionary.""" patterns = [