### GET /db - List pets via SQLAlchemy cursor (post-pagination) Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt This endpoint lists pets using SQLAlchemy and a cursor-based pagination strategy. The `CursorPage` class handles the pagination logic, and the response includes pagination metadata in the `X-Pagination` header. ```APIDOC ## GET /db ### Description List pets via SQLAlchemy cursor (post-pagination). ### Method GET ### Endpoint /db ### Parameters #### Query Parameters - **page** (int) - Optional - The page number to retrieve. - **page_size** (int) - Optional - The number of items per page. ### Response #### Success Response (200) - **PetSchema (many=True)** - A list of pet objects. #### Response Example ```json [ { "id": 1, "name": "Buddy", "updated_at": "2023-10-27T10:00:00" } ] ``` ### Response Headers - **X-Pagination** (JSON) - Pagination metadata including total items, total pages, current page, and navigation links. ``` -------------------------------- ### Enable ETag for MethodView GET Requests Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Applies the @blp.etag decorator to a MethodView to automatically compute and validate ETags for GET requests based on serialized response data. ```python @blp.route("/") @blp.etag class PetById(MethodView): @blp.response(200, PetSchema) def get(self, pet_id): """ETag is set automatically from the serialized Pet""" return Pet.get_by_id(pet_id) ``` -------------------------------- ### Blueprint.etag - HTTP Cache Validation Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt The `Blueprint.etag` decorator enables ETag computation and validation for MethodViews. It automatically computes ETags for GET requests from serialized data and allows manual checking for mutating requests. ```APIDOC ## Blueprint.etag ### Description Enables ETag computation and validation for HTTP caching. ### Method GET, PUT, PATCH, DELETE ### Endpoint /pets/{pet_id} ### Parameters #### Path Parameters - **pet_id** (int) - Required - The ID of the pet. #### Request Body (for PUT/PATCH) - **PetSchema** - The data to update the pet with. ### Request Example (PUT) ```http PUT /pets/1 HTTP/1.1 Host: example.com If-Match: "abc123" Content-Type: application/json { "name": "Buddy Updated" } ``` ### Response #### Success Response (200 for GET/PUT) - **PetSchema** - The pet object. #### Success Response (204 for DELETE) No content. #### Error Response (412 Precondition Failed) Returned if the client's ETag does not match the server's ETag. ### ETag Handling - **GET**: ETag is automatically computed from the serialized response. - **PUT/PATCH/DELETE**: Use `blp.check_etag(resource, Schema)` to verify the client's ETag before mutation. - **Custom ETag**: Use `blp.set_etag(data)` to set an ETag from arbitrary data. ``` ```APIDOC ## Blueprint.etag (List Pets) ### Description Enables ETag computation for a collection of pets, using custom data for ETag generation. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **PetSchema (many=True)** - A list of pet objects. ### ETag Handling - **Custom ETag**: Use `blp.set_etag([p.updated_at.isoformat() for p in pets])` to set an ETag based on the `updated_at` timestamp of the pets. ``` -------------------------------- ### Document Custom URL Path Converters with Flask-Smorest Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Register custom Flask URL converters with the Api to document them correctly in the OpenAPI path parameters. A converter function should return a dictionary representing the OpenAPI type, format, and an example. ```python from werkzeug.routing import BaseConverter from flask_smorest import Api class ObjectIdConverter(BaseConverter): regex = r"[0-9a-f]{24}" app = Flask(__name__) app.url_map.converters["objectid"] = ObjectIdConverter api = Api(app) def objectid_to_schema(converter): return {"type": "string", "format": "ObjectId", "example": "507f1f77bcf86cd799439011"} api.register_converter(ObjectIdConverter, objectid_to_schema) blp = Blueprint("pets", "pets", url_prefix="/pets") @blp.route("/") @blp.response(200, PetSchema) def get_pet(pet_id): """pet_id is documented as type: string, format: ObjectId in OpenAPI spec""" return Pet.get_by_id(pet_id) ``` -------------------------------- ### Initialize Flask App with Flask-Smorest Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Initializes the Flask application and configures flask-smorest settings. Supports the application factory pattern. ```python from flask import Flask from flask_smorest import Api app = Flask(__name__) app.config["API_TITLE"] = "Pet Store API" app.config["API_VERSION"] = "v1" app.config["OPENAPI_VERSION"] = "3.0.2" app.config["OPENAPI_URL_PREFIX"] = "/" app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger-ui" app.config["OPENAPI_SWAGGER_UI_URL"] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/" app.config["OPENAPI_REDOC_PATH"] = "/redoc" app.config["OPENAPI_REDOC_URL"] = ( "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js" ) api = Api(app) # Application factory pattern def create_app(): app = Flask(__name__) app.config["API_TITLE"] = "Pet Store API" app.config["API_VERSION"] = "v1" app.config["OPENAPI_VERSION"] = "3.0.2" api = Api() api.init_app(app) return app ``` -------------------------------- ### Docstring-Based OpenAPI Documentation Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Leverages docstrings to generate OpenAPI documentation, where the first line serves as the summary and subsequent lines after a blank line form the description. An optional YAML block can provide further details. ```python # Docstring-based documentation (first line = summary, after blank line = description) @blp.route("/") @blp.response(200, PetSchema(many=True)) def list_pets(): """List all available pets Returns a paginated list of all pets in the store. --- This internal comment is not included in the OpenAPI spec. """ return Pet.get_all() ``` -------------------------------- ### Add OpenAPI Documentation with Blueprint.doc Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Uses the @blp.doc decorator to attach arbitrary OpenAPI operation attributes like summary, description, security, or deprecated flags to an endpoint. This overrides docstring-based documentation. ```python @blp.route("/") @blp.doc( summary="Find pet by ID", description="Returns a single pet identified by its integer ID.", deprecated=True, security=[{"bearerAuth": []}], ) @blp.response(200, PetSchema) def get_pet(pet_id): """Docstring summary is overridden by Blueprint.doc summary above.""" return Pet.get_by_id(pet_id) ``` -------------------------------- ### Define API Resources with Blueprint Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Defines API resources using Blueprint and MethodView, including request/response schema binding and OpenAPI documentation. Resources are grouped under a blueprint. ```python from flask import Flask from flask.views import MethodView import marshmallow as ma from flask_smorest import Api, Blueprint, abort app = Flask(__name__) app.config.update({ "API_TITLE": "Pet Store", "API_VERSION": "v1", "OPENAPI_VERSION": "3.0.2" }) api = Api(app) class PetSchema(ma.Schema): id = ma.fields.Int(dump_only=True) name = ma.fields.String(required=True) breed = ma.fields.String() class PetQueryArgsSchema(ma.Schema): name = ma.fields.String() breed = ma.fields.String() blp = Blueprint("pets", "pets", url_prefix="/pets", description="Operations on pets") @blp.route("/") class Pets(MethodView): @blp.arguments(PetQueryArgsSchema, location="query") @blp.response(200, PetSchema(many=True)) def get(self, args): """List pets""" return Pet.get(filters=args) @blp.arguments(PetSchema) @blp.response(201, PetSchema) def post(self, new_data): """Add a new pet""" return Pet.create(**new_data) @blp.route("/") class PetsById(MethodView): @blp.response(200, PetSchema) def get(self, pet_id): """Get pet by ID""" try: return Pet.get_by_id(pet_id) except NotFoundError: abort(404, message="Pet not found.") @blp.arguments(PetSchema) @blp.response(200, PetSchema) def put(self, update_data, pet_id): """Update existing pet""" try: item = Pet.get_by_id(pet_id) except NotFoundError: abort(404, message="Pet not found.") item.update(update_data) return item @blp.response(204) def delete(self, pet_id): """Delete pet""" try: Pet.delete(pet_id) except NotFoundError: abort(404, message="Pet not found.") api.register_blueprint(blp) ``` -------------------------------- ### Manual ETag Check Before Mutation Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Demonstrates manually checking the ETag using blp.check_etag before performing a mutating operation (PUT, DELETE). Raises a 412 error if the client's ETag does not match the current resource's ETag. ```python @blp.route("/") @blp.etag class PetById(MethodView): @blp.arguments(PetSchema) @blp.response(200, PetSchema) def put(self, update_data, pet_id): pet = Pet.get_by_id(pet_id) # Manually verify ETag before mutation (raises 412 if mismatch) blp.check_etag(pet, PetSchema) pet.update(update_data) return pet @blp.response(204) def delete(self, pet_id): pet = Pet.get_by_id(pet_id) blp.check_etag(pet, PetSchema) Pet.delete(pet_id) ``` -------------------------------- ### Blueprint.paginate Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Handles pagination automatically for list endpoints, injecting pagination parameters or slicing collections. ```APIDOC ## GET / ### Description Lists pets with manual pagination handling. ### Method GET ### Endpoint /pets/ ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **page_size** (integer) - Optional - The number of items per page. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the pet. - **name** (string) - The name of the pet. - **breed** (string) - The breed of the pet. ### Headers - **X-Pagination** - Information about the pagination (e.g., item_count, page_count, next_url, prev_url). ``` -------------------------------- ### Blueprint.doc - Attach Extra OpenAPI Documentation Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt The `Blueprint.doc` decorator allows adding custom OpenAPI operation attributes like summaries, descriptions, security schemes, and deprecation flags. ```APIDOC ## Blueprint.doc ### Description Attach extra OpenAPI documentation attributes to an endpoint. ### Method GET ### Endpoint /pets/{pet_id} ### Parameters #### Path Parameters - **pet_id** (int) - Required - The ID of the pet. ### OpenAPI Attributes - **summary**: "Find pet by ID" - **description**: "Returns a single pet identified by its integer ID." - **deprecated**: true - **security**: `[{"bearerAuth": []}]` ### Response #### Success Response (200) - **PetSchema** - The pet object. ``` ```APIDOC ## Blueprint.doc (List Pets) ### Description Documenting a pet listing endpoint using docstring conventions and `Blueprint.doc`. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **PetSchema (many=True)** - A list of all pets. ### Docstring Documentation - **Summary**: "List all available pets" - **Description**: "Returns a paginated list of all pets in the store." ``` -------------------------------- ### Deserialize and Validate Request Inputs with Blueprint.arguments Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Use Blueprint.arguments to parse, validate, and inject request data using a marshmallow Schema. The location parameter controls where data is read from. Multiple decorators can be stacked. ```python import marshmallow as ma from flask_smorest import Blueprint blp = Blueprint("pets", "pets", url_prefix="/pets") class PetSchema(ma.Schema): name = ma.fields.String(required=True) breed = ma.fields.String() class PetQueryArgsSchema(ma.Schema): name = ma.fields.String() class PetHeadersSchema(ma.Schema): x_request_id = ma.fields.String(data_key="X-Request-ID") # JSON body (default location) @blp.route("/", methods=["POST"]) @blp.arguments(PetSchema) @blp.response(201, PetSchema) def create_pet(pet_data): return Pet.create(**pet_data) # Query string args @blp.route("/search") @blp.arguments(PetQueryArgsSchema, location="query") @blp.response(200, PetSchema(many=True)) def search_pets(args): return Pet.get(filters=args) # Inject as kwargs instead of a dict @blp.route("/find") @blp.arguments(PetQueryArgsSchema, location="query", as_kwargs=True) @blp.response(200, PetSchema(many=True)) def find_pets(**kwargs): return Pet.get(filters=kwargs) # Multiple locations stacked (order matches signature order) @blp.route("/advanced", methods=["POST"]) @blp.arguments(PetSchema) # injected as pet_data @blp.arguments(PetQueryArgsSchema, location="query") # injected as query_args @blp.response(201, PetSchema) def advanced_create(pet_data, query_args): pet = Pet.create(**pet_data) return pet ``` -------------------------------- ### Api - Initialize the Flask Application Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt The Api class is the main extension class that integrates flask-smorest into a Flask app. It handles initialization of APISpec, error handlers, and serving OpenAPI documentation. ```APIDOC ## Api — Initialize the Flask Application `Api` is the main extension class. It wires flask-smorest into a Flask app, initializes the internal APISpec instance, registers error handlers, and optionally sets up routes to serve the OpenAPI JSON file and UI pages. It supports the application factory pattern via `init_app`. ```python from flask import Flask from flask_smorest import Api app = Flask(__name__) app.config["API_TITLE"] = "Pet Store API" app.config["API_VERSION"] = "v1" app.config["OPENAPI_VERSION"] = "3.0.2" app.config["OPENAPI_URL_PREFIX"] = "/" app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger-ui" app.config["OPENAPI_SWAGGER_UI_URL"] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/" app.config["OPENAPI_REDOC_PATH"] = "/redoc" app.config["OPENAPI_REDOC_URL"] = ( "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js" ) api = Api(app) # Application factory pattern def create_app(): app = Flask(__name__) app.config["API_TITLE"] = "Pet Store API" app.config["API_VERSION"] = "v1" app.config["OPENAPI_VERSION"] = "3.0.2" api = Api() api.init_app(app) return app ``` ``` -------------------------------- ### OpenAPI Spec Export CLI Commands Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Flask-smorest provides CLI commands to print or write the OpenAPI specification to a file, which is useful for CI/CD pipelines. ```APIDOC ## OpenAPI Spec Export CLI Commands ### Description These commands allow you to interact with the generated OpenAPI specification directly from your terminal. ### Commands - **`flask openapi print`**: Prints the OpenAPI specification as JSON to standard output. - `--format=yaml`: Optional. Specifies the output format as YAML instead of JSON. - **`flask openapi write `**: Writes the OpenAPI specification to a file. - `--format=yaml`: Optional. Specifies the output format as YAML instead of JSON. Defaults to JSON. ### Examples **Print spec as JSON:** ```bash flask openapi print ``` **Print spec as YAML:** ```bash flask openapi print --format=yaml ``` **Write spec to a JSON file:** ```bash flask openapi write openapi.json ``` **Write spec to a YAML file:** ```bash flask openapi write --format=yaml openapi.yaml ``` ``` -------------------------------- ### Add Pagination to List Endpoints with Blueprint.paginate Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Blueprint.paginate handles pagination automatically. In view-function mode, it injects PaginationParameters and expects the view to slice data and set item_count. In post-pagination mode, it accepts a pager class and slices a returned collection or cursor. A X-Pagination header is added to responses. ```python from flask.views import MethodView from flask_smorest import Blueprint, Page blp = Blueprint("pets", "pets", url_prefix="/pets") class PetSchema(ma.Schema): id = ma.fields.Int(dump_only=True) name = ma.fields.String() # Mode 1: View function handles pagination explicitly @blp.route("/") class Pets(MethodView): @blp.response(200, PetSchema(many=True)) @blp.paginate() def get(self, pagination_parameters): """List pets with manual pagination""" # Set total count; view slices data manually pagination_parameters.item_count = Pet.count() return Pet.get_slice( first=pagination_parameters.first_item, last=pagination_parameters.last_item, ) ``` -------------------------------- ### Blueprint.arguments Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Decorates a view method to parse, validate, and inject request data using a marshmallow Schema. The `location` parameter controls where data is read from. ```APIDOC ## POST / ### Description Creates a new pet using data from the JSON request body. ### Method POST ### Endpoint /pets/ ### Parameters #### Request Body - **name** (string) - Required - The name of the pet. - **breed** (string) - Optional - The breed of the pet. ### Response #### Success Response (201) - **name** (string) - The name of the created pet. - **breed** (string) - The breed of the created pet. ``` ```APIDOC ## GET /search ### Description Searches for pets based on provided query parameters. ### Method GET ### Endpoint /pets/search ### Parameters #### Query Parameters - **name** (string) - Optional - The name to search for. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the pet. - **name** (string) - The name of the pet. - **breed** (string) - The breed of the pet. ``` ```APIDOC ## GET /find ### Description Finds pets using query parameters passed as keyword arguments. ### Method GET ### Endpoint /pets/find ### Parameters #### Query Parameters - **name** (string) - Optional - The name to search for. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the pet. - **name** (string) - The name of the pet. - **breed** (string) - The breed of the pet. ``` ```APIDOC ## POST /advanced ### Description Advanced creation endpoint that accepts both JSON body and query parameters. ### Method POST ### Endpoint /pets/advanced ### Parameters #### Query Parameters - **name** (string) - Optional - The name to search for. #### Request Body - **name** (string) - Required - The name of the pet. - **breed** (string) - Optional - The breed of the pet. ### Response #### Success Response (201) - **name** (string) - The name of the created pet. - **breed** (string) - The breed of the created pet. ``` -------------------------------- ### Override Default Pagination Parameters Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Shows how to override default pagination parameters like page size for a specific blueprint. This allows for blueprint-specific pagination configurations. ```python class MyBlueprint(Blueprint): DEFAULT_PAGINATION_PARAMETERS = {"page": 1, "page_size": 20, "max_page_size": 200} ``` -------------------------------- ### Export OpenAPI Specification using Flask CLI Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Use Flask CLI commands to print the OpenAPI specification to stdout or write it to a file in JSON or YAML format. ```bash # Print OpenAPI spec as JSON to stdout flask openapi print ``` ```bash # Print OpenAPI spec as YAML to stdout flask openapi print --format=yaml ``` ```bash # Write spec to a JSON file flask openapi write openapi.json ``` ```bash # Write spec to a YAML file flask openapi write --format=yaml openapi.yaml ``` -------------------------------- ### Configure OpenAPI UI Options in Flask-Smorest Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Configure various OpenAPI UI options such as API title, version, JSON path, and paths for ReDoc, Swagger UI, and Rapidoc. ```python # Full app config example with all UI options enabled class Config: API_TITLE = "Pet Store API" API_VERSION = "v1" OPENAPI_VERSION = "3.0.2" OPENAPI_JSON_PATH = "api-spec.json" OPENAPI_URL_PREFIX = "/" OPENAPI_REDOC_PATH = "/redoc" OPENAPI_REDOC_URL = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js" OPENAPI_SWAGGER_UI_PATH = "/swagger-ui" OPENAPI_SWAGGER_UI_URL = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/" OPENAPI_RAPIDOC_PATH = "/rapidoc" OPENAPI_RAPIDOC_URL = "https://unpkg.com/rapidoc/dist/rapidoc-min.js" OPENAPI_RAPIDOC_CONFIG = {"theme": "dark"} ``` -------------------------------- ### Post-pagination with SQLAlchemy Cursor Pager Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Demonstrates using a custom CursorPage class for post-pagination with SQLAlchemy. The pager handles slicing, and the endpoint returns a SQLAlchemy query. ```python class CursorPage(Page): @property def item_count(self): return self.collection.count() # SQLAlchemy Query.count() @blp.route("/db") class PetsFromDB(MethodView): @blp.response(200, PetSchema(many=True)) @blp.paginate(CursorPage) def get(self): """List pets via SQLAlchemy cursor (post-pagination)""" return db.session.query(Pet) # Returns query; pager handles slicing ``` -------------------------------- ### Multiple APIs in a Single Application Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Flask-smorest supports exposing multiple independent APIs from a single Flask application by using a distinct `config_prefix` for each `Api` instance. ```APIDOC ## Multiple APIs in a Single Application ### Description This feature allows you to manage and expose multiple distinct APIs within the same Flask application. Each API can have its own configuration, including title, version, and OpenAPI specification endpoint, by assigning a unique `config_prefix` to each `Api` instance. ### Configuration Each API's configuration is prefixed. For example, `V1_API_TITLE` and `V2_API_TITLE` can be set independently. ### Example ```python from flask import Flask from flask_smorest import Api, Blueprint app = Flask(__name__) # Configuration for the first API (v1) app.config.update({ "V1_API_TITLE": "Pet Store API v1", "V1_API_VERSION": "v1", "V1_OPENAPI_VERSION": "3.0.2", "V1_OPENAPI_URL_PREFIX": "/v1", "V1_OPENAPI_SWAGGER_UI_PATH": "/swagger-ui", "V1_OPENAPI_SWAGGER_UI_URL": "https://cdn.jsdelivr.net/npm/swagger-ui-dist/" }) # Configuration for the second API (v2) app.config.update({ "V2_API_TITLE": "Pet Store API v2", "V2_API_VERSION": "v2", "V2_OPENAPI_VERSION": "3.0.2", "V2_OPENAPI_URL_PREFIX": "/v2", "V2_OPENAPI_SWAGGER_UI_PATH": "/swagger-ui", "V2_OPENAPI_SWAGGER_UI_URL": "https://cdn.jsdelivr.net/npm/swagger-ui-dist/" }) # Initialize Api instances with different config prefixes api_v1 = Api(app, config_prefix="V1_") api_v2 = Api(app, config_prefix="V2_") # Define blueprints for each API blp_v1 = Blueprint("pets_v1", "pets", url_prefix="/v1/pets") blp_v2 = Blueprint("pets_v2", "pets", url_prefix="/v2/pets") # Register blueprints with their respective Api instances api_v1.register_blueprint(blp_v1) api_v2.register_blueprint(blp_v2) # Access Swagger UI for v1: GET /v1/swagger-ui # Access Swagger UI for v2: GET /v2/swagger-ui ``` ``` -------------------------------- ### Blueprint - Define and Group API Resources Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Blueprint extends Flask's Blueprint with decorators for request/response schema binding and OpenAPI documentation. Resources are grouped under a blueprint that becomes a tag in the generated spec. ```APIDOC ## Blueprint — Define and Group API Resources `Blueprint` extends Flask's `Blueprint` with decorators for request/response schema binding and OpenAPI documentation. Resources are grouped under a blueprint that becomes a tag in the generated spec. Use `Api.register_blueprint` (not Flask's native one) to include documentation registration. ```python from flask import Flask from flask.views import MethodView import marshmallow as ma from flask_smorest import Api, Blueprint, abort app = Flask(__name__) app.config.update({ "API_TITLE": "Pet Store", "API_VERSION": "v1", "OPENAPI_VERSION": "3.0.2" }) api = Api(app) class PetSchema(ma.Schema): id = ma.fields.Int(dump_only=True) name = ma.fields.String(required=True) breed = ma.fields.String() class PetQueryArgsSchema(ma.Schema): name = ma.fields.String() breed = ma.fields.String() blp = Blueprint("pets", "pets", url_prefix="/pets", description="Operations on pets") @blp.route("/") class Pets(MethodView): @blp.arguments(PetQueryArgsSchema, location="query") @blp.response(200, PetSchema(many=True)) def get(self, args): """List pets""" return Pet.get(filters=args) @blp.arguments(PetSchema) @blp.response(201, PetSchema) def post(self, new_data): """Add a new pet""" return Pet.create(**new_data) @blp.route("/") class PetsById(MethodView): @blp.response(200, PetSchema) def get(self, pet_id): """Get pet by ID""" try: return Pet.get_by_id(pet_id) except NotFoundError: abort(404, message="Pet not found.") @blp.arguments(PetSchema) @blp.response(200, PetSchema) def put(self, update_data, pet_id): """Update existing pet""" try: item = Pet.get_by_id(pet_id) except NotFoundError: abort(404, message="Pet not found.") item.update(update_data) return item @blp.response(204) def delete(self, pet_id): """Delete pet""" try: Pet.delete(pet_id) except NotFoundError: abort(404, message="Pet not found.") api.register_blueprint(blp) ``` ``` -------------------------------- ### Multiple APIs in a Single Flask Application Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Expose multiple independent APIs from a single Flask application by using a distinct `config_prefix` for each `Api` instance. This allows each API to have its own configuration and OpenAPI spec endpoint. ```python from flask import Flask from flask_smorest import Api, Blueprint app = Flask(__name__) app.config.update({ "V1_API_TITLE": "Pet Store API", "V1_API_VERSION": "v1", "V1_OPENAPI_VERSION": "3.0.2", "V1_OPENAPI_URL_PREFIX": "/v1", "V1_OPENAPI_SWAGGER_UI_PATH": "/swagger-ui", "V1_OPENAPI_SWAGGER_UI_URL": "https://cdn.jsdelivr.net/npm/swagger-ui-dist/", "V2_API_TITLE": "Pet Store API", "V2_API_VERSION": "v2", "V2_OPENAPI_VERSION": "3.0.2", "V2_OPENAPI_URL_PREFIX": "/v2", "V2_OPENAPI_SWAGGER_UI_PATH": "/swagger-ui", "V2_OPENAPI_SWAGGER_UI_URL": "https://cdn.jsdelivr.net/npm/swagger-ui-dist/", }) api_v1 = Api(app, config_prefix="V1_") api_v2 = Api(app, config_prefix="V2_") blp_v1 = Blueprint("pets_v1", "pets", url_prefix="/v1/pets") blp_v2 = Blueprint("pets_v2", "pets", url_prefix="/v2/pets") api_v1.register_blueprint(blp_v1) api_v2.register_blueprint(blp_v2) # Swagger UI for v1: GET /v1/swagger-ui # Swagger UI for v2: GET /v2/swagger-ui ``` -------------------------------- ### Set Custom ETag Data Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Shows how to override the automatically computed ETag with custom data using blp.set_etag. This is useful for using arbitrary data, like a timestamp, as the ETag source. ```python # ETag computed from arbitrary data (e.g., last-modified timestamp) @blp.route("/") @blp.etag class Pets(MethodView): @blp.response(200, PetSchema(many=True)) def get(self): pets = Pet.get_all() # Override automatic ETag with custom data blp.set_etag([p.updated_at.isoformat() for p in pets]) return pets ``` -------------------------------- ### Serialize and Document Responses with Blueprint.response Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Blueprint.response serializes the view function's return value using a marshmallow Schema and sets the HTTP status code. Pass many=True for lists, omit schema for empty responses, and use alt_response for additional non-nominal codes. ```python import marshmallow as ma from flask import Response from flask_smorest import Blueprint blp = Blueprint("pets", "pets", url_prefix="/pets") class PetSchema(ma.Schema): id = ma.fields.Int(dump_only=True) name = ma.fields.String() # Single object response @blp.route("/") @blp.response(200, PetSchema) def get_pet(pet_id): return Pet.get_by_id(pet_id) # List response @blp.route("/") @blp.response(200, PetSchema(many=True)) def list_pets(): return Pet.get_all() # Empty 204 response @blp.route("/", methods=["DELETE"]) @blp.response(204) def delete_pet(pet_id): Pet.delete(pet_id) # File (binary) response with custom content type @blp.route("/export") @blp.response(200, {"format": "binary", "type": "string"}, content_type="text/csv") def export_pets(): csv_str = Pet.export_csv() response = Response(csv_str, mimetype="text/csv") response.headers.set("Content-Disposition", "attachment", filename="pets.csv") return response # Document an alternative error response @blp.route("//transfer", methods=["POST"]) @blp.response(200, PetSchema) @blp.alt_response(409, description="Pet already transferred") def transfer_pet(pet_id): try: return Pet.transfer(pet_id) except AlreadyTransferredError: abort(409, message="Pet already transferred.") ``` -------------------------------- ### Blueprint.response Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Serializes the view function's return value using a marshmallow Schema and sets the HTTP status code. Can document alternative responses. ```APIDOC ## GET / ### Description Retrieves a specific pet by its ID. ### Method GET ### Endpoint /pets/ ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the pet. - **name** (string) - The name of the pet. ``` ```APIDOC ## GET / ### Description Lists all pets. ### Method GET ### Endpoint /pets/ ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the pet. - **name** (string) - The name of the pet. - **breed** (string) - The breed of the pet. ``` ```APIDOC ## DELETE / ### Description Deletes a specific pet by its ID. ### Method DELETE ### Endpoint /pets/ ### Response #### Success Response (204) No content. ``` ```APIDOC ## GET /export ### Description Exports a list of pets in CSV format. ### Method GET ### Endpoint /pets/export ### Response #### Success Response (200) - **binary** (string) - The CSV data of the pets. ``` ```APIDOC ## POST //transfer ### Description Transfers a specific pet. ### Method POST ### Endpoint /pets//transfer ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the pet. - **name** (string) - The name of the pet. #### Error Response (409) - **message** (string) - Description: Pet already transferred ``` -------------------------------- ### Register Custom URL Path Converters Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Custom Flask URL converters must be registered with the Api so the correct OpenAPI type is used in path parameter documentation. ```APIDOC ## Api.register_converter ### Description Registers a custom URL converter with the Api instance. This allows flask-smorest to correctly document the converter's type and format in the OpenAPI specification. ### Method `Api.register_converter(converter, converter_to_schema)` ### Parameters - **converter** (type): The custom URL converter class (e.g., `ObjectIdConverter`). - **converter_to_schema** (callable): A function that takes the converter instance and returns a dictionary representing the OpenAPI schema for the converter. ### Example ```python from werkzeug.routing import BaseConverter from flask_smorest import Api class ObjectIdConverter(BaseConverter): regex = r"[0-9a-f]{24}" def objectid_to_schema(converter): return {"type": "string", "format": "ObjectId", "example": "507f1f77bcf86cd799439011"} api.register_converter(ObjectIdConverter, objectid_to_schema) ``` ``` -------------------------------- ### Api.register_field — Document Custom Marshmallow Fields Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Registers custom Marshmallow fields with the Api instance to ensure they are correctly documented in the OpenAPI specification. ```APIDOC ## Api.register_field ### Description Document custom Marshmallow fields for OpenAPI generation. ### Method `api.register_field(field_class, type, format=None)` ### Parameters - **field_class** (type) - The custom Marshmallow field class. - **type** (string) - The OpenAPI type (e.g., "string", "number"). - **format** (string, optional) - The OpenAPI format (e.g., "ObjectId", "date-time"). ### Example Usage ```python # Registering ObjectId field api.register_field(ObjectId, "string", "ObjectId") # Registering BsonDecimal field (no specific format) api.register_field(BsonDecimal, "number") ``` ``` -------------------------------- ### Register Custom Marshmallow Field for OpenAPI Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Registers custom Marshmallow fields with the Api instance to ensure they are correctly documented in the OpenAPI specification. This maps the custom field to an OpenAPI type and format. ```python class ObjectId(ma.fields.Field): """Custom MongoDB ObjectId field""" def _serialize(self, value, attr, obj, **kwargs): return str(value) class BsonDecimal(ma.fields.Field): """Custom BSON Decimal128 field""" pass # Map to explicit type + format string api.register_field(ObjectId, "string", "ObjectId") # Map to a type only (no format) api.register_field(BsonDecimal, "number", None) ``` -------------------------------- ### Register Marshmallow Field with Flask-Smorest Source: https://context7.com/marshmallow-code/flask-smorest/llms.txt Register a custom Marshmallow field with the Api instance to ensure correct OpenAPI type and format mapping. ```python api.register_field(BsonDecimal, ma.fields.Float) ```