def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field(name='foreign_lookup_field', required=False, location='path', schema=coreschema.String( title=force_text("foreign look up "), description=force_text("foreign look up "))) ]
class CustomViewSet(GenericViewSet): @action(detail=True, schema=AutoSchema(manual_fields=[ coreapi.Field( "my_extra_field", required=True, location="path", schema=coreschema.String() ), ])) def extra_action(self, pk, **kwargs): pass
def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field(name=self.search_param, required=False, location='query', schema=coreschema.String( title=force_str(self.search_title), description=force_str(self.search_description))) ]
def get_schema_fields(self, view): return [ coreapi.Field( name='spm', location='query', required=False, type='string', example='', description='Pre post objects id get spm id, then using filter' ) ]
def get_serializer_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method not in ('PUT', 'PATCH', 'POST'): return [] if not hasattr(view, 'get_serializer'): return [] serializer = view.get_serializer() if isinstance(serializer, serializers.ListSerializer): return [ coreapi.Field( name='data', location='body', required=True, schema=coreschema.Array() ) ] if not isinstance(serializer, serializers.Serializer): return [] fields = [] for field in serializer.fields.values(): if field.read_only or isinstance(field, serializers.HiddenField): continue required = field.required and method != 'PATCH' field = coreapi.Field( name=field.field_name, location='form', required=required, schema=field_to_schema(field) ) fields.append(field) return fields
def test_schema_for_regular_views(self): """ Ensure that schema generation works for APIView classes. """ generator = SchemaGenerator(title='Example API', patterns=self.patterns) schema = generator.get_schema() expected = coreapi.Document( url='', title='Example API', content={ 'example': { 'create': coreapi.Link( url='/example/', action='post', fields=[] ), 'list': coreapi.Link( url='/example/', action='get', fields=[] ), 'read': coreapi.Link( url='/example/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'sub': { 'list': coreapi.Link( url='/example/{id}/sub/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } } ) assert schema == expected
class PasswordResetConfirm(APIView): serializer_class = OTPConfirmSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="token", required=True, location='form', schema=coreschema.String( title="Token", description="Valid token for verify user", ), ), coreapi.Field( name="otp", required=True, location='form', schema=coreschema.String( title="OTP", description="Valid otp for verify the token", ), ), ], encoding="application/json", ) def post(self, request, *args, **kwargs): serializer = self.serializer_class( data=request.data, context={'request': request}, ) serializer.is_valid(raise_exception=True) user = serializer.validated_data if user: token, created = Token.objects.get_or_create(user=user) if not created: token.delete() token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}) return Response({'otp': "Something went wrong"}, 400)
def get_schema_fields(self, views): return [ coreapi.Field( name="fields", required=False, location='query', schema=coreschema.String( title='Cursor', description=force_text( "List of fields (comma separated) to be displayed. " "If empty all are shown. Can include _set fields."))) ]
def queryarg(name, _type, description): ''' A simple helper method to generate a coreapi field out of a less verbose syntax. ''' html_desc = SafeString(markdown(dedent(description))) return coreapi.Field(name, location="query", schema=SIMPLE_QUERYARG_TYPE_MAP[_type]( description=html_desc, ))
def DocParam(name="default", location="header", required=True, description=None, type="string", *args, **kwargs): return coreapi.Field(name=name, location=location, required=required, description=description, type=type)
def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' fields = [ coreapi.Field(name="term", required=False, location='query', schema=coreschema.Integer( title='Term', description='Get classes from specific Term')) ] return fields
def get_schema_fields(self, view): return [ coreapi.Field( name=field, location='query', required=False, type='string', example='', description='', schema=None, ) for field in self.fields ]
def get_path_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any templated path variables. """ fields = [] for variable in uritemplate.variables(path): field = coreapi.Field(name=variable, location='path', required=True) fields.append(field) return fields
def test_anonymous_request(self): client = APIClient() response = client.get('/', HTTP_ACCEPT='application/coreapi+json') assert response.status_code == 200 expected = coreapi.Document( url='http://testserver/', title='Example API', content={ 'example': { 'list': coreapi.Link( url='/example/', action='get', fields=[ coreapi.Field('page', required=False, location='query', schema=coreschema.Integer(title='Page', description='A page number within the paginated result set.')), coreapi.Field('page_size', required=False, location='query', schema=coreschema.Integer(title='Page size', description='Number of results to return per page.')), coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.')) ] ), 'custom_list_action': coreapi.Link( url='/example/custom_list_action/', action='get' ), 'custom_list_action_multiple_methods': { 'read': coreapi.Link( url='/example/custom_list_action_multiple_methods/', action='get' ) }, 'read': coreapi.Link( url='/example/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()), coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.')) ] ) } } ) assert response.data == expected
def test_anonymous_request(self): client = APIClient() response = client.get('/', HTTP_ACCEPT='application/coreapi+json') self.assertEqual(response.status_code, 200) expected = coreapi.Document( url='', title='Example API', content={ 'example': { 'list': coreapi.Link(url='/example/', action='get', fields=[ coreapi.Field('page', required=False, location='query'), coreapi.Field('ordering', required=False, location='query') ]), 'custom_list_action': coreapi.Link(url='/example/custom_list_action/', action='get'), 'custom_list_action_multiple_methods': { 'read': coreapi.Link( url='/example/custom_list_action_multiple_methods/', action='get') }, 'read': coreapi.Link(url='/example/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path') ]) } }) self.assertEqual(response.data, expected)
def get_serializer_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method not in ('PUT', 'PATCH', 'POST'): return [] if not hasattr(view, 'get_serializer'): return [] serializer = view.get_serializer() if isinstance(serializer, serializers.ListSerializer): return [ coreapi.Field(name='data', location='body', required=True, type='array') ] if not isinstance(serializer, serializers.Serializer): return [] fields = [] for field in serializer.fields.values(): if field.read_only or isinstance(field, serializers.HiddenField): continue required = field.required and method != 'PATCH' description = force_text( field.help_text) if field.help_text else '' field = coreapi.Field(name=field.source, location='form', required=required, description=description, type=types_lookup[field]) fields.append(field) return fields
def test_default_actions(self): schema = coreapi.Document( url='', title='Example API', content={ 'users': { 'create': coreapi.Link( url='/users/', action='post', fields=[] ), 'list': coreapi.Link( url='/users/', action='get', fields=[] ), 'read': coreapi.Link( url='/users/{id}/', action='get', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ), 'update': coreapi.Link( url='/users/{id}/', action='patch', fields=[ coreapi.Field('id', required=True, location='path', schema=coreschema.String()) ] ) } } ) section = schema['users'] flat_links = schema_links(section) assert len(flat_links) is 4 assert 'list' in flat_links assert 'create' in flat_links assert 'read' in flat_links assert 'update' in flat_links
class createDeploymentRequest(APIView): """ This API is used to create new deployment requests. """ permission_classes = (IsAuthenticated, ) schema = AutoSchema(manual_fields=[ coreapi.Field("program_version", required=True, location="form", schema=coreschema.String()), coreapi.Field("version", required=True, location="form", schema=coreschema.String()), coreapi.Field("requested_by", required=True, location="form", schema=coreschema.String()), coreapi.Field("description", required=True, location="form", schema=coreschema.String()), coreapi.Field("technician_id", required=True, location="form", schema=coreschema.String()), coreapi.Field("status", required=True, location="form", schema=coreschema.String()) ]) def post(self, request, format=None): data = requestsService.createDeploymentRequest(request) return Response(data, status=HTTP_200_OK)
def get_schema_fields(self, _view): """ return Q parameter documentation """ fields = [ coreapi.Field(name='bbox', required=False, location='query', schema=coreschema.String( title=force_text('Bounding box.'), description=force_text(self.bbox_desc))) ] return fields
def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' fields = [ coreapi.Field(name=self.cursor_query_param, required=False, location='query', schema=coreschema.String( title='Cursor', description=force_str( self.cursor_query_description))) ] if self.page_size_query_param is not None: fields.append( coreapi.Field(name=self.page_size_query_param, required=False, location='query', schema=coreschema.Integer( title='Page size', description=force_str( self.page_size_query_description)))) return fields
def get_schema(): return coreapi.Document( url='https://api.example.com/', title='Example API', content={ 'simple_link': coreapi.Link('/example/', description='example link'), 'headers': coreapi.Link('/headers/'), 'location': { 'query': coreapi.Link('/example/', fields=[ coreapi.Field(name='example', schema=coreschema.String(description='example field')) ]), 'form': coreapi.Link('/example/', action='post', fields=[ coreapi.Field(name='example') ]), 'body': coreapi.Link('/example/', action='post', fields=[ coreapi.Field(name='example', location='body') ]), 'path': coreapi.Link('/example/{id}', fields=[ coreapi.Field(name='id', location='path') ]) }, 'encoding': { 'multipart': coreapi.Link('/example/', action='post', encoding='multipart/form-data', fields=[ coreapi.Field(name='example') ]), 'multipart-body': coreapi.Link('/example/', action='post', encoding='multipart/form-data', fields=[ coreapi.Field(name='example', location='body') ]), 'urlencoded': coreapi.Link('/example/', action='post', encoding='application/x-www-form-urlencoded', fields=[ coreapi.Field(name='example') ]), 'urlencoded-body': coreapi.Link('/example/', action='post', encoding='application/x-www-form-urlencoded', fields=[ coreapi.Field(name='example', location='body') ]), 'raw_upload': coreapi.Link('/upload/', action='post', encoding='application/octet-stream', fields=[ coreapi.Field(name='example', location='body') ]), }, 'response': { 'download': coreapi.Link('/download/'), 'text': coreapi.Link('/text/') } } )
def get_schema_fields(self, view): return [ coreapi.Field( name='org_role', location='query', required=False, type='string', schema=coreschema.String( title='Organization role users', description= 'Organization role users can be {admins|auditors|users|members}' )) ]
class ObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="username", required=True, location='form', schema=coreschema.String( title="Username", description="Valid username for authentication", ), ), coreapi.Field( name="password", required=True, location='form', schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], encoding="application/json", ) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key})
class EmailAuthToken(ObtainAuthToken): if coreapi is not None and coreschema is not None: schema = ManualSchema( fields=[ coreapi.Field( name="email", required=True, location="body", schema=coreschema.String( title="Email", description="Valid email for authentication"), ), coreapi.Field( name="password", required=True, location="form", schema=coreschema.String( title="Password", description="Valid password for authentication", ), ), ], encoding="application/json", ) serializer_class = EmailAuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return Response({ "token": token.key, "participantId": user.related_participant.id, "participantType": user.related_participant.type, "email": user.email, })
def get_manual_fields(self, path, method): extra_fields = [ coreapi.Field('field1', required=True, location='form', description='', type='', example=''), coreapi.Field('field2', required=False, location='form', description='', type='', example=''), coreapi.Field('field3', required=False, location='form', description='', type='', example='') ] manual_fields = super().get_manual_fields(path, method) return manual_fields + extra_fields
def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field( name=self.limit_query_param, required=False, location='query', schema=coreschema.Integer( title='Limit', description=force_str(self.limit_query_description) ) ), coreapi.Field( name=self.offset_query_param, required=False, location='query', schema=coreschema.Integer( title='Offset', description=force_str(self.offset_query_description) ) ) ]
def get_schema_fields(self, view): return [ coreapi.Field( name='start_at', required=False, location='query', schema=coreschema.String( title='StartAt', description=force_text("date/time in ISO format"\ " after which records were created.") ) ), coreapi.Field( name='ends_at', required=False, location='query', schema=coreschema.String( title='EndsAt', description=force_text("date/time in ISO format"\ " before which records were created.") ) ), ]
def get_schema_fields(self, view): assert (coreapi is not None ), "coreapi must be installed to use `get_schema_fields()`" assert (coreschema is not None ), "coreschema must be installed to use `get_schema_fields()`" return [ coreapi.Field( name=self.limit_query_param, required=False, location="query", schema=coreschema.Integer(title="Limit", description=force_str( self.limit_query_description)), ), coreapi.Field( name=self.offset_query_param, required=False, location="query", schema=coreschema.Integer(title="Offset", description=force_str( self.offset_query_description)), ), ]
def test_view_with_manual_schema(self): path = '/example' method = 'get' base_url = None fields = [ coreapi.Field("first_field", required=True, location="path", schema=coreschema.String()), coreapi.Field("second_field", required=True, location="path", schema=coreschema.String()), coreapi.Field("third_field", required=True, location="path", schema=coreschema.String()), ] description = "A test endpoint" class CustomView(APIView): """ ManualSchema takes list of fields for endpoint. - Provides url and action, which are always dynamic """ schema = ManualSchema(fields, description) expected = coreapi.Link(url=path, action=method, fields=fields, description=description) view = CustomView() link = view.schema.get_link(path, method, base_url) assert link == expected
def get_schema_fields(self, view): #pylint:disable=unused-argument assert coreapi is not None, 'coreapi must be installed to use'\ ' `get_schema_fields()`' assert coreschema is not None, 'coreschema must be installed '\ 'to use `get_schema_fields()`' sort_fields_description = "sort by %s" % ', '.join( [field[1] for field in self.sort_fields]) search_fields_description = "search for matching text in %s" % ( ', '.join([field_name for field_name in self.search_fields])) fields = [ coreapi.Field( name='o', required=False, location='query', schema=coreschema.String( title='O', description=force_text(sort_fields_description))), coreapi.Field( name='ot', required=False, location='query', schema=coreschema.String( title='OT', description=force_text( "sort by natural ascending or descending order"))), coreapi.Field( name='q', required=False, location='query', schema=coreschema.String( title='Q', description=force_text(search_fields_description))) ] return fields