Skip to main content

Flask JSONAPI Trivial

Provides Flask with very basic compliance with JSONAPI.org. It enables easy construction of APIs that return JSON.

Statuses or exceptions generated by the following modules are automatically transformed to JSONAPI while keeping the correct HTTP headers:

  • http.HTTPStatus
  • Jose (for JWT exceptions)
  • Werkzeug (for Flask itself)

Note, all exceptions raised by Jose (for JWT exceptions) are converted to Werkzeug Unauthorized 401 exceptions. Extra information about the JWT error is added to the returned JSON.

Example

from flask import Flask, abort
from flask_jsonapi_trivial import jsonapi, JsonApiModel
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from werkzeug import exceptions
import json

db = SQLAlchemy()
app = Flask(__name__)

# Add the @jsonapi decorator and return a
# status or exception, plus optional JSON
# object. Only keys 'meta', 'included',
# 'data', and 'links' are taken from this
# JSON object. Anything else is ignored.
@app.route("/")
@jsonapi
def hello_world():
    return HTTPStatus.OK, { "meta": "Hello, world!" }

# Get Flask to return JSON for exceptions.
# Exceptions raised Werkzeug and Jose
# are supported, as well as all HTTPStatus types.
@app.errorhandler(jose.exceptions.JWTError)
@app.errorhandler(exceptions.NotImplemented)
def custom_error_handler(e):
    return jsonapi_response(e)

# Standard errors can simply be raised, the
# custom error handler catches them.
@app.route('/raise')
def raise_error():
    raise exceptions.NotImplemented

# Errors can simply be returned as well:
@app.route('/show_error')
@jsonapi
def show_error():
    return exceptions.ImATeapot


# Flask abort() will return JSON if the error
# handler has been registered, provided it is
# called with an appropriate numerical code.
@app.route('/abort')
@jsonapi
def flask_abort():
    abort(exceptions.NotImplemented.code)


# flask_jsonapi_trivial allows standard database
# models to easily expose a jsonapi() method
# simply by extending JsonApiModel class.
# The class needs to implement a json()
# method which needs to return a dict JSON
# representation. Appropriate formatting is
# up to you -- see below for an example.
class MyModel(db.Model, JsonApiModel):
    __tablename__ = 'my_table'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self):
        self.id = None
        self.name = "Default Name"
        self.last_seen = datetime.utcnow()

    def json(self):
        if self.id is not None:
            self.id = str(self.id)
        if self.name is not None:
            self.name = str(self.name)
        return {
            "id": self.id,
            "name": self.name,
            "last_seen": json.loads(json.dumps(self.last_seen,default=str))
        }

# Then it's simple to return the JSON representation
# of the model. Correct headers etc are taken care of.
@app.route('/show_model')
@jsonapi
def show_model():
    model = MyModel()
    model.id = 1
    model.name = "Whom So Ever"
    return HTTPStatus.OK, model.jsonapi()

# The method jsonapi_limited() strips all detail
# from the model, leaving the keys intact. Any "id"
# field is removed unless specified.
@app.route('/show_limited_model')
@jsonapi
def show_limited_model():
    model = MyModel()
    model.id = 999
    model.name = "Limited Model"
    return HTTPStatus.OK, model.jsonapi_limited(show_id=True)

Metadata

Release files for flask-jsonapi-trivial 0.2.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flask-jsonapi-trivial 0.2.5
File Size Uploaded Provenance Actions
flask_jsonapi_trivial-0.2.5.tar.gz 5.6 kB Without provenance Details for flask_jsonapi_trivial-0.2.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flask-jsonapi-trivial 0.2.5
File Interpreter ABI Platform Actions
flask_jsonapi_trivial-0.2.5-py3-none-any.whl Python 3 none any Details for flask_jsonapi_trivial-0.2.5-py3-none-any.whl

Total release size: 18.1 kB

Release files / flask_jsonapi_trivial-0.2.5.tar.gz

Download URL flask_jsonapi_trivial-0.2.5.tar.gz
Size 5.6 kB
Tags Source
SHA-256 checksum
How to use checksums
150b93f783834f1a69efe4e2f0a0c82bfaa39e8725514c7c0d13590b5735e68b
BLAKE2b-256 checksum
How to use checksums
1ca8cab52fdaf626f305bf0a2677530638327d17da3a6984e762606ed4c431fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.1.0 requests-toolbelt/0.9.1 tqdm/4.47.0 CPython/3.6.9

Release files / flask_jsonapi_trivial-0.2.5-py3-none-any.whl

Download URL flask_jsonapi_trivial-0.2.5-py3-none-any.whl
Size 12.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2d7815d411b186dddad661d28c055a27d0faf998d02527efe8a7f969d3d51b74
BLAKE2b-256 checksum
How to use checksums
442140c53f0fb1f7a5486c62d3e78adfc6bdae1510685a54b6bf862fe6a09690
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.1.0 requests-toolbelt/0.9.1 tqdm/4.47.0 CPython/3.6.9

Security for flask-jsonapi-trivial 0.2.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.5 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page