Skip to content

Custom Documentation

Thomas Pollet edited this page Jul 14, 2021 · 13 revisions

Overview

The OAS/swagger documentation is described in the swagger.json file. This documentation is generated from the docstrings in the code and can be customized in several ways. Several examples are implemented in the custom_swagger.py example

Import Swagger

You can modify the swagger.json by specifying the custom_swagger argument to the API constructor, for example

custom_swagger = {
        "securityDefinitions": {"Bearer": {"type": "apiKey", "in": "header", "name": "Authorization"}},
        "security": [{"Bearer": []}],
    }  # Customized swagger will be merged

api = SAFRSAPI(app, custom_swagger=custom_swagger)

This will update the generated swagger with your customizations.

Demo: https://github.com/thomaxxl/safrs/blob/master/examples/mini_examples/ex12_swagger.py

You can also customize the swagger after the models have been exposed by calling SAFRSAPI.update_spec:

api.update_spec(custom_swagger)        

Docstrings

The SAFRSBase instances can contain python docstrings that will be used to generate the swagger.json. For example

class User(SAFRSBase, db.Model):
    """
        description: User description
    """

The jsonapi_rpc methods may also contain docstrings:

    @jsonapi_rpc(http_methods=["POST"])
    def send_mail(self, **args):
        """
        description : Send an email
        args:
            email:
                type : string
                example : test email
        """
        return {"result": args}

Column Customization

Example implementation in https://github.com/thomaxxl/safrs/blob/master/examples/demo_pythonanywhere_com.py

Hide columns

class HiddenColumn(db.Column):
    """
        The "expose" attribute indicates that the column shouldn't be exposed
    """
    expose = False
class Person(BaseModel):

    __tablename__ = "People"
    id = db.Column(db.String, primary_key=True)
    name = db.Column(db.String, default="")
    password = HiddenColumn(db.String, default="")

Column Swagger Customization

Column properties can be declared that will be used to generate customized swagger, for example:

class DocumentedColumn(db.Column):
    """
        The class attributes are used for the swagger
    """
    description = "My custom column description"
    swagger_type = "string"
    swagger_format = "string"
    name_format = "filter[{}]" # Format string with the column name as argument
    required = False # Property used in the swagger url query parameters
    sample = "sample value" # Property used in the swagger update models (for POST and PATCH)