1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How to use @doc in BlackSheep API

Discussão em 'Python' iniciado por Stack, Setembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    Use blacksheep create with the following options to create an example API:

    ✨ Project name: soquestion
    Project template: api
    Use controllers? Yes
    Use OpenAPI Documentation? Yes
    Library to read settings essentials-configuration
    App settings format YAML


    This will generate a simple API based on BlackSheep, with the endpoints defined in app/controllers/examples.py:

    """
    Example API implemented using a controller.
    """
    from typing import List, Optional

    from blacksheep.server.controllers import Controller, get, post


    class ExamplesController(Controller):
    @classmethod
    def route(cls) -> Optional[str]:
    return "/api/examples"

    @classmethod
    def class_name(cls) -> str:
    return "Examples"

    @get()
    async def get_examples(self) -> List[str]:
    """
    Gets a list of examples.


    Lorem Ipsum Dolor Sit amet
    """
    return list(f"example {i}" for i in range(3))

    @post()
    async def add_example(self, example: str):
    """
    Adds an example.
    """


    When you start the API (don't forget to create and activate a virtual environment before you do the pip install ...) with python dev.py and navigate to http://localhost:44777/docs you can see the OpenAPI documentation.

    According to the documentation you can use the docstring to specify the endpoint description.

    Is it somehow possible to also add documentation for the responses?

    According to the documentation you can use the @docs decorator, but that only works in a simple file where @docs is defined beforehand. In the generated API @docs is defined in app/docs/__init.py__, but I can't find a way to use this inside the example.py.

    The generated app/docs/__init.py__ looks like this:

    """
    This module contains OpenAPI Documentation definition for the API.

    It exposes a docs object that can be used to decorate request handlers with additional
    information, used to generate OpenAPI documentation.
    """
    from blacksheep import Application
    from blacksheep.server.openapi.v3 import OpenAPIHandler
    from openapidocs.v3 import Info

    from app.docs.binders import set_binders_docs
    from app.settings import Settings


    def configure_docs(app: Application, settings: Settings):
    docs = OpenAPIHandler(
    info=Info(title=settings.info.title, version=settings.info.version),
    anonymous_access=True,
    )

    # include only endpoints whose path starts with "/api/"
    docs.include = lambda path, _: path.startswith("/api/")

    set_binders_docs(docs)

    docs.bind_app(app)

    Continue reading...

Compartilhe esta Página