Merge pull request #21816 from regisb/regisb/simplify-swagger-auto-schema
Regisb/simplify swagger auto schema
This commit is contained in:
162
openedx/core/apidocs.py
Normal file
162
openedx/core/apidocs.py
Normal file
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
Open API support.
|
||||
"""
|
||||
|
||||
import textwrap
|
||||
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.generators import OpenAPISchemaGenerator
|
||||
from drf_yasg.utils import swagger_auto_schema as drf_swagger_auto_schema
|
||||
from drf_yasg.views import get_schema_view
|
||||
from rest_framework import permissions
|
||||
|
||||
# -- Code that will eventually be in another openapi-helpers repo -------------
|
||||
|
||||
|
||||
class ApiSchemaGenerator(OpenAPISchemaGenerator):
|
||||
"""A schema generator for /api/*
|
||||
|
||||
Only includes endpoints in the /api/* url tree, and sets the path prefix
|
||||
appropriately.
|
||||
"""
|
||||
|
||||
def get_endpoints(self, request):
|
||||
endpoints = super(ApiSchemaGenerator, self).get_endpoints(request)
|
||||
subpoints = {p: v for p, v in endpoints.items() if p.startswith("/api/")}
|
||||
return subpoints
|
||||
|
||||
def determine_path_prefix(self, paths):
|
||||
return "/api/"
|
||||
|
||||
|
||||
def dedent(text):
|
||||
"""
|
||||
Dedent multi-line text nicely.
|
||||
|
||||
An initial empty line is ignored so that triple-quoted strings don't need
|
||||
to start with a backslash.
|
||||
"""
|
||||
if "\n" in text:
|
||||
first, rest = text.split("\n", 1)
|
||||
if not first.strip():
|
||||
# First line is blank, discard it.
|
||||
text = rest
|
||||
return textwrap.dedent(text)
|
||||
|
||||
|
||||
def schema(parameters=None):
|
||||
"""
|
||||
Decorator for documenting an API endpoint.
|
||||
|
||||
The operation summary and description are taken from the function docstring. All
|
||||
description fields should be in Markdown and will be automatically dedented.
|
||||
|
||||
Args:
|
||||
parameters (Parameter list): each object may be conveniently defined with the
|
||||
`parameter` function.
|
||||
|
||||
This is heavily inspired from the the `drf_yasg.utils.swagger_auto_schema`__
|
||||
decorator, but callers do not need to know about this abstraction.
|
||||
|
||||
__ https://drf-yasg.readthedocs.io/en/stable/drf_yasg.html#drf_yasg.utils.swagger_auto_schema
|
||||
"""
|
||||
for param in parameters or ():
|
||||
param.description = dedent(param.description)
|
||||
|
||||
def decorator(view_func):
|
||||
"""
|
||||
Final view decorator.
|
||||
"""
|
||||
operation_summary = None
|
||||
operation_description = None
|
||||
if view_func.__doc__ is not None:
|
||||
doc_lines = view_func.__doc__.strip().split("\n")
|
||||
if doc_lines:
|
||||
operation_summary = doc_lines[0].strip()
|
||||
if len(doc_lines) > 1:
|
||||
operation_description = dedent("\n".join(doc_lines[1:]))
|
||||
return drf_swagger_auto_schema(
|
||||
manual_parameters=parameters,
|
||||
operation_summary=operation_summary,
|
||||
operation_description=operation_description
|
||||
)(view_func)
|
||||
return decorator
|
||||
|
||||
|
||||
def is_schema_request(request):
|
||||
"""Is this request serving an OpenAPI schema?"""
|
||||
return request.query_params.get('format') == 'openapi'
|
||||
|
||||
|
||||
class ParameterLocation(object):
|
||||
"""Location of API parameter in request."""
|
||||
BODY = openapi.IN_BODY
|
||||
PATH = openapi.IN_PATH
|
||||
QUERY = openapi.IN_QUERY
|
||||
FORM = openapi.IN_FORM
|
||||
HEADER = openapi.IN_HEADER
|
||||
|
||||
|
||||
def string_parameter(name, in_, description=None):
|
||||
"""
|
||||
Convenient function for defining a string parameter.
|
||||
|
||||
Args:
|
||||
name (str)
|
||||
in_ (ParameterLocation attribute)
|
||||
description (str)
|
||||
"""
|
||||
return parameter(name, in_, str, description=description)
|
||||
|
||||
|
||||
def parameter(name, in_, param_type, description=None):
|
||||
"""
|
||||
Define typed parameters.
|
||||
|
||||
Args:
|
||||
name (str)
|
||||
in_ (ParameterLocation attribute)
|
||||
type (type): one of object, str, float, int, bool, list, file.
|
||||
description (str)
|
||||
"""
|
||||
openapi_type = None
|
||||
if param_type is object:
|
||||
openapi_type = openapi.TYPE_OBJECT
|
||||
elif param_type is str:
|
||||
openapi_type = openapi.TYPE_STRING
|
||||
elif param_type is float:
|
||||
openapi_type = openapi.TYPE_NUMBER
|
||||
elif param_type is int:
|
||||
openapi_type = openapi.TYPE_INTEGER
|
||||
elif param_type is bool:
|
||||
openapi_type = openapi.TYPE_BOOLEAN
|
||||
elif param_type is list:
|
||||
openapi_type = openapi.TYPE_ARRAY
|
||||
elif param_type is file:
|
||||
openapi_type = openapi.TYPE_FILE
|
||||
else:
|
||||
raise ValueError(u"Unsupported parameter type: '{}'".format(type))
|
||||
return openapi.Parameter(
|
||||
name,
|
||||
in_,
|
||||
type=openapi_type,
|
||||
description=description
|
||||
)
|
||||
# -----------------------------------------------------
|
||||
|
||||
|
||||
default_info = openapi.Info(
|
||||
title="Open edX API",
|
||||
default_version="v1",
|
||||
description="APIs for access to Open edX information",
|
||||
#terms_of_service="https://www.google.com/policies/terms/", # TODO: Do we have these?
|
||||
contact=openapi.Contact(email="oscm@edx.org"),
|
||||
#license=openapi.License(name="BSD License"), # TODO: What does this mean?
|
||||
)
|
||||
|
||||
schema_view = get_schema_view(
|
||||
default_info,
|
||||
generator_class=ApiSchemaGenerator,
|
||||
public=True,
|
||||
permission_classes=(permissions.AllowAny,),
|
||||
)
|
||||
@@ -7,7 +7,7 @@ import six
|
||||
from rest_framework import serializers
|
||||
|
||||
from openedx.core.lib.api.serializers import CourseKeyField, UsageKeyField
|
||||
from openedx.core.openapi import is_schema_request
|
||||
from openedx.core.apidocs import is_schema_request
|
||||
|
||||
|
||||
from . import DEFAULT_FIELDS, OPTIONAL_FIELDS
|
||||
|
||||
@@ -11,7 +11,6 @@ import logging
|
||||
import eventtracking
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.translation import ugettext as _
|
||||
from django.utils.translation import ugettext_noop
|
||||
from edx_rest_framework_extensions.paginators import DefaultPagination
|
||||
@@ -27,7 +26,7 @@ from rest_framework_oauth.authentication import OAuth2Authentication
|
||||
from openedx.core.djangoapps.bookmarks.api import BookmarksLimitReachedError
|
||||
from openedx.core.lib.api.permissions import IsUserInUrl
|
||||
from openedx.core.lib.url_utils import unquote_slashes
|
||||
from openedx.core.openapi import swagger_auto_schema, openapi
|
||||
from openedx.core import apidocs
|
||||
from xmodule.modulestore.exceptions import ItemNotFoundError
|
||||
|
||||
from . import DEFAULT_FIELDS, OPTIONAL_FIELDS, api
|
||||
@@ -97,9 +96,32 @@ class BookmarksViewMixin(object):
|
||||
)
|
||||
|
||||
|
||||
@method_decorator(name='get', decorator=swagger_auto_schema(
|
||||
operation_summary="Get a paginated list of bookmarks for a user.",
|
||||
operation_description=u"""
|
||||
class BookmarksListView(ListCreateAPIView, BookmarksViewMixin):
|
||||
"""REST endpoints for lists of bookmarks."""
|
||||
|
||||
authentication_classes = (OAuth2Authentication, SessionAuthentication)
|
||||
pagination_class = BookmarksPagination
|
||||
permission_classes = (permissions.IsAuthenticated,)
|
||||
serializer_class = BookmarkSerializer
|
||||
|
||||
@apidocs.schema(
|
||||
parameters=[
|
||||
apidocs.string_parameter(
|
||||
'course_id',
|
||||
apidocs.ParameterLocation.QUERY,
|
||||
description="The id of the course to limit the list",
|
||||
),
|
||||
apidocs.string_parameter(
|
||||
'fields',
|
||||
apidocs.ParameterLocation.QUERY,
|
||||
description="The fields to return: display_name, path.",
|
||||
),
|
||||
],
|
||||
)
|
||||
def get(self, request, *args, **kwargs):
|
||||
"""
|
||||
Get a paginated list of bookmarks for a user.
|
||||
|
||||
The list can be filtered by passing parameter "course_id=<course_id>"
|
||||
to only include bookmarks from a particular course.
|
||||
|
||||
@@ -117,31 +139,8 @@ class BookmarksViewMixin(object):
|
||||
# Example Requests
|
||||
|
||||
GET /api/bookmarks/v1/bookmarks/?course_id={course_id1}&fields=display_name,path
|
||||
""",
|
||||
manual_parameters=[
|
||||
openapi.Parameter(
|
||||
'course_id',
|
||||
openapi.IN_QUERY,
|
||||
type=openapi.TYPE_STRING,
|
||||
description="The id of the course to limit the list",
|
||||
),
|
||||
openapi.Parameter(
|
||||
'fields',
|
||||
openapi.IN_QUERY,
|
||||
type=openapi.TYPE_STRING,
|
||||
description="""
|
||||
The fields to return: display_name, path.
|
||||
""",
|
||||
),
|
||||
],
|
||||
))
|
||||
class BookmarksListView(ListCreateAPIView, BookmarksViewMixin):
|
||||
"""REST endpoints for lists of bookmarks."""
|
||||
|
||||
authentication_classes = (OAuth2Authentication, SessionAuthentication)
|
||||
pagination_class = BookmarksPagination
|
||||
permission_classes = (permissions.IsAuthenticated,)
|
||||
serializer_class = BookmarkSerializer
|
||||
"""
|
||||
return super(BookmarksListView, self).get(request, *args, **kwargs)
|
||||
|
||||
def get_serializer_context(self):
|
||||
"""
|
||||
@@ -201,25 +200,21 @@ class BookmarksListView(ListCreateAPIView, BookmarksViewMixin):
|
||||
|
||||
return page
|
||||
|
||||
@swagger_auto_schema(
|
||||
operation_summary="Create a new bookmark for a user.",
|
||||
operation_description=u"""
|
||||
The POST request only needs to contain one parameter "usage_id".
|
||||
|
||||
Http400 is returned if the format of the request is not correct,
|
||||
the usage_id is invalid or a block corresponding to the usage_id
|
||||
could not be found.
|
||||
|
||||
# Example Requests
|
||||
|
||||
POST /api/bookmarks/v1/bookmarks/
|
||||
Request data: {"usage_id": <usage-id>}
|
||||
|
||||
""",
|
||||
)
|
||||
@apidocs.schema()
|
||||
def post(self, request, *unused_args, **unused_kwargs):
|
||||
"""Create a new bookmark for a user."""
|
||||
"""Create a new bookmark for a user.
|
||||
|
||||
The POST request only needs to contain one parameter "usage_id".
|
||||
|
||||
Http400 is returned if the format of the request is not correct,
|
||||
the usage_id is invalid or a block corresponding to the usage_id
|
||||
could not be found.
|
||||
|
||||
# Example Requests
|
||||
|
||||
POST /api/bookmarks/v1/bookmarks/
|
||||
Request data: {"usage_id": <usage-id>}
|
||||
"""
|
||||
if not request.data:
|
||||
return self.error_response(ugettext_noop(u'No data provided.'), DEFAULT_USER_MESSAGE)
|
||||
|
||||
@@ -314,17 +309,13 @@ class BookmarksDetailView(APIView, BookmarksViewMixin):
|
||||
log.error(error_message)
|
||||
return self.error_response(error_message, error_status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
@swagger_auto_schema(
|
||||
operation_summary="Get a specific bookmark for a user.",
|
||||
operation_description=u"""
|
||||
# Example Requests
|
||||
|
||||
GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path
|
||||
|
||||
""",
|
||||
)
|
||||
@apidocs.schema()
|
||||
def get(self, request, username=None, usage_id=None):
|
||||
"""
|
||||
Get a specific bookmark for a user.
|
||||
|
||||
# Example Requests
|
||||
|
||||
GET /api/bookmarks/v1/bookmarks/{username},{usage_id}?fields=display_name,path
|
||||
"""
|
||||
usage_key_or_response = self.get_usage_key_or_error_response(usage_id=usage_id)
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
"""
|
||||
Open API support.
|
||||
"""
|
||||
|
||||
import textwrap
|
||||
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.generators import OpenAPISchemaGenerator
|
||||
from drf_yasg.utils import swagger_auto_schema as drf_swagger_auto_schema
|
||||
from drf_yasg.views import get_schema_view
|
||||
from rest_framework import permissions
|
||||
|
||||
# -- Code that will eventually be in another openapi-helpers repo -------------
|
||||
|
||||
|
||||
class ApiSchemaGenerator(OpenAPISchemaGenerator):
|
||||
"""A schema generator for /api/*
|
||||
|
||||
Only includes endpoints in the /api/* url tree, and sets the path prefix
|
||||
appropriately.
|
||||
"""
|
||||
|
||||
def get_endpoints(self, request):
|
||||
endpoints = super(ApiSchemaGenerator, self).get_endpoints(request)
|
||||
subpoints = {p: v for p, v in endpoints.items() if p.startswith("/api/")}
|
||||
return subpoints
|
||||
|
||||
def determine_path_prefix(self, paths):
|
||||
return "/api/"
|
||||
|
||||
|
||||
def dedent(text):
|
||||
"""
|
||||
Dedent multi-line text nicely.
|
||||
|
||||
An initial empty line is ignored so that triple-quoted strings don't need
|
||||
to start with a backslash.
|
||||
"""
|
||||
if "\n" in text:
|
||||
first, rest = text.split("\n", 1)
|
||||
if not first.strip():
|
||||
# First line is blank, discard it.
|
||||
text = rest
|
||||
return textwrap.dedent(text)
|
||||
|
||||
|
||||
def swagger_auto_schema(**kwargs):
|
||||
"""
|
||||
Decorator for documenting an OpenAPI endpoint.
|
||||
|
||||
Identical to `drf_yasg.utils.swagger_auto_schema`__ except that
|
||||
description fields will be dedented properly. All description fields
|
||||
should be in Markdown.
|
||||
|
||||
__ https://drf-yasg.readthedocs.io/en/stable/drf_yasg.html#drf_yasg.utils.swagger_auto_schema
|
||||
|
||||
"""
|
||||
if 'operation_description' in kwargs:
|
||||
kwargs['operation_description'] = dedent(kwargs['operation_description'])
|
||||
for param in kwargs.get('manual_parameters', ()):
|
||||
param.description = dedent(param.description)
|
||||
return drf_swagger_auto_schema(**kwargs)
|
||||
|
||||
|
||||
def is_schema_request(request):
|
||||
"""Is this request serving an OpenAPI schema?"""
|
||||
return request.query_params.get('format') == 'openapi'
|
||||
|
||||
|
||||
# -----------------------------------------------------
|
||||
|
||||
|
||||
openapi_info = openapi.Info(
|
||||
title="Open edX API",
|
||||
default_version="v1",
|
||||
description="APIs for access to Open edX information",
|
||||
#terms_of_service="https://www.google.com/policies/terms/", # TODO: Do we have these?
|
||||
contact=openapi.Contact(email="oscm@edx.org"),
|
||||
#license=openapi.License(name="BSD License"), # TODO: What does this mean?
|
||||
)
|
||||
|
||||
schema_view = get_schema_view(
|
||||
openapi_info,
|
||||
generator_class=ApiSchemaGenerator,
|
||||
public=True,
|
||||
permission_classes=(permissions.AllowAny,),
|
||||
)
|
||||
Reference in New Issue
Block a user