marshmallow-code / apispec

A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..

Home Page:https://apispec.readthedocs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Generate specification for routes based on YAML frontmatter attribute

aalvrz opened this issue · comments

First of all thanks for this awesome library 🌟

I was wondering if it's possible to control the generation of the specification based on a certain attribute in the frontmatter. For example, I can mark some routes as public/private and decide which ones to generate when calling spec.to_yaml():

@app.route("/random")
def random_pet():
    """
    public: true
    ---
    get:
      description: Get a random pet
      security:
        - ApiKeyAuth: []
      responses:
        200:
          content:
            application/json:
              schema: PetSchema
    """
    pet = get_random_pet()
    return PetSchema().dump(pet)

You mean the view func is added to the app and functional but you just want to hide it from the spec?

apispec itself has no feature for that, and I don't think it will. But it shouldn't be too hard to achieve from user side. Just add a condition before your call to spec.path to check the "public/private" flag. Or even override spec.path to do it internally.

But it shouldn't be too hard to achieve from user side. Just add a condition before your call to spec.path to check the "public/private" flag.

@lafrech That could work. But how can we check the public/private flag when calling spec.path? If this flag is set as an attribute in the yaml frontmatter.

@lafrech Maybe this example explains it better:

# This is a "public" endpoint that will be exposed in some docs generated from the final spec
@app.route("/random")
def random_pet():
    """
    public: true
    ---
    get:
      # ...
    """


# This is a "private" endpoint that we do not want to include in those docs generated from the spec
@app.route("/foobar")
def foobar():
    """
    ---
    get:
      # ...
    """

So if I only want to generate the YAML for endpoints with public: true. Basically I was looking for something like this:

api_spec.to_yaml(public=true)  # or some other way to filter based on the frontmatter

YAML Frontmatter reference: https://assemble.io/docs/YAML-front-matter.html