APIFlask
APIFlask is a lightweight Python web API framework built on top of Flask. It enhances Flask with modern API features such as automatic request validation, response formatting, OpenAPI specification generation, and interactive API documentation (Swagger UI, Redoc, Elements, etc.). It is ORM/ODM-agnostic and offers flexible data schema support through both Marshmallow schemas and Pydantic models. The current stable version is 3.1.0, and it maintains an active release cadence, closely following Flask's development.
Common errors
-
ModuleNotFoundError: No module named 'apiflask'
cause The `apiflask` library is not installed in the current Python environment.fixRun `pip install apiflask` to install the library. -
TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable.
cause Your view function returned a complex object (e.g., a custom class instance) without an `@app.output()` decorator to serialize it, or the object is not a simple dictionary/list that Flask can convert to JSON.fixDecorate your view function with `@app.output(YourSchema)` to define how the return value should be serialized to JSON. If returning a non-dict, ensure it's explicitly handled or convertible. -
werkzeug.exceptions.UnprocessableEntity: 422 Unprocessable Entity
cause This error (or similar `ValidationError` from Marshmallow/Pydantic) indicates that the request payload did not conform to the schema defined in the `@app.input()` decorator.fixCheck the API documentation for the expected input schema and ensure your request body or query parameters match it. The error response details will typically provide specifics on validation failures. -
AttributeError: 'HTTPTokenAuth' object has no attribute 'verify_apikey' (or similar auth-related AttributeError)
cause You are likely using `HTTPTokenAuth` for API key authentication on APIFlask v3.x or later, which has been deprecated and refactored.fixMigrate your API key authentication to use `APIKeyHeaderAuth`, `APIKeyCookieAuth`, or `APIKeyQueryAuth` from `apiflask.security`. -
RuntimeError: 'APIFlask' object has no attribute 'json_errors' when trying to configure JSON error handling (or similar configuration issues)
cause Accessing or setting configuration variables incorrectly, or attempting to configure features that have been renamed or refactored in newer versions.fixConsult the `APIFlask` documentation for the current version's configuration variables and their correct usage. Some settings might have moved or been replaced by `APIFlask` constructor arguments or specific decorators.
Warnings
- breaking APIFlask 3.x refactored API key authentication. Old classes like `HTTPTokenAuth` are deprecated for API keys. Instead, use `APIKeyHeaderAuth`, `APIKeyCookieAuth`, or `APIKeyQueryAuth` based on the key's location.
- breaking APIFlask 3.x dropped official support for Python 3.8 and PyPy 3.10. While it might still work, new features and fixes are not guaranteed for these versions.
- breaking In APIFlask 2.x, data passed via the `@app.input()` decorator is now injected into the view function as a keyword argument named `{location}_data` (e.g., `json_data`, `query_data`).
- gotcha APIFlask's `abort()` function (`from apiflask import abort`) automatically returns a JSON error response, which differs from Flask's default `flask.abort()` behavior (which typically returns HTML).
- gotcha When using Pydantic models for output validation with `@app.output()`, if the data returned by your view function does not conform to the specified Pydantic model, APIFlask will raise a `500 Internal Server Error` before sending the response.
- breaking APIFlask 1.2.0 introduced a breaking change where `apiflask.views.MethodView` must be used for class-based views instead of `flask.views.MethodView` to ensure proper OpenAPI spec generation and functionality.
- breaking The default status code for request validation errors changed from `400 Bad Request` to `422 Unprocessable Entity` in APIFlask 1.2.0, aligning with common API practices for semantic validation errors.
Install
-
pip install apiflask
Imports
- APIFlask
from apiflask import APIFlask
- APIBlueprint
from flask import Blueprint
from apiflask import APIBlueprint
- abort
from flask import abort
from apiflask import abort
- HTTPError
from apiflask import HTTPError
- Schema
from apiflask import Schema
- BaseModel
from pydantic import BaseModel
Quickstart
from apiflask import APIFlask
from apiflask.fields import String
from apiflask.schemas import Schema
app = APIFlask(__name__, title='My Awesome API', version='1.0.0')
class MessageSchema(Schema):
message = String(required=True, example='Hello from APIFlask')
@app.get('/')
@app.output(MessageSchema)
def index():
return {'message': 'Hello from APIFlask'}
# To run: flask --app your_app_file_name run