def _hal_serializer(node, base_url, path, schema): """Recursively serialize a Document to the HAL format.""" document = { "_links": { "self": { "href": as_absolute(base_url, path), "title": schema["paths"][path]["get"].get("summary"), }, **node, } } return document
def serialize(self, document, base_url: str, path: str, schema) -> str: """Serialize a document using Core API serializer.""" doc = { "_type": "document", "_meta": { "url": as_absolute(base_url, path), "title": schema["paths"][path]["get"].get("description", ""), }, **document, } for method, link in schema["paths"][path].items(): doc[method] = { "_type": "link", "url": as_absolute(base_url, path), "action": method, "title": link.get("summary"), "description": link.get("description"), "fields": [], } # TODO Add fields from OpenAPI content / application/json / schema ? return json.dumps(doc, indent=4)
def _ld_serializer(node, base_url=None): """Recursively serialize a Document to the JSON-LD format.""" if isinstance(node, Document): ret = { key: _ld_serializer(value, base_url=base_url) for key, value in node.content.items() } if not node.url: warn("Each Resource Object SHOULD contain a 'self' link") ret["_links"] = {"self": {"href": as_absolute(base_url, node.url)}} if node.title: ret["_links"]["self"]["title"] = node.title ret["_links"].update({ key: _ld_serializer(item, base_url=base_url) for key, item in node.links.items() }) return ret if isinstance(node, Link): # The "templated" property is OPTIONAL. Its value is boolean and # SHOULD be true when the Link Object's "href" property is a URI # Template. ret = {} if node.href: ret["href"] = as_absolute(base_url, node.href) else: ret["href"] = as_absolute(base_url, node.href_template) ret["templated"] = True if node.formats: ret["type"] = node.formats[0] if node.title: ret["title"] = node.title return ret if isinstance(node, list): return [_ld_serializer(value, base_url=base_url) for value in node] return node
def serialize(self, document, base_url: str, path, schema) -> str: """Serialize a Document to the JSON-home format.""" home = { "api": { "title": schema["info"]["title"], "links": { "author": schema["info"]["contact"]["name"], "describedBy": "", }, }, "resources": {}, } for path, path_desc in schema["paths"].items(): home["resources"][path.strip("/")] = { "href": as_absolute(base_url, path), "hints": { "allow": [key.upper() for key in path_desc.keys()] }, } return json.dumps(home, indent=4)
def test_as_absolute(): assert as_absolute("http://localhost/", "/foo") == as_absolute("http://localhost/", "http://localhost/foo")