API

This part of the documentation covers all the interfaces of Flask-Utils

Extension

class FlaskUtils(app: Flask | None = None, register_error_handlers: bool = True)[source]

FlaskUtils extension class.

This class currently optionally register the custom error handlers found in flask_utils.errors. Call init_app() to configure the extension on an application.

Parameters:
  • app (Optional[Flask]) – Flask application instance.

  • register_error_handlers – Register the custom error handlers. Default is True.

  • register_error_handlers – bool

Example:

from flask import Flask
from flask_utils import FlaskUtils

app = Flask(__name__)
fu = FlaskUtils(app)

# or

fu = FlaskUtils()
fu.init_app(app)

Changed in version 1.0.0: The validate_params() decorator will now use the VALIDATE_PARAMS_MAX_DEPTH config variable to determine the maximum depth of the validation for dictionaries.

Example:

from flask import Flask
from flask_utils import FlaskUtils

app = Flask(__name__)
fu = FlaskUtils(app)
app.config["VALIDATE_PARAMS_MAX_DEPTH"] = 3

The VALIDATE_PARAMS_MAX_DEPTH configuration determines the maximum depth of nested dictionary validation when using the validate_params decorator. This allows fine-tuning of validation behavior for complex nested structures.

Added in version 0.5.0.

init_app(app: Flask, register_error_handlers: bool = True) None[source]
Parameters:
  • app (Flask) – The Flask application to initialize.

  • register_error_handlers (bool) – Register the custom error handlers. Default is True.

Initialize a Flask application for use with this extension instance. This must be called before any request is handled by the application.

If the app is created with the factory pattern, this should be called after the app is created to configure the extension.

If register_error_handlers is True, the custom error handlers will be registered and can then be used in routes to raise errors. This is enabled by default. The decorator validate_params() will also use the custom error handlers if set to True.

Changed in version 0.7.0: Setting register_error_handlers to True will now enable using the custom error handlers in the validate_params(). decorator.

Example:

from flask import Flask
from flask_utils import FlaskUtils

app = Flask(__name__)
fu = FlaskUtils()
fu.init_app(app)

Added in version 0.5.0.

Custom exceptions

Warning

For any of these errors to work, you need to register the error handlers in your Flask app.

To do this, you need to pass register_error_handlers=True to the FlaskUtils class or to init_app().

from flask import Flask
from flask_utils import FlaskUtils

app = Flask(__name__)
utils = FlaskUtils(app, register_error_handlers=True)

# OR

utils = FlaskUtils()
utils.init_app(app, register_error_handlers=True)
exception BadRequestError(msg: str, solution: str | None = 'Try again.')[source]

This is the BadRequestError exception class.

When raised, it will return a 400 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import BadRequestError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise BadRequestError("This is a bad request error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "BadRequestError",
        "name": "Bad Request",
        "message": "This is a bad request error.",
        "solution": "Try again."
    },
    "code": 400
}

Added in version 0.1.0.

exception ConflictError(msg: str, solution: str | None = 'Try again.')[source]

This is the ConflictError exception class.

When raised, it will return a 409 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import ConflictError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise ConflictError("This is a conflict error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "ConflictError",
        "name": "Conflict",
        "message": "This is a conflict error.",
        "solution": "Try again."
    },
    "code": 409
}

Added in version 0.1.0.

exception FailedDependencyError(msg: str, solution: str | None = 'Try again later.')[source]

This is the FailedDependencyError exception class.

When raised, it will return a 424 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import FailedDependencyError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise FailedDependencyError("This is a failed dependency error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "FailedDependencyError",
        "name": "Failed Dependency",
        "message": "This is a failed dependency error.",
        "solution": "Try again later."
    },
    "code": 424
}

Added in version 0.1.0.

exception ForbiddenError(msg: str, solution: str | None = 'Try again.')[source]

This is the ForbiddenError exception class.

When raised, it will return a 403 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import ForbiddenError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise ForbiddenError("This is a forbidden error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "ForbiddenError",
        "name": "Forbidden",
        "message": "This is a forbidden error.",
        "solution": "Try again."
    },
    "code": 403
}

Added in version 0.1.0.

exception GoneError(msg: str, solution: str | None = 'Try again later.')[source]

This is the GoneError exception class.

When raised, it will return a 410 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import GoneError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise GoneError("This is a gone error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "GoneError",
        "name": "Ressource is gone.",
        "message": "This is a gone error.",
        "solution": "Try again later."
    },
    "code": 410
}

Added in version 0.1.0.

exception NotFoundError(msg: str, solution: str | None = 'Try again.')[source]

This is the NotFoundError exception class.

When raised, it will return 404 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import NotFoundError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise NotFoundError("This is a not found error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "NotFoundError",
        "name": "Not Found",
        "message": "This is a not found error.",
        "solution": "Try again."
    },
    "code": 404
}

Added in version 0.1.0.

exception OriginIsUnreachableError(msg: str, solution: str | None = 'Try again later.')[source]

This is the OriginIsUnreachableError exception class.

When raised, it will return a 523 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import OriginIsUnreachableError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise OriginIsUnreachableError("The origin is unreachable.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "OriginIsUnreachableError",
        "name": "Origin is unreachable",
        "message": "The origin is unreachable.",
        "solution": "Try again later."
    },
    "code": 523
}

Added in version 0.1.0.

exception ServiceUnavailableError(msg: str, solution: str | None = 'Try again later.')[source]

This is the ServiceUnavailableError exception class.

When raised, it will return a 503 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import ServiceUnavailableError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise ServiceUnavailableError("This is a service unavailable error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "ServiceUnavailableError",
        "name": "Service Unavailable",
        "message": "This is a service unavailable error.",
        "solution": "Try again later."
    },
    "code": 503
}

Added in version 0.1.0.

exception UnauthorizedError(msg: str, solution: str | None = 'Try again.')[source]

This is the UnauthorizedError exception class.

When raised, it will return a 401 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import UnauthorizedError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise UnauthorizedError("This is an unauthorized error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "UnauthorizedError",
        "name": "Unauthorized",
        "message": "This is an unauthorized error.",
        "solution": "Try again."
    },
    "code": 401
}

Added in version 0.1.0.

exception UnprocessableEntityError(msg: str, solution: str | None = 'Try again.')[source]

This is the UnprocessableEntityError exception class.

When raised, it will return a 422 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import UnprocessableEntityError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise UnprocessableEntityError("This is an unprocessable entity error.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "UnprocessableEntityError",
        "name": "Unprocessable Entity",
        "message": "This is an unprocessable entity error.",
        "solution": "Try again."
    },
    "code": 422
}

Added in version 0.1.0.

exception WebServerIsDownError(msg: str, solution: str | None = 'Try again later.')[source]

This is the WebServerIsDownError exception class.

When raised, it will return a 521 status code with the message and solution provided.

Parameters:
  • msg (str) – The message to be displayed in the error.

  • solution (Optional[str]) – The solution to the error.

Example:

from flask_utils.errors import WebServerIsDownError

# Inside a Flask route
@app.route('/example', methods=['POST'])
def example_route():
    ...
    if some_condition:
        raise WebServerIsDownError("The web server is down.")

The above code would return the following JSON response from Flask:

{
    "success": false,
    "error": {
        "type": "WebServerIsDownError",
        "name": "Web Server Is Down",
        "message": "The web server is down.",
        "solution": "Try again later."
    },
    "code": 521
}

Added in version 0.1.0.

Decorators

validate_params() Callable[source]

Decorator to validate request JSON body parameters.

This decorator ensures that the JSON body of a request matches the specified parameter types and includes all required parameters.

Raises:

BadRequestError – If the JSON body is malformed, the Content-Type header is missing or incorrect, required parameters are missing, or parameters are of the wrong type.

Example:

from flask import Flask, request
from typing import List, Dict
from flask_utils.decorators import validate_params
from flask_utils.errors import BadRequestError

app = Flask(__name__)

@app.route("/example", methods=["POST"])
@validate_params()
def example(name: str, age: int, is_student: bool, courses: List[str], grades: Dict[str, int]):
    """
    This route expects a JSON body with the following:
        - name: str
        - age: int (optional)
        - is_student: bool
        - courses: list of str
        - grades: dict with str keys and int values
    """
    # Use the data in your route
    ...

Tip

You can use any of the following types:
  • str

  • int

  • float

  • bool

  • List

  • Dict

  • Any

  • Optional

  • Union

Warning

If a parameter exists both in the route parameters and in the JSON body, the value from the JSON body will override the route parameter. A warning is issued when this occurs.

Example:

from flask import Flask, request
from typing import List, Dict
from flask_utils.decorators import validate_params
from flask_utils.errors import BadRequestError

app = Flask(__name__)

@app.route("/users/<int:user_id>", methods=["POST"])
@validate_params()
def create_user(user_id: int):
    print(f"User ID: {user_id}")
    return "User created"

...

requests.post("/users/123", json={"user_id": 456})
# Output: User ID: 456

Changed in version 1.0.0: The decorator doesn’t take any parameters anymore, it loads the types and parameters from the function signature as well as the Flask route’s slug parameters.

Changed in version 0.7.0: The decorator will now use the custom error handlers if register_error_handlers has been set to True when initializing the FlaskUtils extension.

Added in version 0.2.0.

Utilities

is_it_true(value: str) bool[source]

This function checks if a string value is true. Useful for flask’s request.form.get() method and request.args.get() method

Parameters:

value (str) – String value to check if it is true

Returns:

True if value is true, False otherwise

Return type:

bool

Example:

from flask_utils import is_it_true

@app.route('/example', methods=['GET'])
def example():
    is_ordered = request.args.get('is_ordered', type=is_it_true, default=False)

This allows your API to accept these kind of requests:

import requests

response = requests.get('http://localhost:5000/example?is_ordered=true')
print(response.json())  # True

response = requests.get('http://localhost:5000/example?is_ordered=1')
print(response.json())  # True

response = requests.get('http://localhost:5000/example?is_ordered=yes')
print(response.json())  # True

Added in version 0.4.0.

Private API

_is_optional(type_hint: Type) bool[source]

Check if the type hint is Optional.

Parameters:

type_hint (Type) – Type hint to check.

Returns:

True if the type hint is Optional, False otherwise.

Return type:

bool

Example:

from typing import Optional
from flask_utils.decorators import _is_optional

_is_optional(Optional[str])  # True
_is_optional(str)  # False

Added in version 0.2.0.

_is_allow_empty(value: Any, type_hint: Type) bool[source]

Determine if the value is considered empty and whether it’s allowed.

Parameters:
  • value (Any) – Value to check.

  • type_hint (Type) – Type hint to check against.

Returns:

True if the value is empty and allowed, False otherwise.

Return type:

bool

Example:

from typing import Optional
from flask_utils.decorators import _is_allow_empty

_is_allow_empty(None, str, False)  # False
_is_allow_empty("", str, False)  # False
_is_allow_empty(None, Optional[str], False)  # True
_is_allow_empty("", Optional[str], False)  # True
_is_allow_empty("", Optional[str], True)  # True
_is_allow_empty("", str, True)  # True
_is_allow_empty([], Optional[list], False)  # True

Added in version 0.2.0.

_check_type(value: Any, expected_type: Type, curr_depth: int = 0) bool[source]

Check if the value matches the expected type, recursively if necessary.

Parameters:
  • value (Any) – Value to check.

  • expected_type (Type) – Expected type.

  • curr_depth (int) – Current depth of the recursive check.

Returns:

True if the value matches the expected type, False otherwise.

Return type:

bool

Example:

from typing import List, Dict
from flask_utils.decorators import _check_type

_check_type("hello", str)  # True
_check_type(42, int)  # True
_check_type(42.0, float)  # True
_check_type(True, bool)  # True
_check_type(["hello", "world"], List[str])  # True
_check_type({"name": "Jules", "city": "Rouen"}, Dict[str, str])  # True

It also works recursively:

from typing import List, Dict
from flask_utils.decorators import _check_type

_check_type(["hello", "world"], List[str])  # True
_check_type(["hello", 42], List[str])  # False
_check_type([{"name": "Jules", "city": "Rouen"},
    {"name": "John", "city": "Paris"}], List[Dict[str, str]])  # True
_check_type([{"name": "Jules", "city": "Rouen"},
    {"name": "John", "city": 42}], List[Dict[str, str]])  # False

Added in version 0.2.0.

_generate_error_json(error: _BaseFlaskException, status_code: int) Response[source]

This function is used to generate a json of the error passed

Parameters:
  • error (_BaseFlaskException) – The error containing the message and solution

  • status_code (int) – The status code of the error.

Returns:

Returns a json containing all the info

Return type:

flask.Response

Example:

from flask_utils.errors import _BaseFlaskException
from flask_utils.errors._error_template import _generate_error_json

class MyError(_BaseFlaskException):
    self.name = "MyError"
    self.msg = msg
    self.solution = solution
    self.status_code = 666

error = MyError("This is an error", "This is the solution")

json = _generate_error_json(error, 666)

Added in version 0.1.0.

_register_error_handlers(application: Flask) None[source]

This function will register all the error handlers for the application

Parameters:

application (flask.Flask) – The Flask application to register the error handlers

Returns:

None

Return type:

None

Changed in version 0.5.0: Made the function private. If you want to register the custom error handlers, you need to pass register_error_handlers=True to the FlaskUtils class or to init_app()

from flask import Flask
from flask_utils import FlaskUtils

app = Flask(__name__)
utils = FlaskUtils(app)

# OR

utils = FlaskUtils()
utils.init_app(app)

Added in version 0.1.0.