def setUp(self): self.path = '/users/' self.document = coreapi.Document( content={ 'users': { 'create': coreapi.Link(action='post', url=self.path), 'list': coreapi.Link(action='get', url=self.path) } }) self.swagger = generate_swagger_object(self.document)
def setUp(self): self.path = '/users' self.document = coreapi.Document( content={ 'users': { 'create': coreapi.Link(action='post', url=self.path), 'list': coreapi.Link(action='get', url=self.path) } }) self.sut = codecs.DocumentToSwaggerConverter(self.document) \ ._get_paths_object()
def get_link(self, path, method, base_url): links = super(CreditOrganizationViewSchema, self).get_link(path, method, base_url) if method == 'PUT': if path.strip('/').endswith('Status'): return coreapi.Link( action='put', url=path, fields=[ coreapi.Field("order", required=True, location="form", schema=coreschema.Integer()), coreapi.Field("status", required=True, location="form", schema=coreschema.Integer()), ]) elif method == 'POST': if path.strip('/').endswith('Offers'): return coreapi.Link( action='post', url=path, fields=[ coreapi.Field("rotation_from", required=True, location="form", schema=coreschema.String()), coreapi.Field("rotation_to", required=True, location="form", schema=coreschema.String()), coreapi.Field("name", required=True, location="form", schema=coreschema.String()), coreapi.Field("offer_type", required=True, location="form", schema=coreschema.Integer()), coreapi.Field("score_min", required=True, location="form", schema=coreschema.Integer()), coreapi.Field("score_max", required=True, location="form", schema=coreschema.Integer()), ]) return links
async def get_forgotten_passwords(request: web.Request) -> web.Response: """Get forgotten password view, just describes that a POST is possible. """ hostname = request.app["settings"]["server"]["hostname"] return serialize( request, coreapi.Document( url=f"{hostname}/forgotten-passwords/", title="Forgotten password management", content={ "reset-password": coreapi.Link( action="post", title="", description=""" POSTing to this endpoint subscribe for a forgotten password """, fields=[ coreapi.Field(name="login"), coreapi.Field(name="email") ], ) }, ), )
def test_document_with_link_named_data(self): """ Ref #5395: Doc's `document.data` would fail with a Link named "data". As per #4972, use templatetag instead. """ document = coreapi.Document(title='Data Endpoint API', url='https://api.example.org/', content={ 'data': coreapi.Link( url='/data/', action='get', fields=[], description='Return data.') }) factory = APIRequestFactory() request = factory.get('/') renderer = DocumentationRenderer() html = renderer.render(document, accepted_media_type="text/html", renderer_context={"request": request}) assert '<h1>Data Endpoint API</h1>' in html
async def get_users(request: web.Request) -> web.Response: """View for GET /users/, just describes that a POST is possible. """ hostname = request.app["settings"]["server"]["hostname"] return serialize( request, coreapi.Document( url=f"{hostname}/users/", title="Users", content={ "users": [], "register_user": coreapi.Link( action="post", title="Register a new user", description="POSTing to this endpoint creates a new user", fields=[ coreapi.Field(name="username", required=True), coreapi.Field(name="password", required=True), coreapi.Field(name="email", required=True), ], ), }, ), )
def schema_view(request): # print("---inside schema view-----") # noinspection PyArgumentList schema = coreapi.Document( title='Your Title', url='Your host url', content={ 'search': coreapi.Link( url='/search/', action='get', fields=[ coreapi.Field(name='from', required=True, location='query', description='City name or airport code.'), coreapi.Field(name='to', required=True, location='query', description='City name or airport code.'), coreapi.Field( name='date', required=True, location='query', description='Flight date in "YYYY-MM-DD" format.') ], description='Return flight availability and prices.') }) # schema = generator.get_schema(request) return response.Response(schema)
def get_link(self, path, method, view): """ Return a `coreapi.Link` instance for the given endpoint. """ fields = self.get_path_fields(path, method, view) fields += self.get_serializer_fields(path, method, view) fields += self.get_pagination_fields(path, method, view) fields += self.get_filter_fields(path, method, view) if fields and any( [field.location in ('form', 'body') for field in fields]): encoding = self.get_encoding(path, method, view) else: encoding = None description = self.get_description(path, method, view) if self.url and path.startswith('/'): path = path[1:] data_link = coreapi.Link(url=urlparse.urljoin(self.url, path), action=method.lower(), encoding=encoding, fields=fields, description=description) data_link._api_docs = self.get_api_docs(path, method, view) return data_link
def setUp(self): self.field = coreapi.Field(name='email', required=True, location='query', description='A valid email address.') self.swagger = _get_parameters(coreapi.Link(fields=[self.field]), encoding='')
def get_link(self, path, method, base_url): """ Here we are overriding get_link method """ fields = self.get_path_fields(path, method) fields += self.get_serializer_fields(path, method) fields += self.get_pagination_fields(path, method) if self.view.action in ['list']: fields += self.get_filter_fields(path, method) manual_fields = self.get_manual_fields(path, method) fields = self.update_fields(fields, manual_fields) if fields and any( [field.location in ('form', 'body') for field in fields]): encoding = self.get_encoding(path, method) else: encoding = None description = self.get_description(path, method) if base_url and path.startswith('/'): path = path[1:] return coreapi.Link(url=urlparse.urljoin(base_url, path), action=method.lower(), encoding=encoding, fields=fields, description=description)
def schema_view(request): schema = coreapi.Document( title='Text recognition API', content={ 'api': { 'run_tesseract': coreapi.Link( title='Image', url='/api/ocr/', action='post', fields=[ coreapi.Field( name='image', required=True, location="form", description='Upload image', type='file', ) ], encoding="multipart/form-data", description='Run tesseract algorithm' ) } }, description='API document' ) return response.Response(schema)
def get_link(self, path, method, callback, view): """ Return a `coreapi.Link` instance for the given endpoint. """ fields = self.get_path_fields(path, method, callback, view) fields += self.get_serializer_fields(path, method, callback, view) fields += self.get_pagination_fields(path, method, callback, view) fields += self.get_filter_fields(path, method, callback, view) if fields and any( [field.location in ('form', 'body') for field in fields]): encoding = self.get_encoding(path, method, callback, view) else: encoding = None description = self.get_description(path, method, callback, view) return coreapi.Link( url=urlparse.urljoin(self.url, path), action=method.lower(), encoding=encoding, description=description, fields=fields, transform=None, # Not handled, but here for future reference )
def setUp(self): self.field = coreapi.Field( name='page', required=True, location='query', schema=coreschema.Integer(description='A page number.')) self.swagger = _get_parameters(coreapi.Link(fields=[self.field]), encoding='')
def get_link(self, path, method, view): """ Customized Schema generator: if __doc__ of the function exists, use the __doc__ to build the schema. else use the default serializer. """ fields = self.get_path_fields(path, method, view) yaml_doc = None # Check and load if the function has __doc__ if view and view.__doc__: try: yaml_doc = yaml.load(view.__doc__) except: yaml_doc = None #Extract schema information from yaml if yaml_doc and type(yaml_doc) != str: _method_desc = yaml_doc.get('description', '') params = yaml_doc.get('parameters', []) for i in params: _name = i.get('name') _desc = i.get('description') _required = i.get('required', False) _type = i.get('type', 'string') _location = i.get('location', 'form') field = coreapi.Field(name=_name, location=_location, required=_required, description=_desc, type=_type) fields.append(field) else: _method_desc = view.__doc__ if view and view.__doc__ else '' fields += self.get_serializer_fields(path, method, view) fields += self.get_pagination_fields(path, method, view) fields += self.get_filter_fields(path, method, view) if fields and any( [field.location in ('form', 'body') for field in fields]): encoding = self.get_encoding(path, method, view) else: encoding = None if self.url and path.startswith('/'): path = path[1:] return coreapi.Link(url=urljoin(self.url, path), action=method.lower(), encoding=encoding, fields=fields, description=_method_desc)
def setUp(self): self.field = coreapi.Field(name='published_before', required=True, location='query', schema=coreschema.String( description='Filter by published date.', format='date')) self.swagger = _get_parameters(coreapi.Link(fields=[self.field]), encoding='')
def get_link(self, path, method, view): """custom the coreapi using the func.__doc__. """ fields = self.get_path_fields(path, method, view) yaml_doc = None func = getattr(view, view.action) if getattr(view, 'action', None) else None if func and func.__doc__: try: func_doc, schema_doc = func.__doc__.split('--swagger schema--') yaml_doc = yaml.load(schema_doc) except: yaml_doc = None if yaml_doc: desc = yaml_doc.get('desc', func_doc) ret = yaml_doc.get('ret', '') err = yaml_doc.get('err', '') _method_desc = func_doc params = yaml_doc.get('params', []) for i in params: _name = i.get('name') _desc = i.get('desc', '') _required = i.get('required', True) _type = i.get('type', 'string') _location = i.get('location', 'form') field = coreapi.Field(name=_name, location=_location, required=_required, description=_desc, type=_type) fields.append(field) else: _method_desc = func.__doc__ if func and func.__doc__ else '' fields += self.get_serializer_fields(path, method, view) fields += self.get_pagination_fields(path, method, view) fields += self.get_filter_fields(path, method, view) if fields and any( [field.location in ('form', 'body') for field in fields]): encoding = self.get_encoding(path, method, view) else: encoding = None if self.url and path.startswith('/'): path = path[1:] return coreapi.Link(url=urljoin(self.url, path), action=method.lower(), encoding=encoding, fields=fields, description=_method_desc)
def get_link(self, path, method, base_url, view=None): fields = self.get_path_fields(path, method) yaml_doc = None if self._view and self._view.__doc__: try: yaml_doc = yaml.load(self._view.__doc__) except Exception as e: print(e) yaml_doc = None #Extract schema information from yaml if yaml_doc and type(yaml_doc) != str: _method_desc = yaml_doc.get('description', '') params = yaml_doc.get('parameters', []) for i in params: _name = i.get('name') _desc = i.get('description') _required = i.get('required', False) _type = i.get('type', 'string') _location = i.get('location', 'form') field = coreapi.Field(name=_name, location=_location, required=_required, description=_desc, type=_type) fields.append(field) else: _method_desc = view.__doc__ if view and view.__doc__ else '' fields += self.get_serializer_fields(path, method) fields += self.get_pagination_fields(path, method) fields += self.get_filter_fields(path, method) manual_fields = self.get_manual_fields(path, method) fields = self.update_fields(fields, manual_fields) if fields and any( [field.location in ('form', 'body') for field in fields]): encoding = self.get_encoding(path, method) else: encoding = None description = self.get_description(path, method) if base_url and path.startswith('/'): path = path[1:] return coreapi.Link(url=urlparse.urljoin(base_url, path), action=method.lower(), encoding=encoding, fields=fields, description=description)
def get_link(self, path, method, base_url): self.autoschema.view = self.view fields = self.get_path_fields(path, method) fields += self.get_pagination_fields(path, method) manual_fields = self.autoschema.get_manual_fields(path, method) fields = self.autoschema.update_fields(fields, manual_fields) link = self.autoschema.get_link(path, method, base_url) return coreapi.Link(url=link.url, action=method.lower(), encoding=link.encoding, fields=fields, description=link.description)
def get_link(self, path, method, base_url): link = super(CustomOutletRestSchema, self).get_link(path, method, base_url) path_field = [ coreapi.Field( name=link.fields[0].name, required=True, location='path', schema=coreschema.Integer( description="Outlet number. Must be an integer"), ), ] extra_fields = [] if method == 'PUT': extra_fields = [ coreapi.Field( name='name', required=False, location='form', type=coreschema.String, schema=coreschema.String( description= "Change the outlet name in the position provided", title="name")), coreapi.Field( name='status', required=False, location='form', type=coreschema.String, schema=coreschema.String( description= "Turn on or off the remote server connected to the outlet position provided. Values accepted: \'on\' or \'off\'", title='status')) ] campos = path_field + extra_fields newlink = coreapi.Link(url=link.url, action=link.action, description=link.description, encoding='application/json', fields=campos) return newlink
def get_link(url, method, func): """ Returns a CoreAPI `Link` object for a given view function. """ path_params = uritemplate.variables(url) spec = getargspec(func) names = spec.args num_optional = len(spec.defaults or []) num_required = len(names) - num_optional required_list = [True for idx in range(num_required) ] + [False for idx in range(num_optional)] default_location = 'query' if method in ('GET', 'DELETE') else 'form' locations = [ 'path' if (name in path_params) else default_location for name in names ] link_description = '' field_descriptions = ['' for name in names] if func.__doc__: docstring = dedent(func.__doc__) else: docstring = '' for line in docstring.splitlines(): if line.startswith('* '): field_name, desc = line.split('-', 1) field_descriptions.append(desc.strip()) else: link_description += line + '\n' link_description = link_description.strip() fields = [ coreapi.Field(name=name, required=required, location=location, description=description) for name, required, location, description in zip( names, required_list, locations, field_descriptions) ] return coreapi.Link(url, action=method, fields=fields, description=link_description)
async def post_jwt(request: web.Request) -> web.Response: """A user is asking for a JWT. """ data = await request.json() if "login" not in data or "password" not in data: raise web.HTTPUnprocessableEntity(reason="Missing login or password.") logger.debug("Trying to identify user %s", data["login"]) user = await request.app["identity_backend"].identify( data["login"], data["password"]) if user is None: raise web.HTTPForbidden(reason="Failed identification for kisee.") jti = shortuuid.uuid() return serialize( request, coreapi.Document( url="/jwt/", title="JSON Web Tokens", content={ "tokens": [ jwt.encode( { "iss": request.app["settings"]["jwt"]["iss"], "sub": user.user_id, "exp": datetime.utcnow() + timedelta(hours=1), "jti": jti, }, request.app["settings"]["jwt"]["private_key"], algorithm="ES256", ).decode("utf8") ], "add_token": coreapi.Link( action="post", title="Create a new JWT", description="POSTing to this endpoint create JWT tokens.", fields=[ coreapi.Field(name="login", required=True), coreapi.Field(name="password", required=True), ], ), }, ), status=201, headers={"Location": "/jwt/" + jti}, )
def get_link(self, path, method, base_url): link = super().get_link(path, method, base_url) if method == 'POST': fields = [ coreapi.Field( "file[]", required=False, location="form", schema=coreschema.String(title='file[]', description='A multipart list of files to upload.') ), coreapi.Field( "course", required=False, location="form", schema=coreschema.Integer(title='course', description=Attachment._meta.get_field('course').help_text) ), coreapi.Field( "event", required=False, location="form", schema=coreschema.Integer(title='event', description=Attachment._meta.get_field('event').help_text) ), coreapi.Field( "homework", required=False, location="form", schema=coreschema.Integer(title='homework', description=Attachment._meta.get_field('homework').help_text) ) ] return coreapi.Link( url=link.url, action=link.action, encoding=link.encoding, fields=fields, description=link.description ) return link
def schema_view(request): schema = coreapi.Document( title='NewPee API Documentation', url='https://newpee.herokuapp.com/', content={ 'search': coreapi.Link( url='api/posts/', action='get', fields=[ coreapi.Field( name='UUID', required=True, location='query', description='A string that represents a UUID'), ], description='Return all authors') }) # schema = generator.get_schema(request) return response.Response(schema)
def decode_raml(bytestring, base_url=None): loader = RAMLLoader(base_url) data = loader.load(bytestring) config = setup_config() config['validate'] = False raml = parse_raml(data, config) content = {} for resource in raml.resources: fields = [] encoding = '' for param in resource.uri_params or []: field = coreapi.Field(param.name, param.required, location='path') fields.append(field) for param in resource.query_params or []: field = coreapi.Field(param.name, param.required, location='query') fields.append(field) if resource.body: body = resource.body[0] encoding = body.mime_type for form_param in body.form_params or []: field = coreapi.Field(param.name, param.required, location='form') fields.append(field) if body.schema: schema_fields = expand_schema(body.schema) fields.extend(schema_fields) link = coreapi.Link(url=resource.absolute_uri, action=resource.method.lower(), encoding=encoding, fields=fields) content[resource.display_name] = link return coreapi.Document(title=raml.title, url=base_url, content=content)
def get_link(self, path, method, base_url): links = super(AuthViewSchema, self).get_link(path, method, base_url) if method == 'POST': return coreapi.Link(action='post', url=path, fields=[ coreapi.Field("username", description="Username", example="asdasd", required=True, location="form", schema=coreschema.String()), coreapi.Field("password", description="Password", required=True, location="form", schema=coreschema.String()), ]) return links
def get_link(route: Route) -> coreapi.Link: """ Given a single route, return a Link instance containing all the information needed to expose that route in an API Schema. """ path, method, view, name = route fields = [] # type: typing.List[coreapi.Field] path_names = set(uritemplate.URITemplate(path).variable_names) for param in inspect.signature(view).parameters.values(): fields += get_fields(param, method, path_names) if view.__doc__: description = textwrap.dedent(view.__doc__).strip() else: description = None return coreapi.Link(url=path, action=method, description=description, fields=fields)
def schema_view(request): schema = coreapi.Document( title='Occurrence Search API', content={ 'create': coreapi.Link( url='/api/occurrence/', action='get', fields=[ coreapi.Field( name='urls', required=True, schema=coreschema.Array(), description='Lista de sites iniciado com http ou https.' ), coreapi.Field(name='word', required=True, description='Palavra buscada.'), ], description='Count specific word occurrence on pages.') }) # schema = generator.get_schema(request) return response.Response(schema)
async def get_jwts(request: web.Request) -> web.Response: """Handlers for GET /jwt/, just describes that a POST is possible. """ hostname = request.app["settings"]["server"]["hostname"] return serialize( request, coreapi.Document( url=f"{hostname}/jwt/", title="JSON Web Tokens", content={ "tokens": [], "add_token": coreapi.Link( action="post", title="Create a new JWT", description="POSTing to this endpoint create JWT tokens.", fields=[ coreapi.Field(name="login", required=True), coreapi.Field(name="password", required=True), ], ), }, ), )
def test_load(): codec = coreapi.codecs.CoreJSONCodec() assert codec.decode(encoded) == { "a": 123, "next": coreapi.Link(url='http://example.org') }
def get_link(self, path, method, base_url): view = self.view method_name = getattr(view, 'action', method.lower()) method_docstring = getattr(view, method_name, None).__doc__ _method_desc = '' fields = self.get_path_fields(path, method) try: a = method_docstring.split('---') except: fields += self.get_serializer_fields(path, method) else: yaml_doc = None if method_docstring: try: yaml_doc = yaml.load(a[1]) except: yaml_doc = None # Extract schema information from yaml if yaml_doc and type(yaml_doc) != str: _desc = yaml_doc.get('desc', '') _ret = yaml_doc.get('ret', '') _err = yaml_doc.get('err', '') _method_desc = _desc + '\n<br/>' + 'return: ' + _ret + '<br/>' + 'error: ' + _err params = yaml_doc.get('input', []) for i in params: _name = i.get('name') _desc = i.get('desc') _required = i.get('required', False) _type = i.get('type', 'string') _location = i.get('location', 'form') field = coreapi.Field(name=_name, location=_location, required=_required, description=_desc, type=_type) fields.append(field) else: _method_desc = a[0] fields += self.get_serializer_fields(path, method) fields += self.get_pagination_fields(path, method) fields += self.get_filter_fields(path, method) manual_fields = self.get_manual_fields(path, method) fields = self.update_fields(fields, manual_fields) if fields and any( [field.location in ('form', 'body') for field in fields]): encoding = self.get_encoding(path, method) else: encoding = None if base_url and path.startswith('/'): path = path[1:] return coreapi.Link(url=urlparse.urljoin(base_url, path), action=method.lower(), encoding=encoding, fields=fields, description=_method_desc)