Skip to content

New DTO

Marc Szymkowiak edited this page Feb 7, 2022 · 1 revision

Add a new dto

  1. Add a new file book.py to app/dto and add the following code:

  2. Import Namespace and fields from flask_restx

    from flask_restx import Namespace, fields
    
  3. Add new class for book dto

    class BookDto:
        """The book dto"""
  4. Add new namespace for book api and create api(namespace) object

    • The namespace value (here book) correspond to the url namespace later (for example http://example.com/book/)
    • The description is shown in the swagger ui
       api = Namespace("book", description="book related operations")
  5. create book model object

    • Descripes the name of the json key
    • Descripes the datatype of the value
    • Descripes if its required or not
    • Description for the swagger api
        book = api.model(
            "book",
            {
                "isbn": fields.String(required=True, description="book isbn"),
                "title": fields.String(required=True, description="book title"),
                "author": fields.String(required=True, description="book author"),
            },
        )

book.py

from flask_restx import Namespace, fields


class BookDto:
    """The book dto"""

    api = Namespace("book", description="book related operations")
    book = api.model(
        "book",
        {
            "isbn": fields.String(required=True, description="book isbn"),
            "title": fields.String(required=True, description="book title"),
            "author": fields.String(required=True, description="book author"),
        },
    )